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
We then run the FTE/BTE experiment with normalizing per image, so that each channel in each image is scaled to a range of [0,1].
accuracy_all_task = fn.ftebte_exp( data2, classes2, model, num_tasks, num_trees, reps, shift=0 ) err, bte, fte, te = fn.get_metrics(accuracy_all_task, num_tasks) fn.plot_ftebte(num_tasks, err, bte, fte, te)
_____no_output_____
MIT
docs/experiments/recruitment_across_datasets.ipynb
AishwaryaSeth/ProgLearn
Plot the throughput of experiment 1 of version 3
import numpy as np import pandas as pd import matplotlib.pyplot as plt import requests import io import glob
_____no_output_____
MIT
PlanB/CPU_utilization_Experiment/version3_Experiment_style/Experiment1/Plot_Throughput_Experiment1.ipynb
phoophoo187/Privacy_SDN_Edge_IoT
Function Read CSV files of Throughput from Iperf log
def getDataframeThru(df,start_row,measurement_interval,header_range): ''' This functions will import the data from txt file and return the dataframe without the header of txt file. Input: measurement_interval = 30 (sec) : header_range = 10 lines start_row = 0 Return: ...
_____no_output_____
MIT
PlanB/CPU_utilization_Experiment/version3_Experiment_style/Experiment1/Plot_Throughput_Experiment1.ipynb
phoophoo187/Privacy_SDN_Edge_IoT
Read File CSV
headerrange = 7 start_data = '9.0-10.0' end_data = '60.0-61.0' tf_load = [i*2 for i in range(2,20)] edge_name = 'edge1_M' directoryPath = '/Users/kalika/PycharmProjects/Privacy_SDN_Edge_IoT/PlanB/CPU_utilization_Experiment/version3_Experiment_style/Experiment1/Edge1_iperf_log/' avg_thr, var_thr = readCSV2pd_Thru(direc...
avg [4.115769230769231, 6.169038461538463, 8.225961538461538, 10.294230769230769, 12.35576923076923, 14.419230769230772, 16.474999999999998, 18.53076923076923, 20.582692307692312, 22.63461538461538, 24.68846153846154, 26.744230769230775, 28.550000000000004, 28.500000000000004, 27.778846153846153, 28.84038461538462, 28....
MIT
PlanB/CPU_utilization_Experiment/version3_Experiment_style/Experiment1/Plot_Throughput_Experiment1.ipynb
phoophoo187/Privacy_SDN_Edge_IoT
Plot Throughput
fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(tf_load, avg_thr, color='green', linestyle='dashed', linewidth = 2, marker='o', markerfacecolor='green', markersize=10,label="Edge 1") ax.plot(tf_load, avg_thr2, color='red', linestyle='dashed', linewidth = 2, marker='x', markerfacecolor='red...
_____no_output_____
MIT
PlanB/CPU_utilization_Experiment/version3_Experiment_style/Experiment1/Plot_Throughput_Experiment1.ipynb
phoophoo187/Privacy_SDN_Edge_IoT
Linearizing with Taylor SeriesTaylor series represents a function as an infinite sum of terms. The terms are linear, even for a nonlinear function, so we can express any arbitrary nonlinear function using linear algebra. The cost of this choice is that unless we use an infinite number of terms the value we compute wil...
import numpy as np x = .3 estimate = x + x**3/6 + x**5/120 exact = np.sin(.3) print('estimate of sin(.3) is', estimate) print('exact value of sin(.3) is', exact)
estimate of sin(.3) is 0.30452025 exact value of sin(.3) is 0.29552020666133955
CC-BY-4.0
Supporting_Notebooks/Taylor-Series.ipynb
cxlldhty/Kalman-and-Bayesian-Filters-in-Python
$\newcommand{\xv}{\mathbf{x}} \newcommand{\wv}{\mathbf{w}} \newcommand{\Chi}{\mathcal{X}} \newcommand{\R}{\rm I\!R} \newcommand{\sign}{\text{sign}} \newcommand{\Tm}{\mathbf{T}} \newcommand{\Xm}{\mathbf{X}} \newcommand{\Im}{\mathbf{I}} \newcommand{\Ym}{\mathbf{Y}}$ ITCS8010 G_np Simulation ExperimentIn this experiment ...
import networkx as nx import numpy as np import matplotlib.pyplot as plt import collections as collec %matplotlib inline # Fraction of node in largest CC Vs. {p*log(n)} n = 100000 x1 = [] y1 = [] for kave in np.arange(0.5, 3.0, 0.1): G = nx.fast_gnp_random_graph(n, kave / (n - 1)) largest_cc = max(nx.connected...
_____no_output_____
MIT
assignments/assignment_0/gnp_simulation_experiment.ipynb
biqar/Fall-2020-ITCS-8010-MLGraph
Observation:1. The result of the first experiment (i.e. `fraction of node in largest CC` varying `p*(n-1)`) gives somewhat similar behaviour we observed in the class slide.2. In the second experiment (i.e. plotting `fraction of isolated nodes` on varying `p*log(n)`) gives somewhat different result comparing to the one...
# plotting degree distribution n1 = 180 p1 = 0.11 G = nx.fast_gnp_random_graph(n1, p1) degree_sequence = sorted([d for n, d in G.degree()], reverse=True) # degree sequence degreeCount = collec.Counter(degree_sequence) deg, cnt = zip(*degreeCount.items()) fig, ax = plt.subplots() plt.bar(deg, cnt, width=0.80, color...
_____no_output_____
MIT
assignments/assignment_0/gnp_simulation_experiment.ipynb
biqar/Fall-2020-ITCS-8010-MLGraph
Project 1: Babynames I. Characterise One File 1. Read the data - Read the file yob2000.txt - Name the columns - Print the first 10 entries
import pandas as pd from matplotlib import pyplot as plt popular_names = pd.read_csv('yob2000.csv', names = ['Names', 'Sex', 'Birth Count']) len(popular_names) popular_names.head(10) top_1000 = popular_names.sort_values(by = 'Birth Count', ascending=Fals...
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
2. Calculate total births - Calculate the sum of the birth count column in the file yob2000.txt.\
top_1000['Birth Count'].sum()
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
3. Separate boys / girls - Calculate separate sums for boys and girls. - Plot both sums in a bar plot
top_1000.groupby('Sex')['Birth Count'].sum() plot_boys_girls = top_1000.groupby('Sex')['Birth Count'].sum() plot_boys_girls.plot.bar() plt.ylabel('Birth Count') plt.title('Total births of females and males in Year 2000') plt.show()
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
But there's a greater amount of female names!
top_1000['Sex'].value_counts() # counts column values
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
4. Frequent names - Count how many names occur at least 1000 times in the file yob2000.txt.
top_1000[top_1000['Birth Count'] > 1000].head(10) top_1000[top_1000['Birth Count'] > 1000]['Birth Count'].count()
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
5. Relative amount - Create a new column containing the percentage of a name on the total births of that year. - Verify that the sum of percentages is 100%.
(top_1000['Birth Count']/(top_1000['Birth Count'].sum()) * 100).head() top_1000['Percentage of total count'] = top_1000['Birth Count']/(top_1000['Birth Count'].sum()) * 100 top_1000.head() top_1000['Percentage of total count'].sum().round()
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
6. Search your name - Identify and print all lines containing your name in the year 2000.
top_1000[top_1000['Names'].str.contains('Max')]
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
7. Bar plot - Create a bar plot showing 5 selected names for the year 2000.
peppermint = top_1000.set_index('Names').loc[['Max', 'Eric','Josh','Daniela','Michael']] peppermint peppermint_5 = peppermint.groupby('Names')[['Birth Count']].sum() peppermint_5 peppermint_5.plot.bar(stacked=True, colormap='Accent')
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
II. Characterize all files 1. Read all namesTo read the complete dataset, you need to loop though all file names: yob1880.txt yob1881.txt yob1882.txt ...Complete the code below by inserting _csv, data````df, names=['name', 'gender', 'count'], y and 2017: years = range(1880, ____, 10) data = [] for...
years = range(1880, 2017) data = [] for y in years: fn = f'yob{y}.txt' df = pd.read_csv(fn, names =['Names', 'Sex', 'Birth Count']) df['year'] = y data.append(df) usa_names = pd.concat(data) usa_names.head(10) len(usa_names)
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
2. Plot a time series- extract all rows containing your name from the variable df- plot the number of babies having your name and gender over time- make the plot nicer by adding row/column labels and a title- change the color and thickness of the line- save the plot as a high-resolution diagram
my_name = usa_names[(usa_names['Names']=='Max') & (usa_names['Sex'] == 'M')] my_name.head(10) my_name = my_name.set_index(['Names', 'Sex', 'year']).stack() my_name = my_name.unstack((0,1,3)) my_name.head(10) plt.plot(my_name) plt.plot(my_name, linewidth=3, color= 'red') plt.xlabel('Year') plt.ylabe...
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
3. Name diversity- Have the baby names become more diverse over time?- What assumptions is your calculation based upon?
usa_names.head(5) name_diversity = usa_names.groupby('year')[['Names']].count() name_diversity.head() plt.plot(name_diversity) plt.xlabel('Year') plt.ylabel('Number of different names') plt.title('Variation of the number of given names over time') plt.show()
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
The SSA files that we are extracting our data from are for the 'Top 1000' names, therefore, there are a certain number of unique names (names with a yearly frequency of less than 5) that will not be included in the data. Our calculation essentially assumes that the number of names that has a frequency of less than 5 i...
usa_names.head() long_names = list() for i in usa_names['Names']: long_names.append(len(i)) usa_names['Length of name'] = long_names usa_names.head(5) long_names_10 = usa_names.sort_values(by='Length of name', ascending=False).head(10) long_names_10
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
III. Plot Celebrities 1. Plotting Madonna- plot time lines of names of celebrities- try actors, presidents, princesses, Star Wars & GoT characters, boot camp participants…Hint: When was the hit single “Like a Prayer” released?
usa_names.drop(columns='Length of name').head() celebrity = usa_names[usa_names['Names'] == 'Madonna'] celebrity = celebrity.drop(columns='Length of name') celeb_stacked = celebrity.set_index(['Names', 'Sex', 'year']).stack() madonna = celeb_stacked.unstack((0,1,3)) plt.plot(madonna, linewidth=2.5) plt.xlabel('Year') ...
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
2. Total births over time- create a plot that shows the total birth rate in the U.S. over time- plot the total birth rate for girls/boys separately
year_sum = usa_names.groupby('year')['Birth Count'].sum() year_sum = pd.DataFrame(year_sum) year_sum.head() year_sum.plot() plt.xlabel('Year') plt.ylabel('Birth Count') plt.title('Total Birth Rate in the USA over time') plt.show() usa_names.head() usa_females_males = usa_names.groupby(['year','Sex'])['Birth Count'].sum...
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
3. Normalize- divide the number of births by the total number of births in each year to obtain the relative frequency- plot the time series of your name or the celebrity names again.Hint: To reshape the data for plotting, you may find a combination of df.groupby( ) and df.unstack( ) useful.
year_sum = usa_names.groupby('year')[['Birth Count']].sum().reset_index() year_sum.head() usa_names = usa_names.drop(columns='Length of name') usa_names.head()
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
 Now let's merge! Almost always 'left' and you will merge 'on' a point they have in common, eg year!Can change sufixes too!
merged_usa_names = usa_names.merge(year_sum, how='left', on='year', suffixes=('_name', '_total')) merged_usa_names.head(10) merged_usa_names['Name Rel. %'] = merged_usa_names['Birth Count_name']/merged_usa_names['Birth Count_total']*100 merged_usa_names = merged_usa_names.sort_values(...
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
II. Letter Statistics 1. First letter statistics- use df.apply(func) to add an extra column that contains the first letter of the name.- count how many names start with ‘A’.- plot the relative occurence of initials over time.- what can you conclude from your observations?Hint: You may need to iterate over the names wi...
merged_usa_names.head() def initial(name): return name[0] merged_usa_names['initial'] = merged_usa_names['Names'].apply(initial) merged_usa_names.head() merged_usa_names[merged_usa_names['initial']== 'A']['initial'].count() first_letter_sum = merged_usa_names.groupby('year')['initial'].value_counts() first_letter_...
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
2. Last letter statistics- try the same for the final character- separate by boys/girls- what can you conclude from your observations?
def last_letter(name): return name[-1] merged_usa_names['last letter'] = merged_usa_names['Names'].apply(last_letter) merged_usa_names.head(5)
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
3. e-rich Names- Find all names that contain the character ‘e’ at least four times.
usa_names.head()
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
USE .APPLY to apply a function!
def four_e(input): check = [] for i in input: if i == 'e' or i == 'E': check.append(i) return len(check) usa_names['e occurences'] = usa_names['Names'].apply(four_e) usa_names.head() many_es = usa_names[usa_names['e occurences'] > 3] many_es.head() len(many_es)
_____no_output_____
MIT
Project_1_Babynames.ipynb
maximcondon/Project_BabyNames
Classify Radio Signals from Space using KerasIn this experiment, we attempt to classify radio signals from space.Dataset has been provided by SETI. Details can be found here:https://github.com/setiQuest/ML4SETI/blob/master/tutorials/Step_1_Get_Data.ipynb Import necessary libraries
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import metrics import seaborn as sns import tensorflow as tf %matplotlib inline # Mount google drive to get data from google.colab import drive drive.mount('/content/drive') !ls -l '/content/drive/My Drive/datasets/seti'
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%2...
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
Load data
# Load dataset from CSV train_images = pd.read_csv('/content/drive/My Drive/datasets/seti/train/images.csv', header=None) train_labels = pd.read_csv('/content/drive/My Drive/datasets/seti/train/labels.csv', header=None) val_images = pd.read_csv('/content/drive/My Drive/datasets/seti/validation/images.csv', header=None)...
_____no_output_____
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
Plot 2D spectrogram data
plt.figure(figsize=(15,15)) for i in range(1,4): plt.subplot(1,3,i) img = np.squeeze(x_train[np.random.randint(x_train.shape[0])]) plt.imshow(img, cmap='gray')
_____no_output_____
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
Preprocess data
from tensorflow.keras.preprocessing.image import ImageDataGenerator datagen_train = ImageDataGenerator(horizontal_flip=True) datagen_train.fit(x_train) datagen_val = ImageDataGenerator(horizontal_flip=True) datagen_val.fit(x_val)
_____no_output_____
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
Build model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten from tensorflow.keras.layers import BatchNormalization, Dropout, Activation from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam # Initialize model model = Sequential() # 1st CNN block model.add(Conv2D(32,...
_____no_output_____
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
Compile the model
# Schedule learnning rate decay lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( 0.005, decay_steps=5, decay_rate=0.9, staircase=True) model.compile(optimizer=Adam(lr_schedule), loss='categorical_crossentropy', metrics=['accuracy']) model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 64, 128, 32) 832 ____________________________________...
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
Train the model
batch_size = 32 history = model.fit( datagen_train.flow(x_train, y_train, batch_size=batch_size, shuffle=True), steps_per_epoch=len(x_train)//batch_size, validation_data = datagen_val.flow(x_val, y_val, batch_size=batch_size, shuffle=True), validation_steps = len(x_val)//batch_size, epochs=10, )
Epoch 1/10 100/100 [==============================] - 115s 1s/step - loss: 0.5255 - accuracy: 0.7044 - val_loss: 5.4126 - val_accuracy: 0.2500 Epoch 2/10 100/100 [==============================] - 118s 1s/step - loss: 0.4004 - accuracy: 0.7391 - val_loss: 6.4884 - val_accuracy: 0.2500 Epoch 3/10 100/100 [==============...
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
Evaluation
plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['training', 'validation']) plt.show() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt....
_____no_output_____
MIT
radio-signal-classification.ipynb
biswajitpawl/radio-signal-classification
building a dask array without knowing sizes from dask.dataframe
from dask import array as da, dataframe as ddf, delayed, compute import numpy as np import pandas as pd import matplotlib.pyplot as plt da.from_delayed def get_chunk_df(array_size,n_cols): col_names = [f"col_{i}" for i in range(n_cols)] pd_df = pd.DataFrame( {nm:pd.Series(np.arange(array_size[0]...
_____no_output_____
BSD-3-Clause
notebooks/da_from_delayed_array_vs_df.ipynb
data-exp-lab/yt-dask-experiments
direct from_array?
delayed_arrays=[] for ichunk in range(0,5): ra_size = 10000+10*ichunk delayed_array = delayed(np.arange)(ra_size) delayed_arrays.append(da.from_delayed(delayed_array, (ra_size,), dtype=float)) delayed_arrays hda = da.hstack(delayed_arrays) hda def get_delayed_array(base_chunk_size,n_chunks): del...
_____no_output_____
BSD-3-Clause
notebooks/da_from_delayed_array_vs_df.ipynb
data-exp-lab/yt-dask-experiments
comparison
def array_construct_compute(base_chunk_size,n_chunks,find_mean=False): res1 = get_delayed_array(base_chunk_size,n_chunks) if find_mean: r = res1.mean().compute() else: r = res1.compute() return def df_construct_compute(base_chunk_size,n_chunks,find_mean=False): res1 = get_delayed_ar...
_____no_output_____
BSD-3-Clause
notebooks/da_from_delayed_array_vs_df.ipynb
data-exp-lab/yt-dask-experiments
Linear Regression with PyTorch Part 2 of "PyTorch: Zero to GANs"*This post is the second in a series of tutorials on building deep learning models with PyTorch, an open source neural networks library developed and maintained by Facebook. Check out the full series:*1. [PyTorch Basics: Tensors & Gradients](https://jovia...
# Uncomment the command below if Numpy or PyTorch is not installed # !conda install numpy pytorch cpuonly -c pytorch -y import numpy as np import torch
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Training dataThe training data can be represented using 2 matrices: `inputs` and `targets`, each with one row per observation, and one column per variable.
# Input (temp, rainfall, humidity) inputs = np.array([[73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70]], dtype='float32') # Targets (apples, oranges) targets = np.array([[56, 70], [81, 101], ...
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
We've separated the input and target variables, because we'll operate on them separately. Also, we've created numpy arrays, because this is typically how you would work with training data: read some CSV files as numpy arrays, do some processing, and then convert them to PyTorch tensors as follows:
# Convert inputs and targets to tensors inputs = torch.from_numpy(inputs) targets = torch.from_numpy(targets) print(inputs) print(targets)
tensor([[ 73., 67., 43.], [ 91., 88., 64.], [ 87., 134., 58.], [102., 43., 37.], [ 69., 96., 70.]]) tensor([[ 56., 70.], [ 81., 101.], [119., 133.], [ 22., 37.], [103., 119.]])
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Linear regression model from scratchThe weights and biases (`w11, w12,... w23, b1 & b2`) can also be represented as matrices, initialized as random values. The first row of `w` and the first element of `b` are used to predict the first target variable i.e. yield of apples, and similarly the second for oranges.
# Weights and biases w = torch.randn(2, 3, requires_grad=True) b = torch.randn(2, requires_grad=True) print(w) print(b)
tensor([[-0.2269, 0.2678, 1.5796], [-1.1205, 0.8164, 0.2107]], requires_grad=True) tensor([-0.4371, -0.5532], requires_grad=True)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
`torch.randn` creates a tensor with the given shape, with elements picked randomly from a [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) with mean 0 and standard deviation 1.Our *model* is simply a function that performs a matrix multiplication of the `inputs` and the weights `w` (transposed) ...
def model(x): return x @ w.t() + b
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
`@` represents matrix multiplication in PyTorch, and the `.t` method returns the transpose of a tensor.The matrix obtained by passing the input data into the model is a set of predictions for the target variables.
# Generate predictions preds = model(inputs) print(preds)
tensor([[ 68.8666, -18.5934], [103.5783, -17.1936], [107.3293, 23.5771], [ 46.3805, -71.9462], [120.1905, 15.2536]], grad_fn=<AddBackward0>)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Let's compare the predictions of our model with the actual targets.
# Compare with targets print(targets)
tensor([[ 56., 70.], [ 81., 101.], [119., 133.], [ 22., 37.], [103., 119.]])
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
You can see that there's a huge difference between the predictions of our model, and the actual values of the target variables. Obviously, this is because we've initialized our model with random weights and biases, and we can't expect it to *just work*. Loss functionBefore we improve our model, we need a way to evalua...
# MSE loss def mse(t1, t2): diff = t1 - t2 return torch.sum(diff * diff) / diff.numel()
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
`torch.sum` returns the sum of all the elements in a tensor, and the `.numel` method returns the number of elements in a tensor. Let's compute the mean squared error for the current predictions of our model.
# Compute loss loss = mse(preds, targets) print(loss)
tensor(5812.5947, grad_fn=<DivBackward0>)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Here’s how we can interpret the result: *On average, each element in the prediction differs from the actual target by about 145 (square root of the loss 20834)*. And that’s pretty bad, considering the numbers we are trying to predict are themselves in the range 50–200. Also, the result is called the *loss*, because it ...
# Compute gradients loss.backward()
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
The gradients are stored in the `.grad` property of the respective tensors. Note that the derivative of the loss w.r.t. the weights matrix is itself a matrix, with the same dimensions.
# Gradients for weights print(w) print(w.grad)
tensor([[-0.2269, 0.2678, 1.5796], [-1.1205, 0.8164, 0.2107]], requires_grad=True) tensor([[ 1130.2988, 796.7463, 685.3582], [-9002.7490, -9128.7617, -5802.7393]])
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
The loss is a [quadratic function](https://en.wikipedia.org/wiki/Quadratic_function) of our weights and biases, and our objective is to find the set of weights where the loss is the lowest. If we plot a graph of the loss w.r.t any individual weight or bias element, it will look like the figure shown below. A key insigh...
w.grad.zero_() b.grad.zero_() print(w.grad) print(b.grad)
tensor([[0., 0., 0.], [0., 0., 0.]]) tensor([0., 0.])
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Adjust weights and biases using gradient descentWe'll reduce the loss and improve our model using the gradient descent optimization algorithm, which has the following steps:1. Generate predictions2. Calculate the loss3. Compute gradients w.r.t the weights and biases4. Adjust the weights by subtracting a small quantity...
# Generate predictions preds = model(inputs) print(preds)
tensor([[ 68.8666, -18.5934], [103.5783, -17.1936], [107.3293, 23.5771], [ 46.3805, -71.9462], [120.1905, 15.2536]], grad_fn=<AddBackward0>)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Note that the predictions are same as before, since we haven't made any changes to our model. The same holds true for the loss and gradients.
# Calculate the loss loss = mse(preds, targets) print(loss) # Compute gradients loss.backward() print(w.grad) print(b.grad)
tensor([[ 1130.2988, 796.7463, 685.3582], [-9002.7490, -9128.7617, -5802.7393]]) tensor([ 13.0690, -105.7805])
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Finally, we update the weights and biases using the gradients computed above.
# Adjust weights & reset gradients with torch.no_grad(): w -= w.grad * 1e-5 b -= b.grad * 1e-5 w.grad.zero_() b.grad.zero_()
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
A few things to note above:* We use `torch.no_grad` to indicate to PyTorch that we shouldn't track, calculate or modify gradients while updating the weights and biases. * We multiply the gradients with a really small number (`10^-5` in this case), to ensure that we don't modify the weights by a really large amount, sin...
print(w) print(b)
tensor([[-0.2382, 0.2599, 1.5727], [-1.0305, 0.9077, 0.2688]], requires_grad=True) tensor([-0.4372, -0.5521], requires_grad=True)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
With the new weights and biases, the model should have lower loss.
# Calculate loss preds = model(inputs) loss = mse(preds, targets) print(loss)
tensor(3987.4089, grad_fn=<DivBackward0>)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
We have already achieved a significant reduction in the loss, simply by adjusting the weights and biases slightly using gradient descent. Train for multiple epochsTo reduce the loss further, we can repeat the process of adjusting the weights and biases using the gradients multiple times. Each iteration is called an ep...
# Train for 100 epochs for i in range(100): preds = model(inputs) loss = mse(preds, targets) loss.backward() with torch.no_grad(): w -= w.grad * 1e-5 b -= b.grad * 1e-5 w.grad.zero_() b.grad.zero_()
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Once again, let's verify that the loss is now lower:
# Calculate loss preds = model(inputs) loss = mse(preds, targets) print(loss)
tensor(92.2694, grad_fn=<DivBackward0>)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
As you can see, the loss is now much lower than what we started out with. Let's look at the model's predictions and compare them with the targets.
# Predictions preds # Targets targets
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
The prediction are now quite close to the target variables, and we can get even better results by training for a few more epochs. At this point, we can save our notebook and upload it to [Jovian.ml](https://www.jovian.ml) for future reference and sharing.
!pip install jovian --upgrade -q import jovian jovian.commit()
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
`jovian.commit` uploads the notebook to [Jovian.ml](https://www.jovian.ml), captures the Python environment and creates a sharable link for the notebook. You can use this link to share your work and let anyone reproduce it easily with the `jovian clone` command. Jovian also includes a powerful commenting interface, so...
import torch.nn as nn
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
As before, we represent the inputs and targets and matrices.
# Input (temp, rainfall, humidity) inputs = np.array([[73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70], [73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70], [73, 67, 43], [91, 88, 64], [87, 134, 58],...
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
We are using 15 training examples this time, to illustrate how to work with large datasets in small batches. Dataset and DataLoaderWe'll create a `TensorDataset`, which allows access to rows from `inputs` and `targets` as tuples, and provides standard APIs for working with many different types of datasets in PyTorch.
from torch.utils.data import TensorDataset # Define dataset train_ds = TensorDataset(inputs, targets) train_ds[0:3]
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
The `TensorDataset` allows us to access a small section of the training data using the array indexing notation (`[0:3]` in the above code). It returns a tuple (or pair), in which the first element contains the input variables for the selected rows, and the second contains the targets. We'll also create a `DataLoader`, ...
from torch.utils.data import DataLoader # Define data loader batch_size = 5 train_dl = DataLoader(train_ds, batch_size, shuffle=True)
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
The data loader is typically used in a `for-in` loop. Let's look at an example.
for xb, yb in train_dl: print(xb) print(yb) break
tensor([[73., 67., 43.], [73., 67., 43.], [91., 88., 64.], [91., 88., 64.], [69., 96., 70.]]) tensor([[ 56., 70.], [ 56., 70.], [ 81., 101.], [ 81., 101.], [103., 119.]])
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
In each iteration, the data loader returns one batch of data, with the given batch size. If `shuffle` is set to `True`, it shuffles the training data before creating batches. Shuffling helps randomize the input to the optimization algorithm, which can lead to faster reduction in the loss. nn.LinearInstead of initializ...
# Define model model = nn.Linear(3, 2) print(model.weight) print(model.bias)
Parameter containing: tensor([[-0.1238, 0.1825, -0.4556], [-0.4230, -0.0333, -0.2770]], requires_grad=True) Parameter containing: tensor([ 0.1319, -0.2120], requires_grad=True)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
PyTorch models also have a helpful `.parameters` method, which returns a list containing all the weights and bias matrices present in the model. For our linear regression model, we have one weight matrix and one bias matrix.
# Parameters list(model.parameters())
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
We can use the model to generate predictions in the exact same way as before:
# Generate predictions preds = model(inputs) preds
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Loss FunctionInstead of defining a loss function manually, we can use the built-in loss function `mse_loss`.
# Import nn.functional import torch.nn.functional as F
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
The `nn.functional` package contains many useful loss functions and several other utilities.
# Define loss function loss_fn = F.mse_loss
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Let's compute the loss for the current predictions of our model.
loss = loss_fn(model(inputs), targets) print(loss)
tensor(16434.4238, grad_fn=<MseLossBackward>)
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
OptimizerInstead of manually manipulating the model's weights & biases using gradients, we can use the optimizer `optim.SGD`. SGD stands for `stochastic gradient descent`. It is called `stochastic` because samples are selected in batches (often with random shuffling) instead of as a single group.
# Define optimizer opt = torch.optim.SGD(model.parameters(), lr=1e-5)
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Note that `model.parameters()` is passed as an argument to `optim.SGD`, so that the optimizer knows which matrices should be modified during the update step. Also, we can specify a learning rate which controls the amount by which the parameters are modified. Train the modelWe are now ready to train the model. We'll fo...
# Utility function to train the model def fit(num_epochs, model, loss_fn, opt, train_dl): # Repeat for given number of epochs for epoch in range(num_epochs): # Train with batches of data for xb,yb in train_dl: # 1. Generate predictions pred = mo...
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Some things to note above:* We use the data loader defined earlier to get batches of data for every iteration.* Instead of updating parameters (weights and biases) manually, we use `opt.step` to perform the update, and `opt.zero_grad` to reset the gradients to zero.* We've also added a log statement which prints the lo...
fit(100, model, loss_fn, opt,train_dl)
Epoch [10/100], Loss: 103.0426 Epoch [20/100], Loss: 162.5573 Epoch [30/100], Loss: 198.4801 Epoch [40/100], Loss: 60.2136 Epoch [50/100], Loss: 166.9063 Epoch [60/100], Loss: 90.8259 Epoch [70/100], Loss: 80.0923 Epoch [80/100], Loss: 25.8551 Epoch [90/100], Loss: 49.2282 Epoch [100/100], Loss: 64.7186
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Let's generate predictions using our model and verify that they're close to our targets.
# Generate predictions preds = model(inputs) preds # Compare with targets targets
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Indeed, the predictions are quite close to our targets, and now we have a fairly good model to predict crop yields for apples and oranges by looking at the average temperature, rainfall and humidity in a region. Commit and update the notebookAs a final step, we can record a new version of the notebook using the `jovia...
import jovian jovian.commit()
_____no_output_____
MIT
week 1/02-linear-regression.ipynb
anuraglahon16/DeepLearning-with-PyTorch
Spin-polarized calculations with BigDFTThe goal of this notebook is to explain how to do a spin-polarized calculation with BigDFT (`nspin=2`).We start with the molecule O$_2$ and a non-spin polarized calculation, which is the code default.To do that we only have to specify the atomic positions of the molecule.
from BigDFT import Calculators as C calc = C.SystemCalculator() posO1=3*[0.0] posO2=[0.0, 0.0, 1.2075] # in angstroem inpt={'posinp': { 'positions': [ {'O': posO1 }, {'O': posO2 }], 'units': 'angstroem' }} logNSP = calc.run(input=inpt)
Initialize a Calculator with OMP_NUM_THREADS=2 and command mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
Such calculation produced a converged set of KS LDA orbitals, with the following density of states:
%matplotlib inline DoS=logNSP.get_dos(label='NSP') DoS.plot()
_____no_output_____
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
Now we do the same calculation but with spin-polarized specifying `nspin=2`, in the `dft` field.
inpt['dft']={'nspin': 2} logSP = calc.run(input=inpt)
Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
We may see that this run did not produce any difference with respect to the previous one. Even though we doubled the number of orbitals, the input guess wavefunctions and densities are identical in both the spin sectors. As a consequence the energy and the DoS are identical to the NSP case:
print logNSP.energy,logSP.energy DoS.append_from_bandarray(logSP.evals,label='SP (m 0)') DoS.plot()
-31.8014240962 -31.8014240962
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
This is due to the fact that: 1. We had the same input guess for up and down subspaces; 2. We had the same number of orbitals in both the sectors and no empty orbitals during the minimization. Such problems can be solved at the same time by performing mixing scheme with *random* initialization of the wavefunctions:
inpt['import']='mixing' inpt['mix']={'iscf': 12, 'itrpmax': 20} # mixing on the potential, just 20 Hamiltonian iterations for a quick look inpt['dft']['inputpsiid']= 'RANDOM' #for random initialization logSP_mix = calc.run(input=inpt)
Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
We see that with these input parameters the DoS is different from the NSP case, the energy is lower and the net polarization is 2:
print logNSP.energy,logSP_mix.energy DoS.append_from_bandarray(logSP_mix.evals,label='SP mix(m 0, RAND)') DoS.plot() print 'Magnetic Polarization', logSP_mix.magnetization
-31.8014240962 -31.86269676
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
We see that to break the symmetry it is therefore necessary to have different IG subspaces between up and down orbitals, otherwise the results will be identical to the NSP case.Now that we know the polarization of the molecule, we may perform a direct minimization calculation of the molecule by specifying from the begi...
inpt={'dft': { 'nspin': 2, 'mpol': 2}, 'mix': { 'norbsempty': 2 }, 'posinp': { 'positions': [ {'O': posO1 }, {'O': posO2 }], 'units': 'angstroem' } } logSP_m2 = calc.run(input=inpt) print logSP_mix.energy,logSP_m2.energy DoS.append_from_bandarray(logSP_m2.evals,label='SP m 2') DoS.plot()
Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft -31.86269676 -31.8634464905
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
We show that the total magnetization is 2 in the case of the oxygen dimer. The DoS is not exactly the same because the mixing scheme was not fully converged (check increasing the value of `itrpmax`).
DoS=logSP_mix.get_dos(label='SP mix') DoS.append_from_bandarray(logSP_m2.evals,label='SP m 2') DoS.plot()
_____no_output_____
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
Odd electron system: the N atomWhat does happen when the number of electrons is odd as in the case of N?If we do a NSP calculation, the occupation of the last state is 1. Switching only the parameter `nspin` to the value 2, we do the same calculation with averaged-occupation (0.5 for the last up and down state).To do ...
inpt = { 'dft': { 'nspin': 1}, 'posinp': { 'units': 'angstroem', 'positions': [ {'N': 3*[0.0] } ] } } logNSP = calc.run(input=inpt) inpt['dft']['nspin'] = 2 logSP = calc.run(input=inpt) print logNSP.energy,logSP.energy print logNSP.fermi_level,logSP.fermi_level DoS=logNSP.get_dos(labe...
Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft 3.0
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
We found a total magnetization of 3 following the Hund's rule. Defining the input guess (*ig_occupation* keyword)We have shown that by default, the input guess is LCAO (localised atomic orbitals) defining by the pseudo-orbitals.The occupation is sphere symmetry (same occupation per orbital moment).We have used random ...
inpt['dft']['inputpsiid']='LCAO' #LCAO input guess inpt['ig_occupation'] = { 'N': { '2s': { 'up': 1, 'down': 1}, '2p': {'up': [1,1,1], 'down': 0} } } logLCAO_mix = calc.run(input=inpt) print logSP_mix.energy,logLCAO_mix.energy DoS=logSP_mix.get_dos(label='SP RAN') DoS.append_from_bandarray(logLCAO_mix.evals,label='SP ...
Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft -9.74145176349 -9.74158042631
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
Instead of `ig_occupation`, it is also possible to specify the keyword `IGSpin` per atom in the `posinp` dictionary.
inpt = { 'dft': { 'nspin': 2, 'mpol': 3}, 'posinp': { 'units': 'angstroem', 'positions': [ {'N': 3*[0.0], 'IGSpin': 3 } ] }, 'ig_occupation': { 'N': { '2s': { 'up': 1, 'down': 1}, '2p': { 'up': [1,1,1], 'down': 0} } } } logIG = calc.run(inpu...
Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft -9.74145176349 -9.74158042631 -9.74158042096
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
Occupation numbersFinally, it is possible to set the occupation numbers for each state by the parameter `occup`.In this case, the direct minimization is done with this occupation number.In the case of N, there are 8 orbitals, the first 4 are up and the other ones down.Here we do a calculation following the Hund's rule...
del inpt['ig_occupation'] inpt['occupation'] = { 'up': { 'Orbital 1': 1, 'Orbital 2': 1, 'Orbital 3': 1, 'Orbital 4': 1 }, # up 'down': { 'Orbital 1': 1, 'Orbital 2': 0, 'Orbital 3': 0, 'Orbital 4': 0 } }# down logS = calc.run(input=inpt) print logSP_mix.energy,logLCAO_mix.energy,logIG.energy,...
Creating the yaml input file "input.yaml" Executing command: mpirun -np 2 /local/deutsch/Forge/BigDFT/build-mpif90-openmp/install/bin/bigdft -9.74145176349 -9.74158042631 -9.74158042096 -9.7415803697
MIT
aiida_bigdft/PyBigDFT/source/notebooks/Spin-Polarization.ipynb
mikiec84/aiida-bigdft-plugin
MNIST on TPU (Tensor Processing Unit)or GPU using tf.Keras and tf.data.DatasetThis sample trains an "MNIST" handwritten digit recognition model on a GPU or TPU backend using a Kerasmodel. Data are handled using the tf.data.Datset API. This isa very simple sample provided for educational purposes. Donot expect outstan...
BATCH_SIZE = 128 # On TPU, this will be the per-core batch size. A Cloud TPU has 8 cores so tha global TPU batch size is 1024 training_images_file = 'gs://mnist-public/train-images-idx3-ubyte' training_labels_file = 'gs://mnist-public/train-labels-idx1-ubyte' validation_images_file = 'gs://mnist-public/t10k-images...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Imports
import os, re, math, json, shutil, pprint import PIL.Image, PIL.ImageFont, PIL.ImageDraw import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from tensorflow.python.platform import tf_logging print("Tensorflow version " + tf.__version__) #@title visualization utilities [RUN ME] """ This cell ...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Colab-only auth for this notebook and the TPU
IS_COLAB_BACKEND = 'COLAB_GPU' in os.environ # this is always set on Colab, the value is 0 or 1 depending on GPU presence if IS_COLAB_BACKEND: from google.colab import auth auth.authenticate_user() # Authenticates the backend and also the TPU using your credentials so that they can access your private GCS buckets
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
tf.data.Dataset: parse files and prepare training and validation datasetsPlease read the [best practices for building](https://www.tensorflow.org/guide/performance/datasets) input pipelines with tf.data.Dataset
def read_label(tf_bytestring): label = tf.decode_raw(tf_bytestring, tf.uint8) label = tf.reshape(label, []) label = tf.one_hot(label, 10) return label def read_image(tf_bytestring): image = tf.decode_raw(tf_bytestring, tf.uint8) image = tf.cast(image, tf.float32)/256.0 image = tf.reshape(...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Let's have a look at the data
N = 24 (training_digits, training_labels, validation_digits, validation_labels) = dataset_to_numpy_util(training_dataset, validation_dataset, N) display_digits(training_digits, training_labels, training_labels, "training digits and their labels", N) display_digits(validation_digits[:N], validation_labels[:N], validati...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Keras model: 3 convolutional layers, 2 dense layersIf you are not sure what cross-entropy, dropout, softmax or batch-normalization mean, head here for a crash-course: [Tensorflow and deep learning without a PhD](https://github.com/GoogleCloudPlatform/tensorflow-without-a-phd/featured-code-sample)
# This model trains to 99.4% sometimes 99.5% accuracy in 10 epochs (with a batch size of 32) l = tf.keras.layers model = tf.keras.Sequential( [ l.Reshape(input_shape=(28*28,), target_shape=(28, 28, 1)), l.Conv2D(filters=6, kernel_size=3, padding='same', use_bias=False), # no bias necessary before batch norm...
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= reshape_4 (Reshape) (None, 28, 28, 1) 0 ________________________________________________________...
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Train and validate the model
EPOCHS = 10 steps_per_epoch = 60000//BATCH_SIZE # 60,000 items in this dataset tpu = None trained_model = model # Counting steps and batches on TPU: the tpu.keras_to_tpu_model API regards the batch size of the input dataset # as the per-core batch size. The effective batch size is 8x more because Cloud TPUs have 8 co...
INFO:tensorflow:Querying Tensorflow master (grpc://10.84.162.34:8470) for TPU system metadata. INFO:tensorflow:Found TPU system: INFO:tensorflow:*** Num TPU Cores: 8 INFO:tensorflow:*** Num TPU Workers: 1 INFO:tensorflow:*** Num TPU Cores Per Worker: 8 INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker...
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Visualize training and validation curves
print(history.history.keys()) display_training_curves(history.history['acc'], history.history['val_acc'], 'accuracy', 211) display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 212)
dict_keys(['val_loss', 'val_acc', 'loss', 'acc', 'lr'])
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Visualize predictions
# recognize digits from local fonts probabilities = trained_model.predict(font_digits, steps=1) predicted_labels = np.argmax(probabilities, axis=1) display_digits(font_digits, predicted_labels, font_labels, "predictions from local fonts (bad predictions in red)", N) # recognize validation digits probabilities = traine...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Deploy the trained model to ML EnginePush your trained model to production on ML Engine for a serverless, autoscaled, REST API experience.You will need a GCS bucket and a GCP project for this.Models deployed on ML Engine autoscale to zero if not used. There will be no ML Engine charges after you are done testing.Googl...
PROJECT = "" #@param {type:"string"} BUCKET = "gs://" #@param {type:"string", default:"jddj"} NEW_MODEL = True #@param {type:"boolean"} MODEL_NAME = "colabmnist" #@param {type:"string"} MODEL_VERSION = "v0" #@param {type:"string"} assert PROJECT, 'For this part, you need a GCP project. Head to http://console.cloud.go...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Export the model for serving from ML Engine
class ServingInput(tf.keras.layers.Layer): # the important detail in this boilerplate code is "trainable=False" def __init__(self, name, dtype, batch_input_shape=None): super(ServingInput, self).__init__(trainable=False, name=name, dtype=dtype, batch_input_shape=batch_input_shape) def get_config(self): re...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst
Deploy the modelThis uses the command-line interface. You can do the same thing through the ML Engine UI at https://console.cloud.google.com/mlengine/models
# Create the model if NEW_MODEL: !gcloud ml-engine models create {MODEL_NAME} --project={PROJECT} --regions=us-central1 # Create a version of this model (you can add --async at the end of the line to make this call non blocking) # Additional config flags are available: https://cloud.google.com/ml-engine/reference/res...
_____no_output_____
Apache-2.0
gc-ai-notebook-tutorials/tutorials/fast-and-lean-data-science/01_MNIST_TPU_Keras.ipynb
kalona/training-data-analyst