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 |
|---|---|---|---|---|---|
Part 2: Introduction to Feed Forward Networks 1. What is a neural network? 1.1 NeuronsA neuron is software that is roughly modeled after the neuons in your brain. In software, we model it with an _affine function_ and an _activation function_. One type of neuron is the perceptron, which outputs a binary output 0 or 1 ... | # Some initial setup. Borrowed from:
# https://github.com/ageron/handson-ml/blob/master/09_up_and_running_with_tensorflow.ipynb
# Common imports
import numpy as np
import os
import tensorflow as tf
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsi... | Done
| MIT | 02-introduction-to-neural-networks-and-tensorflow/introduction-to-neural-networks-and-tensorflow.ipynb | vr140/intro-deep-learning |
Below we will train our first model using the example from the Tensorflow tutorial: https://www.tensorflow.org/tutorials/This will show you the basics of training a model! | # The example below is also in https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/_index.ipynb
# to ensure relatively stable output across sessions
stabilize_output()
mnist = tf.keras.datasets.mnist
# load data (requires Internet connection)
(x_train, y_train),(x_test, y_t... | Epoch 1/5
60000/60000 [==============================] - 8s 127us/step - loss: 0.2198 - acc: 0.9344... | MIT | 02-introduction-to-neural-networks-and-tensorflow/introduction-to-neural-networks-and-tensorflow.ipynb | vr140/intro-deep-learning |
You should see something similar to [0.06788356024027743, 0.9806]. The first number is the final loss and the second number is the accuracy.Congratulations, it means you've trained a classifier that classifies digit images in the MNIST Dataset with __98% accuracy__! We'll break down how the model is optimizing to achie... | # Borrowed from http://cs231n.github.io/assignments2018/assignment2/
def load_cifar10(num_training=49000, num_validation=1000, num_test=10000):
"""
Fetch the CIFAR-10 dataset from the web and perform preprocessing to prepare
it for the two-layer neural net classifier. These are the same steps as
we used... | ('Train data shape: ', (49000, 32, 32, 3))
('Train labels shape: ', (49000,), dtype('int32'))
('Validation data shape: ', (1000, 32, 32, 3))
('Validation labels shape: ', (1000,))
('Test data shape: ', (10000, 32, 32, 3))
('Test labels shape: ', (10000,))
| MIT | 02-introduction-to-neural-networks-and-tensorflow/introduction-to-neural-networks-and-tensorflow.ipynb | vr140/intro-deep-learning |
3.2 Preparation: Dataset objectBorrowed from CS231N [2], we will define a `Dataset` class for iteration to store data and labels. | class Dataset(object):
def __init__(self, X, y, batch_size, shuffle=False):
"""
Construct a Dataset object to iterate over data X and labels y
Inputs:
- X: Numpy array of data, of any shape
- y: Numpy array of labels, of any shape but with y.shape[0] == X.shape[0]
... | [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. ... | MIT | 02-introduction-to-neural-networks-and-tensorflow/introduction-to-neural-networks-and-tensorflow.ipynb | vr140/intro-deep-learning |
3.3 TrainingWe will now train using the gradient descent algorithm explained in the previous notebook. The check_accuracy function below lets us check the accuracy of our neural network.As explained in CS231N:"The `training_step` function has three basic steps:1. Compute the loss2. Compute the gradient of the loss wit... | # Borrowed from cs231n.github.io/assignments2018/assignment2/
def training_step(scores, y, params, learning_rate):
"""
Set up the part of the computational graph which makes a training step.
Inputs:
- scores: TensorFlow Tensor of shape (N, C) giving classification scores for
the model.
- y: T... | Iteration 0, loss = 3.1850
Got 117 / 1000 correct (11.70%)
Iteration 100, loss = 1.8910
Got 386 / 1000 correct (38.60%)
Iteration 200, loss = 1.3805
Got 398 / 1000 correct (39.80%)
Iteration 300, loss = 1.8048
Got 384 / 1000 correct (38.40%)
Iteration 400, loss = 1.7182
Got 431 / 1000 correct (43.10%)
Iteration 500, lo... | MIT | 02-introduction-to-neural-networks-and-tensorflow/introduction-to-neural-networks-and-tensorflow.ipynb | vr140/intro-deep-learning |
3.3 KerasNote in the first cell, we used the tf.keras Sequential API to make a neural network but here we use "barebones" Tensorflow. One of the good (and possibly bad) things about Tensorflow is that there are several ways to create a neural network and train it. Here are some possible ways:* Barebones tensorflow* tf... | # Now we will train the same model using the Sequential API.
# First we set up our training and model initializiation functions
def train_keras(model_init_fn, optimizer_init_fn, num_epochs=1):
"""
Simple training loop for use with models defined using tf.keras. It trains
a model for one epoch on the CIFAR-... | Starting epoch 0
Iteration 0, loss = 2.8911
Got 128 / 1000 correct (12.80%)
()
Iteration 100, loss = 1.8686
Got 391 / 1000 correct (39.10%)
()
Iteration 200, loss = 1.3735
Got 424 / 1000 correct (42.40%)
()
Iteration 300, loss = 1.7414
Got 394 / 1000 correct (39.40%)
()
Iteration 400, loss = 1.6495
Got 434 / 1000 corre... | MIT | 02-introduction-to-neural-networks-and-tensorflow/introduction-to-neural-networks-and-tensorflow.ipynb | vr140/intro-deep-learning |
GETTING DATA | import numpy as np
data = np.load("./data.npz")
X_train = data["X_train"]
Y_train = data["Y_train"]
X_test = data["X_test"]
print("Shapes")
print("X_train:",X_train.shape)
print("Y_train:",Y_train.shape)
print("X_test:",X_test.shape) | Shapes
X_train: (10714, 21)
Y_train: (10714,)
X_test: (14498, 21)
| Apache-2.0 | main.ipynb | krish1237/Flipr-corona |
COMPILING KERAS MODEL | from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Sequential
model = Sequential()
model.add(Dense(32, input_dim=21, kernel_initializer='glorot_uniform',
bias_initializer='zeros', activation="relu"))
model.add(Dense(64, kernel_initializer='glorot_uniform',
... | _____no_output_____ | Apache-2.0 | main.ipynb | krish1237/Flipr-corona |
TRAINING MODEL | labels = Y_train.reshape(-1,1)
epochs = 10
labels
model.fit(X_train,Y_train.reshape(-1,1), validation_split=0.1, epochs=epochs)
y_pred = model.predict(X_train)
y_pred
labels
model.save("model.h5") | _____no_output_____ | Apache-2.0 | main.ipynb | krish1237/Flipr-corona |
Simple Linear Regression using Basic Python | import numpy as np
import random
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%matplotlib inline | _____no_output_____ | MIT | notebooks/simple_linear_regression.ipynb | mjbrann4/py-ml |
Produce target and feature data | X = np.linspace(1,20,20)
# true function
y_true = 2*X + 5
# function with noise ('error term')
y_rand = 2*X + 5 + np.random.randint(-10, 11, len(X))
fig, ax = plt.subplots(figsize=(8,5))
plt.scatter(X, y_rand, color = 'b', s = 20, label = 'Observations')
plt.plot(X, y_true, color='m', label='True Function')
plt.xlab... | _____no_output_____ | MIT | notebooks/simple_linear_regression.ipynb | mjbrann4/py-ml |
OLS | def simple_ols(X, y):
'''Function to perform simple OLS regression using basic python
Parameters:
X - single feature np array or list
y - target np array or list
'''
X_bar = np.mean(X)
y_bar = np.mean(y)
num_list = [(X[i] - X_bar) * (y[i] - y_bar) for i in range(len(X))]
denom_list... | _____no_output_____ | MIT | notebooks/simple_linear_regression.ipynb | mjbrann4/py-ml |
Take 1000 Samples to Verify Estimates are Equal to True Values | samples = [ 2*X + 5 + np.random.randint(-10, 11, len(X)) for i in range(1000) ]
betas = [simple_ols(X, s) for s in samples ]
# mean of each column in list of betas
b0_sampled, b1_sampled = np.mean(betas, axis=0)
print('slope: ', b0_sampled)
print('intercept: ', b1_sampled) | slope: 5.011063157894742
intercept: 2.0014939849624045
| MIT | notebooks/simple_linear_regression.ipynb | mjbrann4/py-ml |
VacationPy---- Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. | # Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import gmaps
import os
# Import API key
from api_keys import g_key | _____no_output_____ | ADSL | starter_code/VacationPy.ipynb | kanikajain1/python-api-challenge |
Store Part I results into DataFrame* Load the csv exported in Part I to a DataFrame | _____no_output_____ | ADSL | starter_code/VacationPy.ipynb | kanikajain1/python-api-challenge | |
Humidity Heatmap* Configure gmaps.* Use the Lat and Lng as locations and Humidity as the weight.* Add Heatmap layer to map. Create new DataFrame fitting weather criteria* Narrow down the cities to fit weather conditions.* Drop any rows will null values. Hotel Map* Store into variable named `hotel_df`.* Add a "Hotel ... | # NOTE: Do not change any of the code in this cell
# Using the template add the hotel marks to the heatmap
info_box_template = """
<dl>
<dt>Name</dt><dd>{Hotel Name}</dd>
<dt>City</dt><dd>{City}</dd>
<dt>Country</dt><dd>{Country}</dd>
</dl>
"""
# Store the DataFrame Row
# NOTE: be sure to update with your DataFrame na... | _____no_output_____ | ADSL | starter_code/VacationPy.ipynb | kanikajain1/python-api-challenge |
Table of Contents1 Scale heights for typical atmospheric soundings1.1 Plot McClatchey's US Standard Atmospheres1.1.1 Reading the soundings files into pandas2 Use pd.DataFrame.head to see first 5 lines2.0.1 Plot temp and vapor mixing ratio rmix ($\rho_{H2O}/\rho_{a... | from matplotlib import pyplot as plt
import matplotlib.ticker as ticks
import numpy as np
import a301
from pathlib import Path
import pandas as pd
import pprint
soundings_folder= a301.test_dir / Path('soundings')
sounding_files = list(soundings_folder.glob("*csv")) | _____no_output_____ | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Reading the soundings files into pandasThere are five soundings.The soundings have six columns and 33 rows (i.e. 33 height levels). The variables are z, press, temp, rmix, den, o3den -- where rmix is the mixing ratio of water vapor, den is the dry air density and o3den is the ozone density. The units are m, pa, K, ... | name_dict=dict()
sound_dict=dict()
for item in sounding_files:
name_dict[item.stem]=item
pprint.pprint(name_dict)
for item in sounding_files:
sound_dict[item.stem]=pd.read_csv(item) | {'midsummer': PosixPath('/Users/phil/repos/a301_code/test_data/soundings/midsummer.csv'),
'midwinter': PosixPath('/Users/phil/repos/a301_code/test_data/soundings/midwinter.csv'),
'subsummer': PosixPath('/Users/phil/repos/a301_code/test_data/soundings/subsummer.csv'),
'subwinter': PosixPath('/Users/phil/repos/a301_co... | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Use pd.DataFrame.head to see first 5 lines | for key,value in sound_dict.items():
print(f"sounding: {key}\n{sound_dict[key].head()}") | sounding: tropics
Unnamed: 0 z press temp rmix den o3den
0 0 0.0 101300.0 300.0 0.01900 1.1670 5.600000e-08
1 1 1000.0 90400.0 294.0 0.01300 1.0640 5.600000e-08
2 2 2000.0 80500.0 288.0 0.00929 0.9689 5.400000e-08
3 3 3000.0 ... | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
We use these keys to get a dataframe with 6 columns, and 33 levels. Here's an example for the midsummer sounding | midsummer=sound_dict['midsummer']
print(midsummer.head())
list(midsummer.columns) | Unnamed: 0 z press temp rmix den o3den
0 0 0.0 101300.0 294.0 0.01400 1.1910 6.000000e-08
1 1 1000.0 90200.0 290.0 0.00930 1.0800 6.000000e-08
2 2 2000.0 80200.0 285.0 0.00585 0.9757 6.000000e-08
3 3 3000.0 71000.0 279.0 ... | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Plot temp and vapor mixing ratio rmix ($\rho_{H2O}/\rho_{air}$) | %matplotlib inline
plt.style.use('ggplot')
meters2km=1.e-3
plt.close('all')
fig,(ax1,ax2)=plt.subplots(1,2,figsize=(11,8))
for a_name,df in sound_dict.items():
ax1.plot(df['temp'],df['z']*meters2km,label=a_name)
ax1.set(ylim=(0,40),title='Temp soundings',ylabel='Height (km)',
xlabel='Temperature (K)')
... | _____no_output_____ | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Calculating scale heights for temperature and air density Here is equation 1 of the [hydrostatic balance notes](http://clouds.eos.ubc.ca/~phil/courses/atsc301/hydrostat.htmlequation-hydro) $$\frac{ 1}{\overline{H_p}} = \overline{ \left ( \frac{1 }{H} \right )} = \frac{\int_{0 }^{z}\!\frac{1}{H} dz^\prime }{z-0} $$wh... | g=9.8 #don't worry about g(z) for this exercise
Rd=287. #kg/m^3
def calcScaleHeight(T,p,z):
"""
Calculate the pressure scale height H_p
Parameters
----------
T: vector (float)
temperature (K)
p: vector (float) of len(T)
pressure (pa)
z: vector (float) of... | _____no_output_____ | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Similarly, equation (5) of the [hydrostatic balance notes](http://clouds.eos.ubc.ca/~phil/courses/atsc301/hydrostat.htmlequation-hydro)is:$$\frac{d\rho }{\rho} = - \left ( \frac{1 }{H} + \frac{1 }{T} \frac{dT }{dz} \right ) dz \equiv - \frac{dz }{H_\rho} $$ Which leads to $$\frac{ 1... | def calcDensHeight(T,p,z):
"""
Calculate the density scale height H_rho
Parameters
----------
T: vector (float)
temperature (K)
p: vector (float) of len(T)
pressure (pa)
z: vector (float) of len(T
height (m)
Returns
-------
Hb... | _____no_output_____ | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
How do $\overline{H_p}$ and $\overline{H_\rho}$ compare for the tropical sounding? | sounding='tropics'
#
# grab the dataframe and get the sounding columns
#
df=sound_dict[sounding]
z=df['z'].values
Temp=df['temp'].values
press=df['press'].values
#
# limit calculation to bottom 10 km
#
hit=z<10000.
zL,pressL,TempL=(z[hit],press[hit],Temp[hit])
rhoL=pressL/(Rd*TempL)
Hbar= calcScaleHeight(TempL,pressL,z... | pressure scale height for the tropics sounding is 7.96 km
density scale height for the tropics is 9.74 km
| MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
How well do these average values represent the pressure and density profiles? | theFig,theAx=plt.subplots(1,1)
theAx.semilogy(Temp,press/100.)
#
# need to flip the y axis since pressure decreases with height
#
theAx.invert_yaxis()
tickvals=[1000,800, 600, 400, 200, 100, 50,1]
theAx.set_yticks(tickvals)
majorFormatter = ticks.FormatStrFormatter('%d')
theAx.yaxis.set_major_formatter(majorFormatter)
... | _____no_output_____ | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Now check the hydrostatic approximation by plotting the pressure column against$$p(z) = p_0 \exp \left (-z/\overline{H_p} \right )$$vs. the actual sounding p(T): | fig,theAx=plt.subplots(1,1)
hydroPress=pressL[0]*np.exp(-zL/Hbar)
theAx.plot(pressL/100.,zL/1000.,label='sounding')
theAx.plot(hydroPress/100.,zL/1000.,label='hydrostat approx')
theAx.set_title('height vs. pressure for tropics')
theAx.set_xlabel('pressure (hPa)')
theAx.set_ylabel('height (km)')
theAx.set_xlim([500,1000... | _____no_output_____ | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Again plot the hydrostatic approximation$$\rho(z) = \rho_0 \exp \left (-z/\overline{H_\rho} \right )$$vs. the actual sounding $\rho(z)$: | fig,theAx=plt.subplots(1,1)
hydroDens=rhoL[0]*np.exp(-zL/Hrho)
theAx.plot(rhoL,zL/1000.,label='sounding')
theAx.plot(hydroDens,zL/1000.,label='hydrostat approx')
theAx.set_title('height vs. density for the tropics')
theAx.set_xlabel('density ($kg\,m^{-3}$)')
theAx.set_ylabel('height (km)')
theAx.set_ylim([0,5])
theAx.l... | _____no_output_____ | MIT | notebooks/hydrostatic_balance.ipynb | Pearl-Ayem/ATSC_Course_Work |
Preprocessing | plt.figure(figsize=(20,12))
sns.heatmap(training_data.isnull(),yticklabels=False,cbar=False,cmap = 'viridis') | _____no_output_____ | MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
Missing value handling We are going to use different approches with missing values:1. Removing the column having 80% missing values (**Self intuition)2. Keeping all the features3. Later, we will try to implement some feature engineering **For the rest of the missing values, we are replacing them with their mean() for ... | sample_training_data = training_data
sample_training_data.fillna(sample_training_data.mean(),inplace=True)
#after replacing with mean()
plt.figure(figsize=(20,12))
sns.heatmap(sample_training_data.isnull(),yticklabels=False,cbar=False,cmap='viridis')
#as all the other values are numerical except Class column so we ca... | _____no_output_____ | MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
Testing Data preprocessing | testing_data = pd.read_csv("../Data/aps_failure_test_set.csv",na_values="na")
testing_data.head()
sample_testing_data = testing_data
sample_testing_data.fillna(sample_testing_data.mean(),inplace=True)
#after replacing with mean()
plt.figure(figsize=(20,12))
sns.heatmap(sample_testing_data.isnull(),yticklabels=False,c... | _____no_output_____ | MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
Implemented Methods | def getCost(y_test,prediction):
'''
evaluate the total cost without modified threshold
'''
tn, fp, fn, tp = confusion_matrix(y_test,prediction).ravel()
confusionData = [[tn,fp],[fn,tp]]
print("Confusion Matrix\n")
print(pd.DataFrame(confusionData,columns=['FN','FP'],index=['TN','TP']))
c... | _____no_output_____ | MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
Model implementation with Cross validation | X = sample_training_data.drop('class',axis=1)
y = sample_training_data['class']
CV_prediction = cross_val_predict(SVC(),X,y,cv = 5)
CV_score = cross_val_score(SVC(),X,y,cv = 5)
#mean cross validation score
np.mean(CV_score)
print(classification_report(y,CV_prediction))
evaluationScores(y,CV_prediction)
CV_prediction ... | _____no_output_____ | MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
Try with test train split | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
svc_model = SVC()
svc_model.fit(X_train,y_train)
trainingPrediction = svc_model.predict(X_test)
evaluationScored(y_test,trainingPrediction)
getCost(y_test,trainingPrediction) | Confusion Matrix
FN FP
TN 17691 0
TP 309 0
Cost
Score Number of Type 1 faults Number of Type 2 faults
0 154500 0 309
| MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
With threshold | aucForThreshold(X_test,y_test,svc_model)
#need to implement
getCostWithThreshold(X_test,y_test,trainingPrediction,threshold,svc_model) | _____no_output_____ | MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
With Gridsearch | param_grid = {'C': [0.1,1], 'gamma': [1,0.1], 'kernel': ['rbf']}
from sklearn.model_selection import GridSearchCV
grid = GridSearchCV(SVC(),param_grid,refit=True,verbose=3)
#fitting again
grid.fit(X_train,y_train)
grid.best_params_
grid.best_estimator_
grid_predictions = grid.predict(X_test)
evaluationScored(y_test,gr... | _____no_output_____ | MIT | Codes/Final (SVM SVC template ).ipynb | masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set |
Get dataset | SPLIT_WEIGHTS = (8, 1, 1)
splits = tfds.Split.TRAIN.subsplit(weighted=SPLIT_WEIGHTS)
(raw_train, raw_validation, raw_test), metadata = tfds.load('cats_vs_dogs',
split=list(splits),
with_info=True,
... | _____no_output_____ | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
Prepare input pipelines | IMG_SIZE = 160
BATCH_SIZE = 32
SHUFFLE_BUFFER_SIZE = 1000
def normalize_img(image, label):
image = tf.cast(image, tf.float32)
image = (image / 127.5) - 1.0
image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))
return image, label
ds_train = raw_train.map(normalize_img)
ds_validation = raw_validation.map(... | _____no_output_____ | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
Get pretrained model | base_model = tf.keras.applications.MobileNetV2(input_shape=(IMG_SIZE, IMG_SIZE, 3),
include_top=False,
weights='imagenet')
base_model.trainable = False
model = tf.keras.Sequential([
base_model,
tf.keras.layers.GlobalAv... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
mobilenetv2_1.00_160 (Model) (None, 5, 5, 1280) 2257984
____________________________________... | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
(Optional): Use Tensorflow Hub | import tensorflow_hub as hub
print(hub.__version__)
feature_extractor_url = "https://tfhub.dev/google/imagenet/mobilenet_v2_035_160/classification/4"
base_model = hub.KerasLayer(feature_extractor_url, input_shape=(IMG_SIZE, IMG_SIZE, 3), trainable=False)
model = tf.keras.Sequential([
base_model,
tf.keras.layers... | Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 1001) 1692489
__________________________________... | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
Compile model | base_learning_rate = 1e-4
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy']) | _____no_output_____ | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
Evaluate random model | loss0, accuracy0 = model.evaluate(ds_validation) | 73/Unknown - 5s 72ms/step - loss: 1.1503 - accuracy: 0.4358 | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
Train model | initial_epochs = 3
history = model.fit(ds_train,
epochs=initial_epochs,
validation_data=ds_validation) | Epoch 1/3
582/582 [==============================] - 27s 46ms/step - loss: 0.5690 - accuracy: 0.7017 - val_loss: 0.4069 - val_accuracy: 0.8022
Epoch 2/3
582/582 [==============================] - 23s 40ms/step - loss: 0.3905 - accuracy: 0.8111 - val_loss: 0.3690 - val_accuracy: 0.8302
Epoch 3/3
582/582 [===============... | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
Fine-tune | base_model.trainable = True
base_learning_rate = 1e-5
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model.summary()
fine_tune_epochs = 3
total_epochs = initial_epochs + fine_tune_e... | Epoch 3/6
582/582 [==============================] - 56s 95ms/step - loss: 0.3367 - accuracy: 0.8987 - val_loss: 0.2620 - val_accuracy: 0.9366
Epoch 4/6
582/582 [==============================] - 48s 82ms/step - loss: 0.2734 - accuracy: 0.9287 - val_loss: 0.2230 - val_accuracy: 0.9483
Epoch 5/6
582/582 [===============... | MIT | notebooks/transfer learning - cats vs dogs.ipynb | quanhua92/TensorFlow-2.x-Cheatsheet |
Problem 1Apply your skills to classify protein foldType with Decision Tree Classifier Imports | from mmtfPyspark.ml import SparkMultiClassClassifier, datasetBalancer
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
import mltoolkit | _____no_output_____ | Apache-2.0 | 6-machine-learning/Problem-1.ipynb | HabibMrad/mmtf-workshop-2018 |
Configure Spark Session | spark = SparkSession.builder.appName("Problem-1").getOrCreate() | _____no_output_____ | Apache-2.0 | 6-machine-learning/Problem-1.ipynb | HabibMrad/mmtf-workshop-2018 |
TODO-1: Read in data from parquet file | parquetFile = './input_features/'
data = # Your Code Here # | _____no_output_____ | Apache-2.0 | 6-machine-learning/Problem-1.ipynb | HabibMrad/mmtf-workshop-2018 |
TODO-2: Select alpha, beta, alpha+beta foldtypes | data = # Your Code Here #
print(f"Total number of data: {data.count()}") | Total number of data: 2390
| Apache-2.0 | 6-machine-learning/Problem-1.ipynb | HabibMrad/mmtf-workshop-2018 |
TODO-3: Downsample data | label = 'foldType'
data = # Your Code Here #
print(f"Dataset size (balanced) : {data.count()}")
data.groupby(label).count().show() | Dataset size (balanced) : 1266
+--------+-----+
|foldType|count|
+--------+-----+
| beta| 626|
| alpha| 640|
+--------+-----+
| Apache-2.0 | 6-machine-learning/Problem-1.ipynb | HabibMrad/mmtf-workshop-2018 |
TODO-4: Decision Tree Classifier with PySpark | from pyspark.ml.classification import DecisionTreeClassifier
dtc = # Your Code Here: Make Decision Tree Classifier Class #
mcc = # Your Code Here: Use MulticlassClassifier wrapper on dtc#
matrics = # Your Code Here: fit data#
for k,v in matrics.items(): print(f"{k}\t{v}") |
Class Train Test
alpha 562 78
beta 561 65
Sample predictions: DecisionTreeClassifier
+----------------+-----------+----------+---------+--------+--------------------+------------+-------------+--------------------+----------+--------------+
|structureChainId| alpha| beta| coil|foldType| feat... | Apache-2.0 | 6-machine-learning/Problem-1.ipynb | HabibMrad/mmtf-workshop-2018 |
BONUS: Decision Tree Classifier with sklearn | from sklearn.tree import DecisionTreeClassifier
df = # Your Code Here: convert data to Pandas Dataframe #
dtc = # Your Code Here: Make Decision Tree Classifier Class #
mcc = # Your Code Here: Use MulticlassClassifier wrapper on dtc#
matrics = # Your Code Here: fit data#
for k,v in matrics.items(): print(f"{k}\t{v}")
s... | _____no_output_____ | Apache-2.0 | 6-machine-learning/Problem-1.ipynb | HabibMrad/mmtf-workshop-2018 |
Tabular core> Basic function to preprocess tabular data before assembling it in a `DataLoaders`. Initial preprocessing | #export
def make_date(df, date_field):
"Make sure `df[date_field]` is of the right date type."
field_dtype = df[date_field].dtype
if isinstance(field_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
field_dtype = np.datetime64
if not np.issubdtype(field_dtype, np.datetime64):
df[date_field... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Tabular - | #export
class _TabIloc:
"Get/set rows by iloc and cols by name"
def __init__(self,to): self.to = to
def __getitem__(self, idxs):
df = self.to.items
if isinstance(idxs,tuple):
rows,cols = idxs
cols = df.columns.isin(cols) if is_listy(cols) else df.columns.get_loc(cols)... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
TabularPandas Pipelines - | procs = [Normalize, Categorify, FillMissing, noop]
df = pd.DataFrame({'a':[0,1,2,1,1,2,0], 'b':[0,1,np.nan,1,2,3,4]})
to = TabularPandas(df, procs, cat_names='a', cont_names='b')
#Test setup and apply on df_main
test_eq(to.cat_names, ['a', 'b_na'])
test_eq(to['a'], [1,2,3,2,2,3,1])
test_eq(to['b_na'], [1,1,2,1,1,1,1])... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Integration example | path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
df_main,df_test = df.iloc[:10000].copy(),df.iloc[10000:].copy()
df_test.drop('salary', axis=1, inplace=True)
df_main.head()
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
cont_names = ['age', 'fnlwgt'... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Other target types Multi-label categories one-hot encoded label | def _mock_multi_label(df):
sal,sex,white = [],[],[]
for row in df.itertuples():
sal.append(row.salary == '>=50k')
sex.append(row.sex == ' Male')
white.append(row.race == ' White')
df['salary'] = np.array(sal)
df['male'] = np.array(sex)
df['white'] = np.array(white)
ret... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Not one-hot encoded | def _mock_multi_label(df):
targ = []
for row in df.itertuples():
labels = []
if row.salary == '>=50k': labels.append('>50k')
if row.sex == ' Male': labels.append('male')
if row.race == ' White': labels.append('white')
targ.append(' '.join(labels))
df['target'] = np.... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Regression | #export
@RegressionSetup
def setups(self, to:Tabular):
if self.c is not None: return
self.c = len(to.y_names)
return to
@RegressionSetup
def encodes(self, to:Tabular): return to
@RegressionSetup
def decodes(self, to:Tabular): return to
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Not being used now - for multi-modal | class TensorTabular(Tuple):
def get_ctxs(self, max_n=10, **kwargs):
n_samples = min(self[0].shape[0], max_n)
df = pd.DataFrame(index = range(n_samples))
return [df.iloc[i] for i in range(n_samples)]
def display(self, ctxs): display_df(pd.DataFrame(ctxs))
class TabularLine(pd.Series):
... | _____no_output_____ | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Export - | #hide
from nbdev.export import notebook2script
notebook2script() | Converted 00_torch_core.ipynb.
Converted 01_layers.ipynb.
Converted 02_data.load.ipynb.
Converted 03_data.core.ipynb.
Converted 04_data.external.ipynb.
Converted 05_data.transforms.ipynb.
Converted 06_data.block.ipynb.
Converted 07_vision.core.ipynb.
Converted 08_vision.data.ipynb.
Converted 09_vision.augment.ipynb.
Co... | Apache-2.0 | nbs/40_tabular.core.ipynb | yijinlee/fastai2 |
Optimización Author: Jesús Cid-Sueiro Jerónimo Arenas-García Versión: 0.1 (2019/09/13) 0.2 (2019/10/02): Solutions added Exercise: compute the minimum of a real-valued functionThe goal of this exercise is to implement and test optimization algorithms for the minimization of a given... | # <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
Part 1: The function and its derivatives.**Question 1.1**: Implement the following three methods:* Method **`f`**: given $w$, it returns the value of function $f(w)$.* Method **`df`**: given $w$, it returns the derivative of $f$ at $w$* Medhod **`d2f`**: given $w$, it returns the second derivative of $f$ at $w$ | # Funcion f
# <SOL>
# </SOL>
# First derivative
# <SOL>
# </SOL>
# Second derivative
# <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
Part 2: Gradient descent.**Question 2.1**: Implement a method **`gd`** that, given `w` and a learning rate parameter `rho` applies a single iteration of the gradien descent algorithm | # <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
**Question 2.2**: Apply the gradient descent to optimize the given function. To do so, start with an initial value $w=0$ and iterate $20$ times. Save two lists:* A list of succesive values of $w_n$* A list of succesive values of the function $f(w_n)$. | # <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
**Question 2.3**: Plot, in a single figure:* The given function, for values ranging from 0 to 20.* The sequence of points $(w_n, f(w_n))$. | # <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
You can check the effect of modifying the value of the learning rate. Part 2: Newton's method.**Question 3.1**: Implement a method **`newton`** that, given `w` and a learning rate parameter `rho` applies a single iteration of the Newton's method | # <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
**Question 3**: Apply the Newton's method to optimize the given function. To do so, start with an initial value $w=0$ and iterate $20$ times. Save two lists:* A list of succesive values of $w_n$* A list of succesive values of the function $f(w_n)$. | # <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
**Question 4**: Plot, in a single figure:* The given function, for values ranging from 0 to 20.* The sequence of points $(w_n, f(w_n))$. | # <SOL>
# </SOL> | _____no_output_____ | MIT | A1.Optimization/Optimization_student.ipynb | ML4DS/ML4all |
Test S-CNN baseline | %load_ext autoreload
%autoreload 2
import numpy as np
import os
import librosa
import glob
import sys
sys.path.insert(0,'../..')
from sed_endtoend.cnn.model import build_custom_cnn
from sed_endtoend.data_generator import DataGenerator
os.environ["CUDA_VISIBLE_DEVICES"]="1"
from params import *
# files parameters
N... | WARNING: Logging before flag parsing goes to stderr.
W1003 16:16:21.528877 140711985211136 deprecation_wrapper.py:119] From /home/pzinemanas/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.
W100... | MIT | exps/04_CNN_baseline/test.ipynb | pzinemanas/sed_endtoend |
CS109A Introduction to Data Science Standard Section 3: Multiple Linear Regression and Polynomial Regression **Harvard University****Fall 2019****Instructors**: Pavlos Protopapas, Kevin Rader, and Chris Tanner**Section Leaders**: Marios Mattheakis, Abhimanyu (Abhi) Vasishth, Robbert (Rob) Struyven | #RUN THIS CELL
import requests
from IPython.core.display import HTML
styles = requests.get("http://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/cs109.css").text
HTML(styles) | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
For this section, our goal is to get you familiarized with Multiple Linear Regression. We have learned how to model data with kNN Regression and Simple Linear Regression and our goal now is to dive deep into Linear Regression.Specifically, we will: - Load in the titanic dataset from seaborn- Learn a few ways to plo... | # Data and Stats packages
import numpy as np
import pandas as pd
# Visualization packages
import matplotlib.pyplot as plt
import seaborn as sns
sns.set() | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Extending Linear Regression Working with the Titanic Dataset from SeabornFor our dataset, we'll be using the passenger list from the Titanic, which famously sank in 1912. Let's have a look at the data. Some descriptions of the data are at https://www.kaggle.com/c/titanic/data, and here's [how seaborn preprocessed it](... | # Load the dataset from seaborn
titanic = sns.load_dataset("titanic")
titanic.head()
# checking for null values
chosen_vars = ['age', 'sex', 'class', 'embark_town', 'alone', 'fare']
titanic = titanic[chosen_vars]
titanic.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 6 columns):
age 714 non-null float64
sex 891 non-null object
class 891 non-null category
embark_town 889 non-null object
alone 891 non-null bool
fare 891 non-null float64
dtyp... | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**Exercise**: check the datatypes of each column and display the statistics (min, max, mean and any others) for all the numerical columns of the dataset. | ## your code here
titanic.dtypes
titanic.describe()
# %load 'solutions/sol1.py'
| _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**Exercise**: drop all the non-null *rows* in the dataset. Is this always a good idea? | ## your code here
titanic = titanic.dropna(axis=0)
titanic.info()
#inputation is an alternative to addressing null values
# %load 'solutions/sol2.py' | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Now let us visualize the response variable. A good visualization of the distribution of a variable will enable us to answer three kinds of questions:- What values are central or typical? (e.g., mean, median, modes)- What is the typical spread of values around those central values? (e.g., variance/stdev, skewness)- What... | fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(24, 6))
ax = ax.ravel()
sns.distplot(titanic['fare'], ax=ax[0])
ax[0].set_title('Seaborn distplot')
ax[0].set_ylabel('Normalized frequencies')
sns.violinplot(x='fare', data=titanic, ax=ax[1])
ax[1].set_title('Seaborn violin plot')
ax[1].set_ylabel('Frequencies')
sns.... | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
How do we interpret these plots? Train-Test Split | from sklearn.model_selection import train_test_split
titanic_train, titanic_test = train_test_split(titanic, train_size=0.7, random_state=99)
titanic_train = titanic_train.copy()
titanic_test = titanic_test.copy()
print(titanic_train.shape, titanic_test.shape) | (498, 6) (214, 6)
| MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Simple one-variable OLS **Exercise**: You've done this before: make a simple model using the OLS package from the statsmodels library predicting **fare** using **age** using the training data. Name your model `model_1` and display the summary | from statsmodels.api import OLS
import statsmodels.api as sm
# Your code here
# %load 'solutions/sol3.py'
age_ca = sm.add_constant(titanic_train['age'])
model_1 = OLS(titanic_train['fare'], age_ca).fit()
model_1.summary() | C:\Users\davidsong\Anaconda3\envs\109a\lib\site-packages\numpy\core\fromnumeric.py:2389: FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.
return ptp(axis=axis, out=out, **kwargs)
| MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Dealing with different kinds of variables In general, you should be able to distinguish between three kinds of variables: 1. Continuous variables: such as `fare` or `age`2. Categorical variables: such as `sex` or `alone`. There is no inherent ordering between the different values that these variables can take on. Thes... | titanic_orig = titanic_train.copy() | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Let us now examine the `sex` column and see the value counts. | titanic_train['sex'].value_counts() | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**Exercise**: Create a column `sex_male` that is 1 if the passenger is male, 0 if female. The value counts indicate that these are the two options in this particular dataset. Ensure that the datatype is `int`. | # your code here
titanic_train['sex_male'] = (titanic_train.sex == 'male').astype(int)
titanic_train['sex_male'].value_counts()
# %load 'solutions/sol4.py' | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Do we need a `sex_female` column, or a `sex_others` column? Why or why not?Now, let us look at `class` in greater detail. | titanic_train['class_Second'] = (titanic_train['class'] == 'Second').astype(int)
titanic_train['class_Third'] = 1 * (titanic_train['class'] == 'Third') # just another way to do it
titanic_train['class_Second'].value_counts()
titanic_train['class_Third'].value_counts()
titanic_train.info()
# This function automates the... | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Linear Regression with More Variables **Exercise**: Fit a linear regression including the new sex and class variables. Name this model `model_2`. Don't forget the constant! | # your code here
# %load 'solutions/sol5.py'
model_2 = sm.OLS(titanic_train['fare'],
sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third']])).fit()
# add constant just once for B0 value)
model_2.summary() | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Interpreting These Results 1. Which of the predictors do you think are important? Why?2. All else equal, what does being male do to the fare? Going back to the example from class3. What is the interpretation of $\beta_0$ and $\beta_1$?Beta 0 = male; beta 1 = male - female (differe... | sns.lmplot(x="age", y="fare", hue="sex", data=titanic_train, size=6) | C:\Users\davidsong\Anaconda3\envs\109a\lib\site-packages\seaborn\regression.py:546: UserWarning: The `size` paramter has been renamed to `height`; please update your code.
warnings.warn(msg, UserWarning)
| MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
The slopes seem to be different for male and female. What does that indicate?Let us now try to add an interaction effect into our model. | # It seemed like gender interacted with age and class. Can we put that in our model?
titanic_train['sex_male_X_age'] = titanic_train['age'] * titanic_train['sex_male']
model_3 = sm.OLS(
titanic_train['fare'],
sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third', 'sex_male_X_age']])
)... | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**What happened to the `age` and `male` terms?** | # It seemed like gender interacted with age and class. Can we put that in our model?
titanic_train['sex_male_X_class_Second'] = titanic_train['age'] * titanic_train['class_Second']
titanic_train['sex_male_X_class_Third'] = titanic_train['age'] * titanic_train['class_Third']
model_4 = sm.OLS(
titanic_train['fare'],... | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Polynomial Regression  Perhaps we now believe that the fare also depends on the square of age. How would we include this term in our model? | fig, ax = plt.subplots(figsize=(12,6))
ax.plot(titanic_train['age'], titanic_train['fare'], 'o')
x = np.linspace(0,80,100)
ax.plot(x, x, '-', label=r'$y=x$')
ax.plot(x, 0.04*x**2, '-', label=r'$y=c x^2$')
ax.set_title('Plotting Age (x) vs Fare (y)')
ax.set_xlabel('Age (x)')
ax.set_ylabel('Fare (y)')
ax.legend(); | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**Exercise**: Create a model that predicts fare from all the predictors in `model_4` + the square of age. Show the summary of this model. Call it `model_5`. Remember to use the training data, `titanic_train`. | # your code here
# %load 'solutions/sol6.py'
titanic_train['age^2'] = titanic_train['age'] **2
model_5 = sm.OLS(
titanic_train['fare'],
sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third', 'sex_male_X_age',
'sex_male_X_class_Second', 'sex_male_X_class_... | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Looking at All Our Models: Model Selection What has happened to the $R^2$ as we added more features? Does this mean that the model is better? (What if we kept adding more predictors and interaction terms? **In general, how should we choose a model?** We will spend a lot more time on model selection and learn about way... | models = [model_1, model_2, model_3, model_4, model_5]
fig, ax = plt.subplots(figsize=(12,6))
ax.plot([model.df_model for model in models], [model.rsquared for model in models], 'x-')
ax.set_xlabel("Model degrees of freedom")
ax.set_title('Model degrees of freedom vs training $R^2$')
ax.set_ylabel("$R^2$"); | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**What about the test data?**We added a lot of columns to our training data and must add the same to our test data in order to calculate $R^2$ scores. | # Added features for model 1
# Nothing new to be added
# Added features for model 2
titanic_test = pd.get_dummies(titanic_test, columns=['sex', 'class'], drop_first=True)
# Added features for model 3
titanic_test['sex_male_X_age'] = titanic_test['age'] * titanic_test['sex_male']
# Added features for model 4
titanic_... | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**Calculating R^2 scores** | from sklearn.metrics import r2_score
r2_scores = []
y_preds = []
y_true = titanic_test['fare']
# model 1
y_preds.append(model_1.predict(sm.add_constant(titanic_test['age'])))
# model 2
y_preds.append(model_2.predict(sm.add_constant(titanic_test[['age', 'sex_male', 'class_Second', 'class_Third']])))
# model 3
y_pred... | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Regression Assumptions. Should We Even Regress Linearly?  **Question**: What are the assumptions of a linear regression model? We find that the answer to this question can be found on closer examimation of $\epsilon$. What is $\epsilon$? It is assumed that $\epsilon$ i... | # your code here
# %load 'solutions/sol7.py'
predictors = sm.add_constant(titanic_train[['age', 'sex_male', 'class_Second', 'class_Third', 'sex_male_X_age',
'sex_male_X_class_Second', 'sex_male_X_class_Third', 'age^2']])
y_hat = model_5.predict(predictors)
residuals = titanic_tr... | Mean of residuals: 4.582536938043967e-13
| MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
**What can you say about the assumptions of the model?** ---------------- End of Standard Section--------------- Extra: Visual exploration of predictors' correlationsThe dataset for this problem contains 10 simulated predictors and a response variable. | # read in the data
data = pd.read_csv('../data/dataset3.txt')
data.head()
# this effect can be replicated using the scatter_matrix function in pandas plotting
sns.pairplot(data); | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Predictors x1, x2, x3 seem to be perfectly correlated while predictors x4, x5, x6, x7 seem correlated. | data.corr()
sns.heatmap(data.corr()) | _____no_output_____ | MIT | content/sections/section3/notebook/cs109a_section_3.ipynb | songdavidb/2019-CS109A |
Example 3. CNN + DDAHere, we train the same CNN as in previous notebook but applying the Direct Domain Adaptation method (DDA) to reduce the gap between MNIST and MNIST-M datasets. -------This code is modified from [https://github.com/fungtion/DANN_py3](https://github.com/fungtion/DANN_py3). | import os
import sys
import tqdm
import random
import numpy as np
from numpy.fft import rfft2, irfft2, fftshift, ifftshift
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.nn as nn
import torch.utils.data
from torchvision import datasets
from torchvision import transforms
from components.... | _____no_output_____ | MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Init paths | # Paths to datasets
source_dataset_name = 'MNIST'
target_dataset_name = 'mnist_m'
source_image_root = os.path.join('dataset', source_dataset_name)
target_image_root = os.path.join('dataset', target_dataset_name)
os.makedirs('./dataset', exist_ok=True)
# Where to save outputs
model_root = './out_ex3_cnn_da'
os.makedirs... | _____no_output_____ | MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Init training | cuda = True
cudnn.benchmark = True
# Hyperparameters
lr = 1e-3
batch_size = 128
image_size = 28
n_epoch = 100
# manual_seed = random.randint(1, 10000)
manual_seed = 222
random.seed(manual_seed)
torch.manual_seed(manual_seed)
print(f'Random seed: {manual_seed}') | Random seed: 222
| MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Data | # Transformations / augmentations
img_transform_source = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor(),
transforms.Normalize(mean=(0.1307,), std=(0.3081,)),
transforms.Lambda(lambda x: x.repeat(3, 1, 1)),
])
img_transform_target = transforms.Compose([
transforms.Resize(i... | _____no_output_____ | MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Direct Domain Adaptation (DDA) Average auto-correlationFor entire dataset | def get_global_acorr_for_loader(loader):
""" The average auto-correlation of all images in the dataset """
global_acorr = np.zeros((3, 28, 15), dtype=np.complex128)
prog_bar = tqdm.tqdm(loader)
for data, _ in prog_bar:
data_f = np.fft.rfft2(data, s=data.shape[-2:], axes=(-2, -1))
# Auto-... | Load global acorr
| MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Average cross-correlationPick a random pixel(-s) from each image in the dataset and average | # Window size
crop_size = 1
print(f'Use the crop size for xcorr = {crop_size}')
def crop_ref(x, n=1, edge=5):
"""Crop a window from the image
Args:
x(np.ndarray): image [c, h, w]
n(int): window size
edge(int): margin to avoid from edges of the image
"""
if n % 2 == 0: n+=1;
k... | Load global xcorr
| MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Train Loader | def flip_channels(x):
"""Reverse polarity of random channels"""
flip_matrix = np.random.choice([-1, 1], 3)[..., np.newaxis, np.newaxis]
return (x * flip_matrix).astype(np.float32)
def shuffle_channels(x):
"""Change order of channels"""
return np.random.permutation(x)
def normalize_channels(x):
... | Image shape: (3, 28, 28) Label: 5
| MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Test Loader | class DDALoaderTest(torch.utils.data.Dataset):
def __init__(self, loader1, avg_acorr2, avg_xcorr1):
super().__init__()
self.loader1 = loader1
self.avg_acorr2 = avg_acorr2
self.avg_xcorr1 = avg_xcorr1
def __len__(self):
return len(self.loader1)
def __... | _____no_output_____ | MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.