markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
**Summary**- The user visit count is very high for Chrome but Firefox users have genereted more revenue Device Category
count_mean('device.deviceCategory',"#FF851B","#FF4136")
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- Desktop site has generated more user count as well as more revenue- One thing to note is tablet users have generated almost same revenue as mobile users Operating system
count_mean('device.operatingSystem',"#80DEEA","#0097A7")
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- Less chrome OS users but high revenue is generated.-For windows phone users also generated good revenue. Continent Based
count_mean('geoNetwork.continent',"#F48FB1","#C2185B")
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- African Users have generated more than a billion mean revenue.- Users from american have used the website a lot but didnt purchased products. Country Based
data = train_df[['geoNetwork.country','totals.transactionRevenue']][(train_df['totals.transactionRevenue'] >1)] temp = data.groupby('geoNetwork.country',as_index=False)['totals.transactionRevenue'].mean() temp['code'] = 'sample' for i,country in enumerate(temp['geoNetwork.country']): mapping = {country.name: countr...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- We can see the revenue generated based on the countries- only 4 countries in africa have generated huge mean revenue. Metro Based
count_mean('geoNetwork.metro',"#CE93D8", "#7B1FA2")
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- Most of the users metro location is not present in the dataset.- may be we have to assume some hypothesis here Network Domain
count_mean('geoNetwork.networkDomain','#90CAF9','#1976D2')
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- Most users who generate revenue uses digitalwest.net- Again same we have huge users count from unknown source/ (not set) Region
count_mean('geoNetwork.region','#DCE775','#AFB42B')
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
** Summary**- Tokyo has generated more than 1 Billion mean revenue Sub Continent Based
count_mean('geoNetwork.subContinent','#FFE082','#FFA000')
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- No surprise Africa stands top in mean revenue Page view V/S bounces
train_df['totals.pageviews'] = train_df['totals.pageviews'].fillna(0).astype('int32') train_df['totals.bounces'] = train_df['totals.bounces'].fillna(0).astype('int32') pageview = train_df.groupby('date')['totals.pageviews'].apply(lambda x:x[x >= 1].count()).reset_index() bounce = train_df.groupby('date')['totals.bounc...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- We can see the based on pageview we have increase/decrease of bounce rate new cusotmer or old customer
train_df['totals.newVisits'] = train_df['totals.newVisits'].fillna(0).astype('int32') train_df['totals.hits'] = train_df['totals.hits'].fillna(0).astype('int32') newvisit = train_df.groupby('date')['totals.newVisits'].apply(lambda x:x[x == 1].count()).reset_index() oldVisit = train_df.groupby('date')['totals.newVisits...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
** Summary **- Out of all the hits we have more new visit than old visit- That means the returning customer is very less than the new customers.- Or there can be other meaning. Minmum & maximum revenue on daily basis
temp = train_df[(train_df['totals.transactionRevenue'] >0)] data = temp[['totals.transactionRevenue','date']].groupby('date')['totals.transactionRevenue'].agg(['min','max']).reset_index() mean = go.Scatter(x = data['date'], y = data['min'],name = "Min",marker = dict(color = '#00E676')) count = go.Scatter(x = data['date...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
** Summary **- I have removed all the non-zero transaction.- This graph is to understand the minimum and maximum revenue the company generates.- 5th april the company generated the maximum revenue.- there are few days where the maximum and minimum revenue are same(Eg - 15 Jan 2017) Revenue based on month
train_df['month'] = train_df['date'].dt.month train_df['day'] = train_df['date'].dt.day train_df['weekday'] = train_df['date'].dt.weekday temp = train_df.groupby('month')['totals.transactionRevenue'].agg(['count','mean']).reset_index() count_chart = go.Bar(x = temp['month'], y = temp['count'],name = 'Count',marker = di...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
** Summary **- It is seen that November month has higest number of visitors but the transaction generated in that month is very low.- April month has generated higest mean revenue while its visitors are not high. Revenue based on day
temp = train_df.groupby('day')['totals.transactionRevenue'].agg(['count','mean']).reset_index() count_chart = go.Bar(x = temp['day'], y = temp['count'],name = 'Count', marker = dict(color = '#1DE9B6')) mean_chart = go.Bar(x = temp['day'],y = temp['mean'], name = 'Mean', marker = dict(color = '#00796B')) fig = tools.ma...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
** Summary **- It is seen that on 31th day the view count is very less I dont blame any because only Jan, Mar, May, Jul, Aug, Oct, Dec has 31 days.- But the intresting fact is that the 2nd highest mean revenue is on day 31st.- I think it can either be because of Jan or Dec as they are the start or end of the year. Rev...
temp = train_df.groupby('weekday')['totals.transactionRevenue'].agg(['count','mean']).reset_index() count_chart = go.Bar(x = temp['weekday'], y = temp['count'],name = 'Count', marker = dict(color = '#9575CD')) mean_chart = go.Bar(x = temp['weekday'],y = temp['mean'], name = 'Mean', marker = dict(color = '#B388FF')) fi...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
** Summary **- Most of the revenue is generated on monday.- very less revenue is generated on weekend. Most Ad Content
train_df['trafficSource.adContent'] = train_df['trafficSource.adContent'].fillna('') wordcloud2 = WordCloud(width=800, height=400).generate(' '.join(train_df['trafficSource.adContent'])) plt.figure( figsize=(15,20)) plt.imshow(wordcloud2) plt.axis("off") plt.show()
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
** Summary **- Image speak for it self Keywords used by users
train_df['trafficSource.keyword'] = train_df['trafficSource.keyword'].fillna('') wordcloud2 = WordCloud(width=800, height=400).generate(' '.join(train_df['trafficSource.keyword'])) plt.figure( figsize=(20,20) ) plt.imshow(wordcloud2) plt.axis("off") plt.show()
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
Source from where users came
train_df['trafficSource.source'] = train_df['trafficSource.source'].fillna('') wordcloud2 = WordCloud(width=800, height=400).generate(' '.join(train_df['trafficSource.source'])) plt.figure( figsize=(15,20) ) plt.imshow(wordcloud2) plt.axis("off") plt.show()
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
Facial Keypoint Detection This project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working wit...
# import the required libraries import glob import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.image as mpimg import cv2 key_pts_frame = pd.read_csv('data/training_frames_keypoints.csv') n = 0 image_name = key_pts_frame.iloc[n, 0] key_pts = key_pts_frame.iloc[n, 1:].as_...
Number of images: 3462
MIT
1. Load and Visualize Data.ipynb
royveshovda/P1_Facial_Keypoints
Look at some imagesBelow, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape.
def show_keypoints(image, key_pts): """Show image with keypoints""" plt.imshow(image) plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='.', c='m') # Display a few different types of images by changing the index n # select an image by index in our data frame n = 5 image_name = key_pts_frame.iloc[n, 0...
/home/roy/anaconda3/envs/cvnd/lib/python3.6/site-packages/ipykernel_launcher.py:6: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
MIT
1. Load and Visualize Data.ipynb
royveshovda/P1_Facial_Keypoints
Dataset class and TransformationsTo prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html). Dataset class``torch.utils.data.Dataset`...
from torch.utils.data import Dataset, DataLoader class FacialKeypointsDataset(Dataset): """Face Landmarks dataset.""" def __init__(self, csv_file, root_dir, transform=None): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory...
_____no_output_____
MIT
1. Load and Visualize Data.ipynb
royveshovda/P1_Facial_Keypoints
Now that we've defined this class, let's instantiate the dataset and display some images.
# Construct the dataset face_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv', root_dir='data/training/') # print some stats about the dataset print('Length of dataset: ', len(face_dataset)) # Display a few of the images from the dataset num_to_displa...
0 (157, 136, 3) (68, 2) 1 (295, 261, 3) (68, 2) 2 (147, 165, 3) (68, 2)
MIT
1. Load and Visualize Data.ipynb
royveshovda/P1_Facial_Keypoints
TransformsNow, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors.Therefore, we will need to write some pre-processing code.L...
import torch from torchvision import transforms, utils # tranforms class Normalize(object): """Convert a color image to grayscale and normalize the color range to [0,1].""" def __call__(self, sample): image, key_pts = sample['image'], sample['keypoints'] image_copy = np.copy(i...
_____no_output_____
MIT
1. Load and Visualize Data.ipynb
royveshovda/P1_Facial_Keypoints
Test out the transformsLet's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescal...
# test out some of these transforms rescale = Rescale(100) crop = RandomCrop(50) composed = transforms.Compose([Rescale(250), RandomCrop(224)]) # apply the transforms to a sample image test_num = 500 sample = face_dataset[test_num] fig = plt.figure() for i, tx in enumerate([rescale, cro...
/home/roy/anaconda3/envs/cvnd/lib/python3.6/site-packages/ipykernel_launcher.py:31: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
MIT
1. Load and Visualize Data.ipynb
royveshovda/P1_Facial_Keypoints
Create the transformed datasetApply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size).
# define the data tranform # order matters! i.e. rescaling should come before a smaller crop data_transform = transforms.Compose([Rescale(250), RandomCrop(224), Normalize(), ToTensor()]) # create the transfor...
Number of images: 3462 0 torch.Size([1, 224, 224]) torch.Size([68, 2]) 1 torch.Size([1, 224, 224]) torch.Size([68, 2]) 2 torch.Size([1, 224, 224]) torch.Size([68, 2]) 3 torch.Size([1, 224, 224]) torch.Size([68, 2]) 4 torch.Size([1, 224, 224]) torch.Size([68, 2])
MIT
1. Load and Visualize Data.ipynb
royveshovda/P1_Facial_Keypoints
Processor temperatureWe have a temperature sensor in the processor of our company's server. We want to analyze the data provided to determinate whether we should change the cooling system for a better one. It is expensive and as a data analyst we cannot make decisions without a basis.We provide the temperatures measur...
# import import matplotlib.pyplot as plt %matplotlib inline # axis x, axis y y = [33,66,65,0,59,60,62,64,70,76,80,81,80,83,90,79,61,53,50,49,53,48,45,39] x = list(range(len(y))) # plot plt.plot(x, y) plt.axhline(y=70, linewidth=1, color='r') plt.xlabel('hours') plt.ylabel('Temperature ºC') plt.title('Temperatures of ...
_____no_output_____
Unlicense
temperature/temperature.ipynb
Gayushka/data-prework-labs
ProblemIf the sensor detects more than 4 hours with temperatures greater than or equal to 70ºC or any temperature above 80ºC or the average exceeds 65ºC throughout the day, we must give the order to change the cooling system to avoid damaging the processor.We will guide you step by step so you can make the decision by...
# assign a variable to the list of temperatures # 1. Calculate the minimum of the list and print the value using print() print('minimum value: ',min(y)) # 2. Calculate the maximum of the list and print the value using print() print('maximum value: ', max(y)) # 3. Items in the list that are greater than 70ºC and prin...
minimum value: 33 maximum value: 90 Temps greater than 70C: 76 80 81 80 83 90 79 Mean temperature: 62.854166666666664 Estimate #1: 62.854166666666664 Estimate #2: 62.5 Updated list: [33, 66, 65, 62.5, 59, 60] Farenheight temps: [91.4, 150.8, 149.0, 144.5, 138.2, 140.0, 143.6, 147.2, 158.0, 168.8, 176.0, 177...
Unlicense
temperature/temperature.ipynb
Gayushka/data-prework-labs
Take the decisionRemember that if the sensor detects more than 4 hours with temperatures greater than or equal to 70ºC or any temperature higher than 80ºC or the average was higher than 65ºC throughout the day, we must give the order to change the cooling system to avoid the danger of damaging the equipment:* more tha...
# Print True or False depending on whether you would change the cooling system or not hours_over = 0 for temp in y: if temp >= 70: hours_over += 1 if hours_over > 4: print('Change Cooling System: ', True) break for temp in y: if temp > 80: print('Change Cooling ...
Change Cooling System: True Change Cooling System: True
Unlicense
temperature/temperature.ipynb
Gayushka/data-prework-labs
Future improvements1. We want the hours (not the temperatures) whose temperature exceeds 70ºC2. Condition that those hours are more than 4 consecutive and consecutive, not simply the sum of the whole set. Is this condition met?3. Average of each of the lists (ºC and ºF). How they relate?4. Standard deviation of each o...
# 1. We want the hours (not the temperatures) whose temperature exceeds 70ºC hours = [] for i in range(len(y)): if y[i] > 70: hours.append(i) hours # 2. Condition that those hours are more than 4 consecutive and consecutive, not simply the sum of the whole set. #Is this condition met? previous = 0 cons...
14.632639861130853 26.338751750035534
Unlicense
temperature/temperature.ipynb
Gayushka/data-prework-labs
Analysis regarding the emissions impact**(these are the informations on the model after running this notebook right after "westeros_LEDS_baseline.ipynb". if you're running it after "westeros_LEDS_diffusion_baseline.ipynb", please jump two cells further)**Here we add the emission bounds and I added a carbon footprint f...
import pandas as pd import ixmp import message_ix from message_ix.utils import make_df %matplotlib inline mp = ixmp.Platform() model = 'Westeros with LEDs' base = message_ix.Scenario(mp, model=model, scenario='baseline') scen = base.clone(model, 'emission_bound','introducing an upper bound on emissions', ...
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Introducing Emissions
# first we introduce the emission of CO2 and the emission category GHG scen.add_set('emission', 'CO2') scen.add_cat('emission', 'GHG', 'CO2') # we now add CO2 emissions to the coal powerplant base_emission_factor = { 'node_loc': country, 'year_vtg': vintage_years, 'year_act': act_years, 'mode': 'standa...
INFO:root:unit `tCO2/kWa` is already defined in the platform instance INFO:root:unit `MtCO2` is already defined in the platform instance
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Now we add emission factor for bulbs and LEDs as well [https://www.carbonfootprint.com/energyconsumption.html](https://www.carbonfootprint.com/energyconsumption.html)
emission_factor = make_df(base_emission_factor, technology= 'bulb', emission= 'CO2', value = 0.63) scen.add_par('emission_factor', emission_factor) emission_factor = make_df(base_emission_factor, technology= 'led', emission= 'CO2', value = 0.055) scen.add_par('emission_factor', emission_factor)
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Define a Bound on EmissionsThe `type_year: cumulative` assigns an upper bound on the *weighted average of emissions* over the entire time horizon.
scen.add_par('bound_emission', [country, 'GHG', 'all', 'cumulative'], value=500., unit='MtCO2')
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Time to Solve the Model
scen.commit(comment='introducing emissions and setting an upper bound') scen.set_as_default() scen.solve()
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
To compare: without emissions bounds: 238'193 With emissions bounds but without any CO2 impact for the light: 336'222
scen.var('OBJ')['lvl']
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Plotting Results
from tools import Plots p = Plots(scen, country, firstyear=700)
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
ActivityHow much energy is generated in each time period from the different potential sources?
p.plot_activity(baseyear=True, subset=['coal_ppl', 'wind_ppl'])
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Here we can se the part of LEDs per year
p.plot_activity(baseyear=True, subset=['bulb', 'led'])
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
CapacityHow much capacity of each plant is installed in each period?
p.plot_capacity(baseyear=True, subset=['coal_ppl', 'wind_ppl'])
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Electricity PriceAnd how much does the electricity cost? These prices are in fact **shadow prices** taken from the **dual variables** of the model solution. They reflect the marginal cost of electricity generation (i.e., the additional cost of the system for supplying one more unit of electricity), which is in fact th...
p.plot_prices(subset=['light'], baseyear=True)
INFO:numexpr.utils:NumExpr defaulting to 8 threads.
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
Close the connection to the database
mp.close_db()
_____no_output_____
MIT
tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb
luciecastella/Tuto_Westeros
We will use keras and tensorflow to implement VAE ⏭
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from keras import backend as K
_____no_output_____
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
**REPARAMETERIZATION TRICK:** This sampling uses mean and logarithmic variance and sample z by using random value from normal distribution. ⚓ Reparameterization sample was first introduced [Kingma and Welling, 2013](https://arxiv.org/pdf/1312.6114.pdf) The process also defined by [Gunderson](https://gregorygundersen.co...
class Sampling(layers.Layer): """Uses (z_mean, z_log_var) to sample z, the vector encoding a digit.""" def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape=(batch, dim)) ret...
_____no_output_____
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
VAE Encoder ▶ ▶ ▶ ☕ Encoder create z_mean and z_variance, then sample z from this z_mean and z_variance using epsilon.
latent_dim = 2 # because of z_mean and z_log_variance encoder_inputs = keras.Input(shape=(28, 28, 1)) x = layers.Conv2D(32, 3, activation="relu", strides=2, padding="same")(encoder_inputs) x = layers.Conv2D(64, 3, activation="relu", strides=2, padding="same")(x) conv_shape = K.int_shape(x) #Shape of conv to be provided...
(None, 7, 7, 64) Model: "encoder" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ========================================================================================...
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
VAE Decoder ◀ ◀ ◀☁ The tied architecture (reverse architecture from encoder to decoder) is preferred in AE. There is an [explanation](https://https://stats.stackexchange.com/questions/419684/why-is-the-autoencoder-decoder-usually-the-reverse-architecture-as-the-encoder) about it.---
latent_inputs = keras.Input(shape=(latent_dim,)) x = layers.Dense(conv_shape[1] * conv_shape[2] * conv_shape[3], activation="relu")(latent_inputs) # 7x7x64 shape x = layers.Reshape((conv_shape[1],conv_shape[2], conv_shape[3]))(x) x = layers.Conv2DTranspose(64, 3, activation="relu", strides=2, padding="same")(x) x = lay...
Model: "decoder" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_7 (InputLayer) [(None, 2)] 0 ...
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
VAE MODEL ✅
class VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder self.total_loss_tracker = keras.metrics.Mean(name="total_loss") self.reconstruction_loss_tracker = keras.metrics.Mean( ...
Mounted at /content/gdrive
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
⛹ If you want to run it on your desktop, you can download [data](https://https://www.kaggle.com/nikbearbrown/tmnist-alphabet-94-characters) and read from same directory with this ipynb file
import pandas as pd df = pd.read_csv('gdrive/My Drive/DeepLearning/94_character_TMNIST.csv') #df = pd.read_csv('94_character_TMNIST.csv') print(df.shape) X = df.drop(columns={'names','labels'}) X_images = X.values.reshape(-1,28,28) X_images = np.expand_dims(X_images, -1).astype("float32") / 255
_____no_output_____
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
⚡ I tried different batch size(32,64,128,256) to train VAE model, 128 gives better result than others.
vae = VAE(encoder, decoder) vae.compile(optimizer=keras.optimizers.Adam()) vae.fit(X_images, epochs=10, batch_size=128)
_____no_output_____
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
⛳ This plot latent space plot image between **[scale_x_left , scale_x_right]** and **[scale_y_bottom, scale_y_top]**
import matplotlib.pyplot as plt def plot_latent_space(vae, n=8, figsize=12): # display a n*n 2D manifold of digits digit_size = 28 scale_x_left = 1 # If we change the range, t generate different image. scale_x_right = 4 scale_y_bottom = 0 scale_y_top = 1 figure = np.zeros((digit_size * n,...
_____no_output_____
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
♑ When we plot all the Training data with labels, we can see ***z_mean*** values of the data. ❎ If we sample with this ***z_mean*** value, we can acquire similar image from this latent space. ⭕ Because two points are close to each other in latent space means they are looking similar(variant of this label).
def plot_label_clusters(vae, data, labels): # display a 2D plot of the digit classes in the latent space z_mean, _, _ = vae.encoder.predict(data) plt.figure(figsize=(12, 12)) plt.scatter(z_mean[:, 0], z_mean[:, 1], c=labels) plt.colorbar() plt.xlabel("z[0]") plt.ylabel("z[1]") plt.show()...
/usr/local/lib/python3.7/dist-packages/sklearn/preprocessing/_label.py:115: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True)
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
⛪ Visualize one image
#Single decoded image with random input latent vector (of size 1x2) #Latent space range is about -5 to 5 so pick random values within this range sample_vector = np.array([[3,0.5]]) decoded_example = decoder.predict(sample_vector) decoded_example_reshaped = decoded_example.reshape(28, 28) plt.imshow(decoded_example_res...
_____no_output_____
Apache-2.0
VariationalAutoEncoder.ipynb
z-tufekci/DeepLearning
Markdown ¿Qué es?Lenguaje de marcado que nos permite aplicar formato a nuestros textos mediante unos caracteres especiales. Muy útil cuando tenemos que documentar algo, escribir un artículo, o entregar un reporte. Este lenguaje está pensado para web, pero es muy común utilizarlo en cualquier tipo de texto, independien...
# Esto es código de Python. # Va a ser muy habitual en el curso, acompañar el código de Python mediante celdas de markdown.
_____no_output_____
MIT
Bloque 1 - Ramp-Up/03_Markdown/RESU_Markdown en Jupyter.ipynb
JuanDG5/bootcamp_thebridge_PTSep20
Expansion velocity of the universeIn 1929, Edwin Hubble published a [paper](http://www.pnas.org/content/pnas/15/3/168.full.pdf) in which he compared the radial velocity of objects with their distance. The former can be done pretty precisely with spectroscopy, the latter is much more uncertain. His original data are [h...
import numpy as np data = np.genfromtxt('table1.txt', names=True, dtype=None) print("Samples:", len(data)) print("Data Types:", data.dtype) %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt plt.scatter(data['R'], data['V']) plt.xlabel('R [Mpc]') plt.ylabel('V [km/s]')
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Use `np.linalg.lstsq` to fit a linear regression function and determine the slope $H_0$ of the line $V=H_0 R$. For that, reshape $R$ as a $N\times1$ matrix (the design matrix) and solve for 1 unknown parameter. Add the best-fit line to the plot.
N = len(data) X = data['R'].reshape((N,1)) params, _, _, _ = np.linalg.lstsq(X, data['V']) print(params) H0 = params[0] R = np.linspace(0,2.5,100) fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(data['R'], data['V']) ax.plot(R, H0*R, 'k--') ax.set_xlim(xmin=0, xmax=2.5) ax.set_xlabel('Distance [Mpc]') ax.set_y...
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Why is there scatter with respect to the best-fit curve? Is it fair to only fit for the slope and not also for the intercept? How would $H_0$ change if you include an intercept in the fit?
X = np.ones((N, 2)) X[:,1] = data['R'] params, _, _, _ = np.linalg.lstsq(X, data['V']) print(params) inter, H0 = params R = np.linspace(0,2.5,100) fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(data['R'], data['V']) ax.plot(R, H0*R + inter, 'k--') ax.set_xlim(xmin=0, xmax=2.5) ax.set_xlabel('Distance [Mpc]') ...
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Correcting for motion of the sun$V$ as given in the table is a combination of any assumed cosmic expansion and the motion of the sun with respect to that cosmic frame. So, we need to generalize the model to $V=H_0 R + V_s$, where the solar velocity is given by $V_s = X \cos(RA)\cos(DEC) + Y\sin(RA)\cos(DEC)+Z\sin(DEC)...
import astropy.coordinates as coord import astropy.units as u pos = coord.SkyCoord(ra=data['RA'].astype('U8'), dec=data['DEC'].astype('U9'), unit=(u.hourangle,u.deg),frame='fk5') ra_ = pos.ra.to(u.deg).value * np.pi/180 dec_ = pos.dec.to(u.deg).value * np.pi/180
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Construct a new $N\times4$ design matrix for the four unknown parameters $H_0$, $X$, $Y$, $Z$ to account for the solar motion. The resulting $H_0$ is Hubble's own version of the "Hubble constant". What do you get?
Ah = np.empty((N,4)) Ah[:,0] = data['R'] Ah[:,1] = np.cos(ra_)*np.cos(dec_) Ah[:,2] = np.sin(ra_)*np.cos(dec_) Ah[:,3] = np.sin(dec_) params_h, _, _, _ = np.linalg.lstsq(Ah, data['V']) print(params_h) H0 = params_h[0]
[ 465.17797833 -67.84096674 236.14706994 -199.58892695]
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Make a scatter plot of $V-V_S$ vs $R$. How is it different from the previous one without the correction for solar velicity. Add the best-fit linear regression line.
VS = params_h[1]*Ah[:,1] + params_h[2]*Ah[:,2] + params_h[3]*Ah[:,3] fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(data['R'], data['V'] - VS) ax.plot(R, H0*R, 'k-') ax.set_xlim(xmin=0, xmax=2.5) ax.set_xlabel('Distance [Mpc]') ax.set_ylabel('Velocity [km/s]')
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Using `astropy.units`, can you estimate the age of the universe from $H_0$? Does it make sense?
H0q = H0 * u.km / u.s / u.Mpc (1./H0q).to(u.Gyr)
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Deconstructing lstsqSo far we have not incorporated any measurement uncertainties. Can you guess or estimate them from the scatter with respect to the best-fit line? You may want to look at the residuals returned by `np.linalg.lstsq`...
scatter = data['V'] - VS - H0*data['R'] fig = plt.figure() ax = fig.add_subplot(111) ax.hist(scatter, 10) ax.set_xlabel('$\Delta$V [km/s]')
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Let see how adopting a suitable value $\sigma$ for those uncertainties would affect the estimate of $H_0$?The problem you solved so far is $Ax=b$, and errors don't occur. With errors the respective equation is changed to $A^\top \Sigma^{-1} Ax=A^\top \Sigma^{-1}b$, where in this case the covariance matrix $\Sigma=\sigm...
error = scatter.std() Sigma = error**2*np.eye(N) Ae = np.dot(Ah.T, np.dot(np.linalg.inv(Sigma), Ah)) be = np.dot(Ah.T, np.dot(np.linalg.inv(Sigma), data['V'])) params_e, _, _, _ = np.linalg.lstsq(Ae, be) print(params_e)
[ 465.17797833 -67.84096674 236.14706994 -199.58892695]
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Compute the parameter covariance matrix $S=(A^\top \Sigma^{-1} A)^{-1}$ and read off the variance of $H_0$. Update your plot to illustrate that uncertainty.
S = np.linalg.inv(Ae) dH0 = np.sqrt(S[0,0]) print(dH0) fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(data['R'], data['V'] - VS) ax.plot(R, H0*R, 'k-') ax.plot(R, (H0-dH0)*R, 'k--') ax.plot(R, (H0+dH0)*R, 'k--') ax.set_xlim(xmin=0, xmax=2.5) ax.set_xlabel('Distance [Mpc]') ax.set_ylabel('Velocity [km/s]')
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
How large is the relative error? Would that help with the problematic age estimate above?
H0q = (H0-dH0) * u.km / u.s / u.Mpc (1./H0q).to(u.Gyr)
_____no_output_____
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Compare the noise-free result from above (Hubble's result) with $SA^\top \Sigma^{-1}b$. Did adopting errors change the result?
params_h, _, _, _ = np.linalg.lstsq(Ah, data['V']) print(params_h) print (np.dot(S, be))
[ 465.17797833 -67.84096674 236.14706994 -199.58892695] [ 465.17797833 -67.84096674 236.14706994 -199.58892695]
MIT
day3/solutions/Hubble-Solutions.ipynb
ishanikulkarni/usrp-sciprog
Graphical AnalysisPyevolve comes with a Graphical Plotting Tool, based on the [Matplotlib plotting library](http://matplotlib.org/).To use this graphical plotting tool, you need to use the [DBAdapters.DBSQLite](http://pyevolve.sourceforge.net/0_6rc1/module_dbadapters.html) adapter and create a database file, where the...
from pyevolve import G1DList, GSimpleGA from pyevolve import DBAdapters def eval_func(chromosome): score = 0.0 for value in chromosome: if value==0: score += 1.0 return score genome = G1DList.G1DList(20) genome.evaluator.set(eval_func) genome.setParams(rangemin=0, rangemax=10)
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
The database adapter is defined in the following cell. The database is stored in a file, and the elements need a specific identifier. We will use always the same identifier, but you could change it if you want to save different evolutions in the same database. The parameter resetDB is set for deleting any existing data...
sqlite_adapter = DBAdapters.DBSQLite(dbname='first_example.db', identify="ex1", resetDB=True)
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
When you run your GA, all the statistics will be dumped to this database. When you use the graph tool, it will read the statistics from this database file.Let's evolve the example. Now, instead of evolving step by step, we will set a number of generations for completing the evolution with a single call to ga.evolve.
ga = GSimpleGA.GSimpleGA(genome) ga.setDBAdapter(sqlite_adapter) ga.setGenerations(20) ga.evolve(freq_stats=5) print("Generation: %d" % ga.currentGeneration) best = ga.bestIndividual() print('\tBest individual: %s' % str(best.genomeList)) print('\tBest score: %.0f' % best.score)
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
PlottingHere are described the main graph types. Usually you can choose to plot the **raw** or **fitness** score, which are defined as:* The raw score represents the score returned by the [Evaluation function](http://pyevolve.sourceforge.net/0_6rc1/intro.htmlterm-evaluation-function), this score is not scaled.* The fi...
%matplotlib inline from pyevolve_plot import plot_errorbars_raw, plot_errorbars_fitness, \ plot_maxmin_raw, plot_maxmin_fitness, \ plot_diff_raw, plot_pop_heatmap_raw
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
Error bars graph (raw scores)In this graph, you will find the generations on the x-axis and the raw scores on the y-axis. The green vertical bars represents the maximum and the minimum raw scores of the current population at generation indicated in the x-axis. The blue line between them is the average raw score of the...
plot_errorbars_raw('first_example.db','ex1')
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
Error bars graph (fitness scores)The differente between this graph option and the previous one is that we are using the fitness scores instead of the raw scores.
plot_errorbars_fitness('first_example.db','ex1')
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
Max/min/avg/std. dev. graph (raw scores)In this graph we have the green line showing the maximum raw score at the generation in the x-axis, the red line shows the minimum raw score, and the blue line shows the average raw scores. The green shaded region represents the difference between our max. and min. raw scores. T...
plot_maxmin_raw('first_example.db','ex1')
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
Max/min/avg/std. dev. graph (fitness scores)This graphs shows the maximum fitness score from the population at the x-axis generation using the green line. The red line shows the minimum fitness score and the blue line shows the average fitness score from the population. The green shaded region between the green and r...
plot_maxmin_fitness('first_example.db','ex1')
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
Min/max difference graph, raw and fitness scoresIn this graph, we have two subplots, the first is the difference between the best individual raw score and the worst individual raw score. The second graph shows the difference between the best individual fitness score and the worst individual fitness score. Both subplot...
plot_diff_raw('first_example.db','ex1')
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
Heat map of population raw score distributionThe heat map graph is a plot with the population individual plotted as the x-axis and the generation plotted in the y-axis. On the right side we have a legend with the color/score relation. As you can see, on the initial populations, the last individals scores are the worst...
plot_pop_heatmap_raw('first_example.db','ex1')
_____no_output_____
MIT
Graphical Analysis.ipynb
ecervera/GA
Analysing structured data with data frames (c) 2019 [Steve Phelps](mailto:sphelps@sphelps.net) Data frames- The `pandas` module provides a powerful data-structure called a data frame.- It is similar, but not identical to: - a table in a relational database, - an Excel spreadsheet, - a dataframe in R. Ty...
import pandas as pd
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Series- A Series contains a one-dimensional array of data, *and* an associated sequence of labels called the *index*.- The index can contain numeric, string, or date/time values.- When the index is a time value, the series is a [time series](https://en.wikipedia.org/wiki/Time_series).- The index must be the same lengt...
import numpy as np data = np.random.randn(5) data my_series = pd.Series(data, index=['a', 'b', 'c', 'd', 'e']) my_series
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Plotting a series- We can plot a series by invoking the `plot()` method on an instance of a `Series` object.- The x-axis will autimatically be labelled with the series index.
import matplotlib.pyplot as plt my_series.plot() plt.show()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Creating a series with automatic index- In the following example the index is creating automatically:
pd.Series(data)
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Creating a Series from a `dict`
d = {'a' : 0., 'b' : 1., 'c' : 2.} my_series = pd.Series(d) my_series
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Indexing a series with `[]`- Series can be accessed using the same syntax as arrays and dicts.- We use the labels in the index to access each element.
my_series['b']
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
- We can also use the label like an attribute:
my_series.b
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Slicing a series- We can specify a range of labels to obtain a slice:
my_series[['b', 'c']]
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Arithmetic and vectorised functions- `numpy` vectorization works for series objects too.
d = {'a' : 0., 'b' : 1., 'c' : 2.} squared_values = pd.Series(d) ** 2 squared_values x = pd.Series({'a' : 0., 'b' : 1., 'c' : 2.}) y = pd.Series({'a' : 3., 'b' : 4., 'c' : 5.}) x + y
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Time series
dates = pd.date_range('1/1/2000', periods=5) dates time_series = pd.Series(data, index=dates) time_series
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Plotting a time-series
ax = time_series.plot()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Missing values- Pandas uses `nan` to represent missing data.- So `nan` is used to represent missing, invalid or unknown data values.- It is important to note that this only convention only applies within pandas. - Other frameworks have very different semantics for these values. DataFrame- A data frame has multiple...
series_dict = { 'x' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']), 'y' : pd.Series([4., 5., 6., 7.], index=['a', 'b', 'c', 'd']), 'z' : pd.Series([0.1, 0.2, 0.3, 0.4], index=['a', 'b', 'c', 'd']) } series_dict
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Converting the dict to a data frame
df = pd.DataFrame(series_dict) df
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Plotting data frames- When plotting a data frame, each column is plotted as its own series on the same graph.- The column names are used to label each series.- The row names (index) is used to label the x-axis.
ax = df.plot()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Indexing - The outer dimension is the column index.- When we retrieve a single column, the result is a Series
df['x'] df['x']['b'] df.x.b
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Projections- Data frames can be sliced just like series.- When we slice columns we call this a *projection*, because it is analogous to specifying a subset of attributes in a relational query, e.g. `SELECT x FROM table`.- If we project a single column the result is a series:
slice = df['x'][['b', 'c']] slice type(slice)
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Projecting multiple columns- When we include multiple columns in the projection the result is a DataFrame.
slice = df[['x', 'y']] slice type(slice)
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Vectorization- Vectorized functions and operators work just as with series objects:
df['x'] + df['y'] df ** 2
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Logical indexing- We can use logical indexing to retrieve a subset of the data.
df['x'] >= 2 df[df['x'] >= 2]
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Descriptive statistics - To quickly obtain descriptive statistics on numerical values use the `describe` method.
df.describe()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Accessing a single statistic- The result is itself a DataFrame, so we can index a particular statistic like so:
df.describe()['x']['mean']
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Accessing the row and column labels- The row labels (index) and column labels can be accessed:
df.index df.columns
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Head and tail- Data frames have `head()` and `tail()` methods which behave analgously to the Unix commands of the same name. Financial data- Pandas was originally developed to analyse financial data.- We can download tabulated data in a portable format called [Comma Separated Values (CSV)](https://www.loc.gov/preserv...
import pandas as pd googl = pd.read_csv('data/GOOGL.csv')
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Examining the first few rows- When working with large data sets it is useful to view just the first/last few rows in the dataset.- We can use the `head()` method to retrieve the first rows:
googl.head()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Examining the last few rows
googl.tail()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Converting to datetime values- So far, the `Date` attribute is of type string.
googl.Date[0] type(googl.Date[0])
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
- In order to work with time-series data, we need to construct an index containing time values.- Time values are of type `datetime` or `Timestamp`.- We can use the function `to_datetime()` to convert strings to time values.
pd.to_datetime(googl['Date']).head()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata