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 |
|---|---|---|---|---|---|
Notebook Day 24Well, I got it to brute force search at ~160,000 ids per second. That's not fast enough to crack a 14-digit number.The next step would be to somehow-optimize my programmatically-generated code. But, I'm stuck on that for now. | from output import eval_license
from itertools import product
from tqdm import tqdm
for serial in tqdm(product(range(9,0,-1), repeat=14)):
result = eval_license(serial)
if result:
break | 46078644it [04:44, 161786.75it/s]
| MIT | src/24/serial_finder.ipynb | j-carson/advent_2021 |
Figures 2 and 5 for gather paper | %matplotlib inline
import pylab
import pandas as pd | _____no_output_____ | BSD-3-Clause | gather/gather_report.ipynb | dib-lab/2021-paper-sourmash-gather-pipeline |
Preparation: load genome-grist summary CSVs | class SampleDFs:
def __init__(self, name, all_df, left_df, gather_df, names_df):
self.name = name
self.all_df = all_df
self.left_df = left_df
self.gather_df = gather_df
self.names_df = names_df
def load_sample_dfs(name, sample_id, subsample_to=None, debug=False):
print(f... | loading sample SRR606249
loading sample SRR1976948
loading sample p8808mo11
loading sample SRR12324253
| BSD-3-Clause | gather/gather_report.ipynb | dib-lab/2021-paper-sourmash-gather-pipeline |
Figure 2: K-mer decomposition of a metagenome into constituent genomes. |
fig, (ax1, ax2) = pylab.subplots(1, 2, figsize=(10, 8), constrained_layout=True)
#pylab.plot(left_df.covered_bp / 1e6, left_df.iloc[::-1].index, 'b.', label='mapped bp to this genome')
ax1.plot(podar_mock.gather_df.intersect_bp / 1e6, podar_mock.gather_df.iloc[::-1].index, 'g<',
label='total k-mers matched')... | _____no_output_____ | BSD-3-Clause | gather/gather_report.ipynb | dib-lab/2021-paper-sourmash-gather-pipeline |
Figure 5: Hash-based k-mer decomposition of a metagenome into constituent genomes compares well to bases covered by read mapping. | import matplotlib.pyplot as plt
fig, axes = plt.subplots(figsize=(20, 12), nrows=2, ncols=2)
samples = (podar_mock, zymo_mock, gut, oil_well)
for n, (ax, sample) in enumerate(zip(axes.flat, samples)):
ax.plot(sample.left_df.index, sample.left_df.covered_bp / 1e6, 'b*', label='genome bases covered by mapped reads'... | _____no_output_____ | BSD-3-Clause | gather/gather_report.ipynb | dib-lab/2021-paper-sourmash-gather-pipeline |
**In this project we implement the Identification system using Machine Learning concepts such as Principal Component Analysis (PCA) and Support Vector Machine (SVM).** Steps Involved:- Importing Libraries- Loading the Dataset- Data Exploration- Splitting the dataset - Compute PCA(eigen faces) - Train a SVM classifica... | #downnlading datasets sklearn
from sklearn.datasets import fetch_lfw_people
#todo import other libraries such sklearn for pca,svc,classification report,plotting | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**Loading the dataset** | # Download the data, if not already on disk and load it as numpy arrays
lfw_people = fetch_lfw_people('data', min_faces_per_person=70, resize=0.4)
# introspect the images arrays to find the shapes (for plotting)
#todo:check shape
# for machine learning we use the data directly (as relative pixel
# position info is igno... | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**Data Exploration** | # plot and explore images and their respective classes
# hint: use matplotlib | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**Splitting the dataset** | #use sklearn test-train split | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**Compute PCA**We can now compute a PCA (eigenfaces) on the face dataset (treated as unlabeled dataset): unsupervised feature extraction / dimensionality reduction. | #Apply the PCA algorithm on the training dataset which computes EigenFaces.
#Here, take n_components = 150 or 300 means we extract the top 150 (or 300) Eigenfaces from the algorithm.
#Also print the time taken to apply this algorithm.
# TODO: Create an instance of PCA, initializing with n_components=n_components and... | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**Train a SVM classification model**Fit a SVM classifier to the training set.Use GridSearchCV to find a good set of parameters for the classifier. | #todo : SVM with Gridsearch algo | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**Evaluation of the model quality on the test set** | #TODO: Test the model and Generate a classification report | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**plot the eigen faces for your visualisation** | #TODO:plot most significant eigen faces | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science |
**Conclusion** | _____no_output_____ | MIT | Face-Recognition-pca-svm/Facial_Recognition(Exercise).ipynb | abhisngh/Data-Science | |
Check a sample from validation dataset | # to see one image
cover,*rest = next(iter(valid_set))
_, H, W = cover.size()
cover = cover[None].to(device)
text = "We are busy in Neural Networks project. Anyhow, how is your day going?"
payload = make_payload(W, H, data_depth, text)
payload = payload.to(device)
#generated = encoder.forward(cover, payload)
generated ... | Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
| MIT | S_GAN_image.ipynb | garg-akash/Steganography_GANs |
Testing begins (from a loaded model) Test1 - Save steganographic images | ##Take all images from test folder (one by one) and message requested by user to encode
from imageio import imread, imwrite
epochs = 64
data_depth = 4
test_folder = "div2k/myval/_"
save_dir = os.mkdir(os.path.join("div2k/myval",str(data_depth)+"_"+str(epochs)))
for filename in os.listdir(test_folder):
print(os... | div2k/myval/_/0805.png
div2k/myval/_/0804.png
div2k/myval/_/0833.png
div2k/myval/_/0855.png
div2k/myval/_/0874.png
div2k/myval/_/0894.png
| MIT | S_GAN_image.ipynb | garg-akash/Steganography_GANs |
Test2 - Take a steganographic image from a folder and decode | ##[Individual]Take an image requested by user to decode
from imageio import imread, imwrite
steg_folder = "div2k/myval/4_64"
filename = "4_64_0855.png"
image = imread(os.path.join(steg_folder,filename), pilmode='RGB') / 127.5 - 1.0
plt.imshow(image)
image = torch.FloatTensor(image).permute(2, 1, 0).unsqueeze(0)
text_... | WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:22: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clo... | MIT | S_GAN_image.ipynb | garg-akash/Steganography_GANs |
Test3 - Encode to decode in one cell | ##Input to outut (both encode decode in one cell)
from imageio import imread, imwrite
cover_im = imread("div2k/myval/_/0805.png", pilmode='RGB') / 127.5 - 1.0
plt.imshow(cover_im)
cover = torch.FloatTensor(cover_im).permute(2, 1, 0).unsqueeze(0)
cover_size = cover.size()
# _, _, height, width = cover.size()
text = "We... | Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:22: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_gr... | MIT | S_GAN_image.ipynb | garg-akash/Steganography_GANs |
Generate Difference Image | from skimage.metrics import structural_similarity as ssim
from imageio import imread, imwrite
diff_epochs = 64
diff_data_depth = 4
cover_folder = "div2k/myval/_"
steg_folder = "div2k/myval/"+str(diff_data_depth)+"_"+str(diff_epochs)
for filename in os.listdir(cover_folder):
print(os.path.join(cover_folder,filenam... | div2k/myval/_/0805.png
| MIT | S_GAN_image.ipynb | garg-akash/Steganography_GANs |
**[Adversarial Disturbances for Controller Verification](http://proceedings.mlr.press/v144/ghai21a/ghai21a.pdf)**[](https://colab.research.google.com/github/google/nsc-tutorial/blob/main/controller-verification.ipynb) HousekeepingImports [jax]... | #@title
import jax
import itertools
import numpy as onp
import jax.numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from jax.numpy.linalg import inv, pinv
from scipy.linalg import solve_discrete_are as dare
from jax import jit, grad, hessian
from IPython import display
from toolz.dicttoolz imp... | _____no_output_____ | MIT | controller-verification.ipynb | google/nsc-tutorial |
A simple dynamical systemDefines a discrete-time [double-integrator](https://en.wikipedia.org/wiki/Double_integrator) -- a simple linear dynamical system that mirrors 1d kinematics -- along with a quadratic cost.Below $\mathbf{x}_t$ is the state, $\mathbf{u}_t$ is the control input (or action), $\mathbf{w}_t$ is the d... | dx, du, T = 2, 1, 100
A, B = np.array([[1.0, 1.0], [0.0, 1.0]]), np.array([[0.0], [1.0]])
Q, R = np.eye(dx), np.eye(du)
dyn = lambda x, u, w, t: A @ x + B @ u + w
cost = lambda x, u, t: x.T @ A @ x + u.T @ R @ u
# A basic control loop.
# (x, z) is the environ-controller state.
# w is disturbance and z_w disturbance ... | WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
| MIT | controller-verification.ipynb | google/nsc-tutorial |
Control AlgorithmsThe segment below puts forth a few basic control strategies, whose performance characteristics we would like to verify.+ **Zero Control**: Executes $\mathbf{u}=\mathbf{0}$.+ **LQR / H2**: A discrete-time [linear-quadratic regulator](https://en.wikipedia.org/wiki/Linear%E2%80%93quadratic_regulator).+ ... | #@title
def zero():
return lambda x, z, t: (np.zeros(du), z)
def h2(A=A, B=B, Q=Q, R=R):
P = dare(A, B, Q, R)
K = - inv(R + B.T @ P @ B) @ (B.T @ P @ A)
return lambda x, z, t: (K @ x, z)
def h2nonstat(A=A, B=B, Q=Q, R=R, T=T):
dx, du = B.shape
P, K = [np.zeros((dx, dx)) for _ in range(T + 1... | _____no_output_____ | MIT | controller-verification.ipynb | google/nsc-tutorial |
[Memory Online Trust Region](https://arxiv.org/abs/2012.06695) (**MOTR**) disturbancesThis is an online learning approach to disturbance generation, akin to nonstochastic control but with the role of control and disturbance swapped. | # Author: Udaya Ghai (ughai@cs.princeton.edu)
def motr(A=A, B=B, Q=Q, R=R, r_off=0.5, r_E= 1.0, T=T, H=3, M=3, lr=0.001, dyn=dyn, cost=cost):
dx, du = B.shape
def proxy(E, off, U, X):
x = X[0]
for h in range(H):
w = np.tensordot(E, U[h: h + M], axes=([0, 2], [0, 1])) + off
... | _____no_output_____ | MIT | controller-verification.ipynb | google/nsc-tutorial |
Aim:* Extract features for logistic regression given some text* Implement logistic regression from scratch* Apply logistic regression on a natural language processing task* Test logistic regressionWe will be using a data set of tweets. Import functions and data | import nltk
from nltk.corpus import twitter_samples
import pandas as pd
nltk.download('twitter_samples')
nltk.download('stopwords')
import re
import string
import numpy as np
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import TweetTokenizer
#process_tweet(): cle... | _____no_output_____ | MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
Prepare the data* The `twitter_samples` contains subsets of 5,000 positive tweets, 5,000 negative tweets, and the full set of 10,000 tweets. | # select the set of positive and negative tweets
all_positive_tweets = twitter_samples.strings('positive_tweets.json')
all_negative_tweets = twitter_samples.strings('negative_tweets.json') | _____no_output_____ | MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
* Train test split: 20% will be in the test set, and 80% in the training set. | # split the data into two pieces, one for training and one for testing
#############################################################
test_pos = all_positive_tweets[4000:]
train_pos = all_positive_tweets[:4000]
test_neg = all_negative_tweets[4000:]
train_neg = all_negative_tweets[:4000]
train_x = train_pos + tr... | _____no_output_____ | MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
* Create the numpy array of positive labels and negative labels. | # combine positive and negative labels
train_y = np.append(np.ones((len(train_pos), 1)), np.zeros((len(train_neg), 1)), axis=0)
test_y = np.append(np.ones((len(test_pos), 1)), np.zeros((len(test_neg), 1)), axis=0) | _____no_output_____ | MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
* Create the frequency dictionary using the `build_freqs()` function. | # create frequency dictionary
#############################################################
freqs = build_freqs(train_x,train_y)
# check the output
print("type(freqs) = " + str(type(freqs)))
print("len(freqs) = " + str(len(freqs.keys()))) | type(freqs) = <class 'dict'>
len(freqs) = 11339
| MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
* HERE, The `freqs` dictionary is the frequency dictionary that's being built.
* The key is the tuple (word, label), such as ("happy",1) or ("happy",0). The value stored for each key is the count of how many times the word "happy" was associated with a positive label, or how many times "happy" was associated with a n... | # Example
print('This is an example of a positive tweet: \n', train_x[0])
print('\nThis is an example of the processed version of the tweet: \n', process_tweet(train_x[0])) | This is an example of a positive tweet:
#FollowFriday @France_Inte @PKuchly57 @Milipol_Paris for being top engaged members in my community this week :)
This is an example of the processed version of the tweet:
['followfriday', 'top', 'engag', 'member', 'commun', 'week', ':)']
| MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
Logistic regression : Sigmoid$$ h(z) = \frac{1}{1+\exp^{-z}} $$It maps the input 'x' to a value that ranges between 0 and 1, and so it can be treated as a probability. | def sigmoid(z):
# calculate the sigmoid of z
#############################################################
h = 1/(1+np.exp(-z))
return h | _____no_output_____ | MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
Logistic regression: regression and a sigmoidLogistic regression takes a regular linear regression, and applies a sigmoid to the output of the linear regression.Logistic regression$$ h(z) = \frac{1}{1+\exp^{-z}}$$$$z = \theta_0 x_0 + \theta_1 x_1 + \theta_2 x_2 + ... \theta_N x_N$$ Update the weights:Gradient Descent... | def gradientDescent(x, y, theta, alpha, num_iters):
# get 'm', the number of rows in matrix x
m = len(x)
for i in range(0, num_iters):
# get z, the dot product of x and theta
#############################################################
z = np.dot(x,theta)
... | _____no_output_____ | MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
Extracting the features* Given a list of tweets, extract the features and store them in a matrix. You will extract two features. * The first feature is the number of positive words in a tweet. * The second feature is the number of negative words in a tweet. * Then train your logistic regression classifier on the... | def extract_features(tweet, freqs):
'''
Input:
tweet: a list of words for one tweet
freqs: a dictionary corresponding to the frequencies of each tuple (word, label)
Output:
x: a feature vector of dimension (1,3)
'''
# tokenizes, stems, and removes stopwords
###... | [[1. 0. 0.]]
| MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
Training Your ModelTo train the model:* Stack the features for all training examples into a matrix `X`. * Call `gradientDescent` | # collect the features 'x' and stack them into a matrix 'X'
X = np.zeros((len(train_x), 3))
for i in range(len(train_x)):
X[i, :]= extract_features(train_x[i], freqs)
# training labels corresponding to X
Y = train_y
# Apply gradient descent
J, theta = gradientDescent(X, Y, np.zeros((3, 1)), 1e-9, 1500)
... | The cost after training is 0.24215613.
| MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
Test logistic regressionPredict whether a tweet is positive or negative.* Given a tweet, process it, then extract the features.* Apply the model's learned weights on the features to get the logits.* Apply the sigmoid to the logits to get the prediction (a value between 0 and 1).$$y_{pred} = sigmoid(\mathbf{x} \cdot \t... | def predict_tweet(tweet, freqs, theta):
'''
Input:
tweet: a string
freqs: a dictionary corresponding to the frequencies of each tuple (word, label)
theta: (3,1) vector of weights
Output:
y_pred: the probability of a tweet being positive or negative
'''
... | I am happy -> 0.518581
I am bad -> 0.494339
this movie should have been great. -> 0.515331
great -> 0.515464
great great -> 0.530899
great great great -> 0.546275
great great great great -> 0.561562
| MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
Check performance using the test set | def test_logistic_regression(test_x, test_y, freqs, theta):
"""
Input:
test_x: a list of tweets
test_y: (m, 1) vector with the corresponding labels for the list of tweets
freqs: a dictionary with the frequency of each pair (or tuple)
theta: weight vector of dimension (3, 1... | 2000
(2000,)
(2000,)
Logistic regression model's accuracy = 0.9950
| MIT | lab7/LogisticRegression-Tweets.ipynb | modhvadiyac25/077_ChetanModhavadiya |
import data | import os
import glob
from PIL import Image
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
def read_feature(folder, num):
filename = glob.glob(os.path.join(folder, '*'))
img_arr = np.zeros([len(filename), 100, 100, 3])
label =... | (8076, 100, 100, 3)
(8076,)
Training data shape (7268, 100, 100, 3)
| MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
Define trainning function | def train_data(model):
loss = []
acc = []
val_loss = []
val_acc = []
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=3)
tensorboard = tf.keras.callbacks.TensorBoard(log_dir='logs/{}'.format('model_name'))
hist = model.fit(X_train, y_train,
... | _____no_output_____ | MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
Define a VGG network | def VGG(activ):
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(64, (3,3), padding='same', activation=activ, input_shape=(100, 100, 3)),
tf.keras.layers.MaxPool2D(padding='same'),
tf.keras.layers.Conv2D(128, (3,3), padding='same', activation=activ),
tf.keras.layers.MaxPool2D(pa... | _____no_output_____ | MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
Define a DNN model | def dnnmodel(n, activ):
param = []
model = tf.keras.Sequential([])
model.add(tf.keras.layers.Flatten(input_shape=(100, 100, 3)))
for i in range(n):
model.add(tf.keras.layers.Dense(100, activation=activ))
model.add(tf.keras.layers.Dense(2, activation='softmax'))
# model.summary()
# mo... | _____no_output_____ | MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
Trainning with VGG VGG with activation "relu" | activ = 'relu'
model_VGG1, param_VGG1 = VGG(activ)
loss_VGG1, val_loss_VGG1, hist_VGG1= train_data(model_VGG1) | WARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
_________________________... | MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
Define the function for plots | def plot_acc_and_loss(hist):
acc = hist.history['acc']
loss = hist.history['loss']
val_acc = hist.history['val_acc']
val_loss = hist.history['val_loss']
plt.plot(acc, 'r-o')
plt.title("Trainning accuracy")
plt.show()
plt.plot(loss, 'g-o')
plt.title("Trainning loss")
plt... | _____no_output_____ | MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
Calculate sensitivity and specificity | from sklearn.metrics import confusion_matrix
predictions = model_VGG1.predict(X_val)
y_val = np.argmax(y_val, axis=-1)
predictions = np.argmax(predictions, axis=-1)
c = confusion_matrix(y_val, predictions)
print('Confusion matrix:\n', c)
print('sensitivity', c[0, 0] / (c[0, 1] + c[0, 0]))
print('specificity', c[1, 1] ... | Confusion matrix:
[[428 29]
[ 12 339]]
sensitivity 0.936542669584245
specificity 0.9658119658119658
| MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
VGG with activation "relu" | activ = 'tanh'
model_VGG2, param_VGG2 = VGG(activ)
loss_VGG2, val_loss_VGG2, hist_VGG2= train_data(model_VGG2)
plot_acc_and_loss(hist_VGG2)
predictions = model_VGG2.predict(X_val)
y_val1 = np.argmax(y_val, axis=-1)
predictions = np.argmax(predictions, axis=-1)
c = confusion_matrix(y_val1, predictions)
print('Confusion ... | Confusion matrix:
[[450 18]
[ 22 318]]
sensitivity 0.9615384615384616
specificity 0.9352941176470588
| MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
DNN | activ = 'relu'
model_DNN, param1_DNN = dnnmodel(15, activ)
loss_DNN, val_loss_DNN, hist_DNN= train_data(model_DNN)
plot_acc_and_loss(hist_DNN)
predictions = model_DNN.predict(X_val)
y_val1 = np.argmax(y_val, axis=-1)
predictions = np.argmax(predictions, axis=-1)
c = confusion_matrix(y_val1, predictions)
print('Confusio... | Confusion matrix:
[[448 20]
[ 65 275]]
sensitivity 0.9572649572649573
specificity 0.8088235294117647
| MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
ResNet | from tensorflow.keras.applications import ResNet50
def resnet():
input_tensor = tf.keras.layers.Input(shape=(100, 100, 3))
model = ResNet50(include_top=True, weights=None, input_tensor=input_tensor, input_shape=None, pooling=None, classes=2)
param = model.count_params()
model.compile(optimizer=tf.train... | Confusion matrix:
[[404 64]
[ 45 295]]
sensitivity 0.8632478632478633
specificity 0.8676470588235294
| MIT | BME590_Final_Project_keras.ipynb | tiffanylin43/BME590L_Final_Project_addon |
Import the needed libraries | import PicSureHpdsLib
import pandas
import matplotlib | _____no_output_____ | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Create an instance of the datasource adapter and get a reference to the data resource | adapter = PicSureHpdsLib.BypassAdapter("http://pic-sure-hpds-nhanes:8080/PIC-SURE")
resource = adapter.useResource() | _____no_output_____ | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Get a listing of all "demographics" entries in the data dictionary. Show what actions can be done with the "demographic_results" object | demographic_entries = resource.dictionary().find("\\demographics\\")
demographic_entries.help() |
[HELP] PicSureHpdsLib.Client(connection).useResource(uuid).dictionary().find(term)
.count() Returns the number of entries in the dictionary that match the given term
.keys() Return the keys of the matching entries
.entries() Return a list of matching dict... | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Examine the demographic_entries results by converting it into a pandas DataFrame | demographic_entries.DataFrame()
resource.query().help()
resource.query().filter().help()
query_male = resource.query()
query_male.filter().add("\\demographics\\SEX\\", ["male"])
query_female = resource.query()
query_female.filter().add("\\demographics\\SEX\\", ["female"])
field_age = resource.dictionary().find("\\AGE\... | .__________[ Query.Select() has NO SELECTIONS ]____________________________________________________________________________________________________________
.__________[ Query.Require() Settings ]_________________________________________________________________________________________
| _key____________________________... | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Convert the query results for females into a DataFrame and plot it by BMI and Age | df_f = query_female.getResultsDataFrame()
plot_f = df_f.plot.scatter(x="\\demographics\\AGE\\", y="\\examination\\body measures\\Body Mass Index (kg per m**2)\\", c="#ffbabb40")
# ____ Uncomment if graphs are not displaying ____
#plot_f.plot()
#matplotlib.pyplot.show() | _____no_output_____ | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Convert the query results for males into a DataFrame and plot it by BMI and Age | df_m = query_male.getResultsDataFrame()
plot_m = df_m.plot.scatter(x="\\demographics\\AGE\\", y="\\examination\\body measures\\Body Mass Index (kg per m**2)\\", c="#5a7dd040")
# ____ Uncomment if graphs are not displaying ____
#plot_m.plot()
#matplotlib.pyplot.show() | _____no_output_____ | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Replot the results using a single DataFrame containing both male and female | d = resource.dictionary()
criteria = []
criteria.extend(d.find("\\SEX\\").keys())
criteria.extend(d.find("\\Body Mass Index").keys())
criteria.extend(d.find("\\AGE\\").keys())
query_unified = resource.query()
query_unified.require().add(criteria)
df_mf = query_unified.getResultsDataFrame()
# map a color field for the... | _____no_output_____ | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Replot data but trim outliers | q = df_mf["\\examination\\body measures\\Body Mass Index (kg per m**2)\\"].quantile(0.9999)
# create a masked array to remove outliers
test = df_mf.mask(df_mf["\\examination\\body measures\\Body Mass Index (kg per m**2)\\"] > q)
# plot data
plot_mf = test.plot.scatter(x="\\demographics\\AGE\\", y="\\examination\\body... | _____no_output_____ | Apache-2.0 | Jupyter Notebook Examples/Python/HPDS/4) BMI-Age Plot by Gender.ipynb | hms-dbmi/PIC-SURE-2-Jupyter-Examples |
Appendix (Application of the mutual fund theorem) | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import FinanceDataReader as fdr
import pandas as pd
ticker_list = ['069500']
df_list = [fdr.DataReader(ticker, '2015-01-01', '2016-12-31')['Change'] for ticker in ticker_list]
df = pd.concat(df_list, axis=1)
#df.columns = ['005930', '000660', '00... | _____no_output_____ | MIT | Advanced/2. Pension Planning using HJB eqn.ipynb | coorung/Finance |
(5B), (7B) | # g_B = 0 # in case of age over retirement (Second scenario in Problem(B))
X0 = 150. # Saving account at the beginning
l = 3
t = 45 # age in case of age over retirement (Second scenario in Problem(B))
gamma = -3. # risk averse measure
phi = rf + (alpha -rf)**2 / (2 * sigma**2 * (1-gamma)) # temporal function for f_B
r... | [0.83630489]
| MIT | Advanced/2. Pension Planning using HJB eqn.ipynb | coorung/Finance |
Simulation | import time
start = time.time()
dt = 1
def mu(t): # Mortality rate in next year
value = (10**(beta + delta*(t+dt) - 10)- 10**(beta + delta*t - 10))/(delta * np.log(10))
return value
n_simulation = 10000
Asset = np.empty(37)
Asset_stack = []
C_stack = []
for i in range(n_simulation):
Asset[0] = 150 # i... | 12911.317305803299
| MIT | Advanced/2. Pension Planning using HJB eqn.ipynb | coorung/Finance |
Check the Simulation Result | Asset_mean = np.mean(Asset_stack, axis=0) #(37,)
C_mean = np.mean(C_stack, axis=0) # (16,1)
plt.rcParams['figure.figsize'] = [30, 15]
plt.rcParams.update({'font.size': 30})
plt.title('Retirement planning')
plt.xlabel('Age')
plt.ylabel('Won(1000000)')
plt.plot(range(45,81),Asset_mean[:-1], label='Wealth')
plt.plot(ran... | _____no_output_____ | MIT | Advanced/2. Pension Planning using HJB eqn.ipynb | coorung/Finance |
前言本文主要讨论如何把pandas移植到spark, 他们的dataframe共有一些特性如操作方法和模式。pandas的灵活性比spark强, 但是经过一些改动spark基本上能完成相同的工作。同时又兼具了扩展性的优势,当然他们的语法和用法稍稍有些不同。 主要不同处: 分布式处理pandas只能单机处理, 把dataframe放进内存计算。spark是集群分布式地,可以处理的数据可以大大超出集群的内存数。 懒执行spark不执行任何`transformation`直到需要运行`action`方法,`action`一般是存储或者展示数据的操作。这种将`transformation`延后的做法可以让spark调度知道所有的执行情况,... | import pandas as pd
import pyspark.sql
import pyspark.sql.functions as sf
from pyspark.sql import SparkSession | _____no_output_____ | Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
Projectionspandas的投影可以直接通过[]操作 | person_pd = pd.read_csv('data/persons.csv')
person_pd[["name", "sex", "age"]] | _____no_output_____ | Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
pyspark也可以直接`[]`来选取投影, 但是这是一个语法糖, 实际是用了`select`方法 | spark = SparkSession.builder \
.master("local[*]") \
.config("spark.driver.memory","6G") \
.getOrCreate()
#person_pd[['age','name']]
person_sp = spark.read.option("inferSchema", True) \
.option("header", True) \
.csv('data/persons.csv')
person_sp.show()
person_sp[['age', 'name']].show() | +---+-------+
|age| name|
+---+-------+
| 23| Alice|
| 21| Bob|
| 27|Charlie|
| 24| Eve|
| 19|Frances|
| 31| George|
+---+-------+
| Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
简单transformation spark的`dataframe.select`实际上接受任何column对象, 一个column对象概念上是dataframe的一列。一列可以是dataframe的一列输入,也可以是一个计算结果或者多个列的transformation结果。 以改变一列为大写为例: | ret = pd.DataFrame(person_pd['name'].apply(lambda x: x.upper()))
ret
result = person_sp.select(
sf.upper(person_sp.name)
)
result.show() | +-----------+
|upper(name)|
+-----------+
| ALICE|
| BOB|
| CHARLIE|
| EVE|
| FRANCES|
| GEORGE|
+-----------+
| Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
给dataframe增加一列 pandas给dataframe增加一列很方便,直接给df赋值就行了。spark需要使用`withColumn`函数。 | def create_salutation(row):
sex = row[0]
name = row[1]
if sex == 'male':
return 'Mr '+name
else:
return "Mrs "+name
result = person_pd.copy()
result['salutation'] = result[['sex','name']].apply(create_salutation, axis=1, result_type='expand')
result
result = person_sp.withColumn(
"salutation",
... | +---+------+-------+------+-----------+
|age|height| name| sex| salutation|
+---+------+-------+------+-----------+
| 23| 156| Alice|female| Mrs Alice|
| 21| 181| Bob| male| Mr Bob|
| 27| 176|Charlie| male| Mr Charlie|
| 24| 167| Eve|female| Mrs Eve|
| 19| 172|Frances|female|Mrs Frances|
... | Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
过滤 | result = person_pd[person_pd['age'] > 20]
result | _____no_output_____ | Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
spark支持三种过滤写法 | person_sp.filter(person_sp['age'] > 20).show()
person_sp[person_sp['age'] > 20].show()
person_sp.filter('age > 20').show() | +---+------+-------+------+
|age|height| name| sex|
+---+------+-------+------+
| 23| 156| Alice|female|
| 21| 181| Bob| male|
| 27| 176|Charlie| male|
| 24| 167| Eve|female|
| 31| 191| George| male|
+---+------+-------+------+
| Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
分组和聚合 类似sql中的`select aggregation Group by grouping`语句功能,pandas和spark都定义了一些聚合函数,如:- count- sum- avg- corr- first- last可以具体查看[PySpark Function Documentation](http://spark.apache.org/docs/latest/api/python/pyspark.sql.htmlmodule-pyspark.sql.functions) | result = person_pd.groupby('sex').agg({'age': 'mean', 'height':['min', 'max']})
result
from pyspark.sql.functions import avg, min, max
result = person_sp.groupBy(person_sp.sex).agg(min(person_sp.height).alias('min height'), max(person_sp.height).alias('max height'),
avg(pers... | +---+------+-------+------+
|age|height| name| sex|
+---+------+-------+------+
| 23| 156| Alice|female|
| 21| 181| Bob| male|
| 27| 176|Charlie| male|
| 24| 167| Eve|female|
| 19| 172|Frances|female|
| 31| 191| George| male|
+---+------+-------+------+
| Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
join spark也支持跨dataframe做join, 让我们加个数据作例子。 | addresses = spark.read.json('data/addresses.json')
addresses_pd = addresses.toPandas()
addresses_pd
pd_join = person_pd.merge(addresses_pd, left_on=['name'], right_on=['name'])
pd_join
sp_join = person_sp.join(addresses, person_sp.name==addresses.name)
sp_join.show()
sp_join_1 = person_sp.join(addresses, on=['name'])
s... | +---+------+-----+------+---------+-----+
|age|height| name| sex| city| name|
+---+------+-----+------+---------+-----+
| 23| 156|Alice|female| Hamburg|Alice|
| 21| 181| Bob| male|Frankfurt| Bob|
+---+------+-----+------+---------+-----+
+-----+---+------+------+---------+
| name|age|height| sex| c... | Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
重装dataframe pandas可以很方便地将现有的一列数据赋给一个新的列, 但是spark做起来不是很方便,需要join操作。 | df = person_pd[['name', 'age']]
col = person_pd['height']
result = df.copy()
result['h2'] = col
result
df = person_sp[['name', 'age']]
col = person_sp[['name', 'height']]
result = df.join(col, on=['name'])
result.show() | +-------+---+------+
| name|age|height|
+-------+---+------+
| Alice| 23| 156|
| Bob| 21| 181|
|Charlie| 27| 176|
| Eve| 24| 167|
|Frances| 19| 172|
| George| 31| 191|
+-------+---+------+
| Apache-2.0 | Pandas to Spark.ipynb | nancunpei/spark-examples |
Distant Viewing with Deep Learning: Part 2In Part 2 of this tutorial, we introduce the concepts of deep learning and show it yieldsinteresting similarity metrics and is able to extract feature useful features such as thepresence and location of faces in the image. Step 9: Python modules for deep learningWe need to re... | %pylab inline
# !pip3 install keras # this wasn't working so had to do change from here
# ------------------
import getpass
import os
password = getpass.getpass()
command = "sudo -S sudo pip3 install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl" #can be any command but don't f... | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
We also need to reload the wikiart metadata. | wikiart = pd.read_csv("meta/wikiart.csv") | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
To run the code in this notebook from scratch, you will also need the **keras**module for working with neural networks. This are not included in the defaultAnaconda Python installation and need to be installed seperately. The codebelow checks if you have keras installed. If you do, it will be loaded. Otherwise,a flag w... | import keras
if importlib.util.find_spec("keras") is not None:
from keras.applications.vgg19 import VGG19
from keras.preprocessing import image
from keras.applications.vgg19 import preprocess_input, decode_predictions
from keras.models import Model
keras_flag = True
else:
keras_flag = False | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
If you are struggling with installing these, we are happy to assist. You'll be able to followalong without keras, but will not be able to apply the techniques you learned today to new datasetswithout it. Step 10: Applying deep learning with neural networks We start by loading a particular neural network model called V... | if keras_flag:
vgg19_full = VGG19(weights='imagenet')
vgg19_full.summary()
else:
with open('data/vgg19.txt','r') as f:
for line in f:
print(line, end='') | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
The VGG19 model was trained to identify 1000 classes of objects within animage. It was built as part of the ImageNet challenge, one of the mostinfluential computer vision competitions that has been running since 2010.We will load a test photo of my dog and see what classes the model predictsfor the image. We will use a... | img_path = join("images", "test", "dog.jpg")
if keras_flag:
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
else:
img = imread(img_path)
x = img.copy().astype(np.float32)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
x.shape | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
Notice that it is now a four dimensional array, a point that we will come back to ina moment. We can look at the image here using the `imshow` function. | plt.imshow(img) | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
Assuming you have keras installed, the code here takes the image `x` and predictsvalues from the model. Notice that the output of the model is a sequence of 1000numbers. These indicate the predicted probability that the image contains each of one of the 1000 pre-selected categories. The function `decode_predictions` co... | if keras_flag:
y = vgg19_full.predict(x)
print(y.shape)
for pred in decode_predictions(y)[0]:
print(pred)
else:
print((1, 1000))
y = np.load(join('data', 'dog_pred.npy'))
for pred in decode_predictions(y)[0]:
print(pred) | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
The largest predicted class is a "Shih-Tzu", incidently an exact match for hisbreed! The other dogs are all similarly sized dogs, and obvious choices for making a mistake. Now, let's compute the category predictions for each image in the corpus. This involvesreading in each image in the wikiart corpus and then running ... | process_new = False
if process_new:
wikiart_img = np.zeros((wikiart.shape[0], 224, 224, 3))
for index, row in wikiart.iterrows():
img_path = join('images', 'wikiart', row['filename'])
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
wikiart_img... | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
What's the most common top category type for this collection? When can use thePython module `collections` to look at the top-10 most common: | collections.Counter(wikiart_vgg19[:, 1, 1]).most_common(10) | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
Cliffs and fountains both seem reasonable, but I doubt there are many jigsaw puzzels in the wikiart corpus. **Any idea by this might be so common?** Step 11: Neural network embeddingThe VGG19 model was constructed in order to predict the objects present in an image,but there is a lot more that we can do with the model... | if keras_flag:
vgg_fc2 = Model(inputs=vgg19_full.input, outputs=vgg19_full.get_layer('fc2').output)
y = vgg_fc2.predict(x)
print(y.shape)
else:
print((1, 4096)) | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
We can use this new model to predict values on the set of images `wikiart_img`. As above,this can take a few minutes, so you may want to load the pre-saved data again by keeping`process_new` equal to `False`. | process_new = False
if process_new:
wikiart_fc2 = vgg_fc2.predict(wikiart_img, verbose=True)
wikiart_fc2.shape
else:
wikiart_fc2 = np.load("data/wikiart_vgg19_fc2.npy")
print(wikiart_fc2.shape) | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
Now, we can use these values to figure out which images are similar to another image.This is similar to the closest saturation values, but using a more complex numericmetric for comparison. Compare the results here with those from saturation alone: | plt.figure(figsize=(14, 14))
dists = np.sum(np.abs(wikiart_fc2 - wikiart_fc2[1, :]), 1)
idx = np.argsort(dists.flatten())[:12]
for ind, i in enumerate(idx):
try:
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
plt.subplot(3, 4, ind + 1)
img_path = join('images', 'wikiart', wikiart.i... | _____no_output_____ | MIT | dl-tutorial/distant-viewing-tutorial-part-2.ipynb | JoshuaGOB/NLTK |
New Dale-Chall list improvement Step 1: Lower case, no duplicates | from nltk.stem import PorterStemmer
with open('promovolt/resources/new_dale-chall_simple_words_en-1.0.txt', 'r') as f:
words = f.read().splitlines()
for i, word in enumerate(words):
words[i] = word.lower().strip()
words = list(set(words))
words.sort()
len(words) | _____no_output_____ | Unlicense | jupyter_notebooks/0016_new_dale-chall_list_improvement.ipynb | korniichuk/phd |
Save to file | with open('promovolt/resources/new_dale-chall_simple_words_en-1.1.txt', 'w') as f:
for i, word in enumerate(words):
if i < (len(words) - 1):
f.write(word + '\n')
else:
f.write(word) | _____no_output_____ | Unlicense | jupyter_notebooks/0016_new_dale-chall_list_improvement.ipynb | korniichuk/phd |
Step 2: Stemming | with open('promovolt/resources/new_dale-chall_simple_words_en-1.1.txt', 'r') as f:
words = f.read().splitlines()
stemmer = PorterStemmer()
for i, word in enumerate(words):
words[i] = stemmer.stem(word)
words = list(set(words))
words.sort()
len(words) | _____no_output_____ | Unlicense | jupyter_notebooks/0016_new_dale-chall_list_improvement.ipynb | korniichuk/phd |
Save to file | with open('promovolt/resources/new_dale-chall_simple_words_en_stemmed.txt', 'w') as f:
for i, word in enumerate(words):
if i < (len(words) - 1):
f.write(word + '\n')
else:
f.write(word) | _____no_output_____ | Unlicense | jupyter_notebooks/0016_new_dale-chall_list_improvement.ipynb | korniichuk/phd |
Putting the "Re" in Reformer: Ungraded LabThis ungraded lab will explore Reversible Residual Networks. You will use these networks in this week's assignment that utilizes the Reformer model. It is based on on the Transformer model you already know, but with two unique features.* Locality Sensitive Hashing (LSH) Attent... | import trax
from trax import layers as tl # core building block
import numpy as np # regular ol' numpy
from trax.models.reformer.reformer import (
ReversibleHalfResidualV2 as ReversibleHalfResidual,
) # unique spot
from trax import fas... | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Part 1.0 Residual Networks[Deep Residual Networks ](https://arxiv.org/abs/1512.03385) (Resnets) were introduced to improve convergence in deep networks. Residual Networks introduce a shortcut connection around one or more layers in a deep network as shown in the diagram below from the original paper.Figure 1: Residua... | # simple function taking one input and one output
bl_add1 = tl.Fn("add1", lambda x0: (x0 + 1), n_out=1)
bl_add2 = tl.Fn("add2", lambda x0: (x0 + 2), n_out=1)
bl_add3 = tl.Fn("add3", lambda x0: (x0 + 3), n_out=1)
# try them out
x = np.array([1])
print(bl_add1(x), bl_add2(x), bl_add3(x))
# some information about our new ... | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Trax uses the concept of a 'stack' to transfer data between layers.For Branch, for each of its layer arguments, it copies the `n_in` inputs from the stack and provides them to the layer, tracking the max_n_in, or the largest n_in required. It then pops the max_n_in elements from the stack.Figure 3: One in, one out Bran... | # n_in = 1, Each bl_addx pushes n_out = 1 elements onto the stack
bl_3add1s(x)
# n = np.array([10]); m = np.array([20]) # n, m will remain on the stack
n = "n"
m = "m" # n, m will remain on the stack
bl_3add1s([x, n, m]) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Each layer in the input list copies as many inputs from the stack as it needs, and their outputs are successively combined on stack. Put another way, each element of the branch can have differing numbers of inputs and outputs. Let's try a more complex example. | bl_addab = tl.Fn(
"addab", lambda x0, x1: (x0 + x1), n_out=1
) # Trax figures out how many inputs there are
bl_rep3x = tl.Fn(
"add2x", lambda x0: (x0, x0, x0), n_out=3
) # but you have to tell it how many outputs there are
bl_3ops = tl.Branch(bl_add1, bl_addab, bl_rep3x) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
In this case, the number if inputs being copied from the stack varies with the layerFigure 4: variable in, variable out BranchThe stack when the operation is finished is 5 entries reflecting the total from each layer. | # Before Running this cell, what is the output you are expecting?
y = np.array([3])
bl_3ops([x, y, n, m]) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Branch has a special feature to support Residual Network. If an argument is 'None', it will pull the top of stack and push it (at its location in the sequence) onto the output stackFigure 5: Branch for Residual | bl_2ops = tl.Branch(bl_add1, None)
bl_2ops([x, n, m]) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Part 1.2 Residual ModelOK, your turn. Write a function 'MyResidual', that uses `tl.Branch` and `tl.Add` to build a residual layer. If you are curious about the Trax implementation, you can see the code [here](https://github.com/google/trax/blob/190ec6c3d941d8a9f30422f27ef0c95dc16d2ab1/trax/layers/combinators.py). | def MyResidual(layer):
return tl.Serial(
### START CODE HERE ###
# tl.----,
# tl.----,
### END CODE HERE ###
)
# Lets Try it
mr = MyResidual(bl_add1)
x = np.array([1])
mr([x, n, m]) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
**Expected Result**(array([3]), 'n', 'm') Great! Now, let's build the 4 layer residual Network in Figure 2. You can use `MyResidual`, or if you prefer, the tl.Residual in Trax, or a combination! | Fl = tl.Fn("F", lambda x0: (2 * x0), n_out=1)
Gl = tl.Fn("G", lambda x0: (10 * x0), n_out=1)
x1 = np.array([1])
resfg = tl.Serial(
### START CODE HERE ###
# None, #Fl # x + F(x)
# None, #Gl # x + F(x) + G(x + F(x)) etc
# None, #Fl
# None, #Gl
### END CODE HERE ###
)
# Lets try it
resfg... | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
**Expected Results**(array([1089]), 'n', 'm') Part 2.0 Reversible Residual NetworksThe Reformer utilized RevNets to reduce the storage requirements for performing backpropagation.Figure 6: Reversible Residual Networks The standard approach on the left above requires one to store the outputs of each stage for use durin... | refm = trax.models.reformer.ReformerLM(
vocab_size=33000, n_layers=2, mode="train" # Add more options.
)
refm | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Eliminating some of the detail, we can see the structure of the network.Figure 8: Key Structure of Reformer Reversible Network Layers in Trax We'll review the Trax layers used to implement the Reversible section of the Reformer. First we can note that not all of the reformer is reversible. Only the section in the Rever... | x1 = np.array([1])
x2 = np.array([5])
# Dup() duplicates the Top of Stack and returns the stack
dl = tl.Dup()
dl(x1)
# ReversibleSwap() duplicates the Top of Stack and returns the stack
sl = tl.ReversibleSwap()
sl([x1, x2]) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
You are no doubt wondering "How is ReversibleSwap different from Swap?". Good question! Lets look:Figure 11: Two versions of Swap() The ReverseXYZ functions include a "reverse" compliment to their "forward" function that provides the functionality to run in reverse when doing backpropagation. It can also be run in reve... | # Demonstrate reverse swap
print(x1, x2, sl.reverse([x1, x2])) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Let's try ReversibleHalfResidual, First we'll need some layers.. | Fl = tl.Fn("F", lambda x0: (2 * x0), n_out=1)
Gl = tl.Fn("G", lambda x0: (10 * x0), n_out=1) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Just a note about ReversibleHalfResidual. As this is written, it resides in the Reformer model and is a layer. It is invoked a bit differently that other layers. Rather than tl.XYZ, it is just ReversibleHalfResidual(layers..) as shown below. This may change in the future. | half_res_F = ReversibleHalfResidual(Fl)
print(type(half_res_F), "\n", half_res_F)
half_res_F([x1, x1]) # this is going to produce an error - why?
# we have to initialize the ReversibleHalfResidual layer to let it know what the input is going to look like
half_res_F.init(shapes.signature([x1, x1]))
half_res_F([x1, x1]) | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
Notice the output: (DeviceArray([3], dtype=int32), array([1])). The first value, (DeviceArray([3], dtype=int32) is the output of the "Fl" layer and has been converted to a 'Jax' DeviceArray. The second array([1]) is just passed through (recall the diagram of ReversibleHalfResidual above). The final layer we need is the... | blk = [ # a list of the 4 layers shown above
### START CODE HERE ###
None,
None,
None,
None,
]
blks = [None, None]
### END CODE HERE ###
mod = tl.Serial(
### START CODE HERE ###
None,
None,
None,
### END CODE HERE ###
)
mod | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
**Expected Output**```Serial[ Dup_out2 ReversibleSerial_in2_out2[ ReversibleHalfResidualV2_in2_out2[ Serial[ F ] ] ReversibleSwap_in2_out2 ReversibleHalfResidualV2_in2_out2[ Serial[ G ] ] ReversibleSwap_in2_out2 ReversibleHalfResidualV2_in2_out2[ Serial[ ... | mod.init(shapes.signature(x1))
out = mod(x1)
out | _____no_output_____ | MIT | Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Ungraded_Lab_Revnet.ipynb | y33-j3T/Coursera |
MICROSOFT STOCK PRICE TIME SERIES ANALYSIS Within this Jupyter Notebook, we will attempt to forecast and model the future price of Microsoft stock through Time Series Analysis and SARIMAX models, while also modelling out potential trades and profits that could be made based on our forecast through training and test se... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import timedelta
import statsmodels.api as sm
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.stattools import acf
from statsmodels.tsa.stattools import pacf
... | _____no_output_____ | MIT | MSFT Time Series Analysis.ipynb | maxrzhang/Microsoft-Stock-Time-Series-Analysis |
Reading in the Stock Price Data and Preprocessing the Data | MSFT = pd.read_csv('MSFT.csv')
MSFT.head()
MSFT.Date = pd.to_datetime(MSFT.Date)
MSFT = MSFT.sort_values('Date')
MSFT.Date = MSFT.Date + timedelta(hours = 16)
stock = MSFT[['Date', 'Close']].copy()
stock.columns = ['Date', 'Price']
MSFT.Date = MSFT.Date - timedelta(hours = 6.5)
MSFT.head()
stock.head()
MSFT.columns = [... | _____no_output_____ | MIT | MSFT Time Series Analysis.ipynb | maxrzhang/Microsoft-Stock-Time-Series-Analysis |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.