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
|
---|---|---|---|---|---|
--- Padding sequencesTo deal with both short and very long reviews, we'll pad or truncate all our reviews to a specific length. For reviews shorter than some `seq_length`, we'll pad with 0s. For reviews longer than `seq_length`, we can truncate them to the first `seq_length` words. A good `seq_length`, in this case, is 200.> **Exercise:** Define a function that returns an array `features` that contains the padded data, of a standard size, that we'll pass to the network. * The data should come from `review_ints`, since we want to feed integers to the network. * Each row should be `seq_length` elements long. * For reviews shorter than `seq_length` words, **left pad** with 0s. That is, if the review is `['best', 'movie', 'ever']`, `[117, 18, 128]` as integers, the row will look like `[0, 0, 0, ..., 0, 117, 18, 128]`. * For reviews longer than `seq_length`, use only the first `seq_length` words as the feature vector.As a small example, if the `seq_length=10` and an input review is: ```[117, 18, 128]```The resultant, padded sequence should be: ```[0, 0, 0, 0, 0, 0, 0, 117, 18, 128]```**Your final `features` array should be a 2D array, with as many rows as there are reviews, and as many columns as the specified `seq_length`.**This isn't trivial and there are a bunch of ways to do this. But, if you're going to be building your own deep learning networks, you're going to have to get used to preparing your data. | def pad_features(reviews_ints, seq_length):
''' Return features of review_ints, where each review is padded with 0's
or truncated to the input seq_length.
'''
## implement function
features=None
return features
# Test your implementation!
seq_length = 200
features = pad_features(reviews_ints, seq_length=seq_length)
## test statements - do not change - ##
assert len(features)==len(reviews_ints), "Your features should have as many rows as reviews."
assert len(features[0])==seq_length, "Each feature row should contain seq_length values."
# print first 10 values of the first 30 batches
print(features[:30,:10]) | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
Training, Validation, TestWith our data in nice shape, we'll split it into training, validation, and test sets.> **Exercise:** Create the training, validation, and test sets. * You'll need to create sets for the features and the labels, `train_x` and `train_y`, for example. * Define a split fraction, `split_frac` as the fraction of data to **keep** in the training set. Usually this is set to 0.8 or 0.9. * Whatever data is left will be split in half to create the validation and *testing* data. | split_frac = 0.8
## split data into training, validation, and test data (features and labels, x and y)
## print out the shapes of your resultant feature data
| _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
**Check your work**With train, validation, and test fractions equal to 0.8, 0.1, 0.1, respectively, the final, feature data shapes should look like:``` Feature Shapes:Train set: (20000, 200) Validation set: (2500, 200) Test set: (2500, 200)``` --- DataLoaders and BatchingAfter creating training, test, and validation data, we can create DataLoaders for this data by following two steps:1. Create a known format for accessing our data, using [TensorDataset](https://pytorch.org/docs/stable/data.html) which takes in an input set of data and a target set of data with the same first dimension, and creates a dataset.2. Create DataLoaders and batch our training, validation, and test Tensor datasets.```train_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))train_loader = DataLoader(train_data, batch_size=batch_size)```This is an alternative to creating a generator function for batching our data into full batches. | import torch
from torch.utils.data import TensorDataset, DataLoader
# create Tensor datasets
train_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))
valid_data = TensorDataset(torch.from_numpy(val_x), torch.from_numpy(val_y))
test_data = TensorDataset(torch.from_numpy(test_x), torch.from_numpy(test_y))
# dataloaders
batch_size = 50
# make sure to SHUFFLE your data
train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)
valid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size)
test_loader = DataLoader(test_data, shuffle=True, batch_size=batch_size)
# obtain one batch of training data
dataiter = iter(train_loader)
sample_x, sample_y = dataiter.next()
print('Sample input size: ', sample_x.size()) # batch_size, seq_length
print('Sample input: \n', sample_x)
print()
print('Sample label size: ', sample_y.size()) # batch_size
print('Sample label: \n', sample_y) | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
--- Sentiment Network with PyTorchBelow is where you'll define the network.The layers are as follows:1. An [embedding layer](https://pytorch.org/docs/stable/nn.htmlembedding) that converts our word tokens (integers) into embeddings of a specific size.2. An [LSTM layer](https://pytorch.org/docs/stable/nn.htmllstm) defined by a hidden_state size and number of layers3. A fully-connected output layer that maps the LSTM layer outputs to a desired output_size4. A sigmoid activation layer which turns all outputs into a value 0-1; return **only the last sigmoid output** as the output of this network. The Embedding LayerWe need to add an [embedding layer](https://pytorch.org/docs/stable/nn.htmlembedding) because there are 74000+ words in our vocabulary. It is massively inefficient to one-hot encode that many classes. So, instead of one-hot encoding, we can have an embedding layer and use that layer as a lookup table. You could train an embedding layer using Word2Vec, then load it here. But, it's fine to just make a new layer, using it for only dimensionality reduction, and let the network learn the weights. The LSTM Layer(s)We'll create an [LSTM](https://pytorch.org/docs/stable/nn.htmllstm) to use in our recurrent network, which takes in an input_size, a hidden_dim, a number of layers, a dropout probability (for dropout between multiple layers), and a batch_first parameter.Most of the time, you're network will have better performance with more layers; between 2-3. Adding more layers allows the network to learn really complex relationships. > **Exercise:** Complete the `__init__`, `forward`, and `init_hidden` functions for the SentimentRNN model class.Note: `init_hidden` should initialize the hidden and cell state of an lstm layer to all zeros, and move those state to GPU, if available. | # First checking if GPU is available
train_on_gpu=torch.cuda.is_available()
if(train_on_gpu):
print('Training on GPU.')
else:
print('No GPU available, training on CPU.')
import torch.nn as nn
class SentimentRNN(nn.Module):
"""
The RNN model that will be used to perform Sentiment analysis.
"""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""
Initialize the model by setting up the layers.
"""
super(SentimentRNN, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
# define all layers
def forward(self, x, hidden):
"""
Perform a forward pass of our model on some input and hidden state.
"""
# return last sigmoid output and hidden state
return sig_out, hidden
def init_hidden(self, batch_size):
''' Initializes hidden state '''
# Create two new tensors with sizes n_layers x batch_size x hidden_dim,
# initialized to zero, for hidden state and cell state of LSTM
return hidden
| _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
Instantiate the networkHere, we'll instantiate the network. First up, defining the hyperparameters.* `vocab_size`: Size of our vocabulary or the range of values for our input, word tokens.* `output_size`: Size of our desired output; the number of class scores we want to output (pos/neg).* `embedding_dim`: Number of columns in the embedding lookup table; size of our embeddings.* `hidden_dim`: Number of units in the hidden layers of our LSTM cells. Usually larger is better performance wise. Common values are 128, 256, 512, etc.* `n_layers`: Number of LSTM layers in the network. Typically between 1-3> **Exercise:** Define the model hyperparameters. | # Instantiate the model w/ hyperparams
vocab_size =
output_size =
embedding_dim =
hidden_dim =
n_layers =
net = SentimentRNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers)
print(net) | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
--- TrainingBelow is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. You can also add code to save a model by name.>We'll also be using a new kind of cross entropy loss, which is designed to work with a single Sigmoid output. [BCELoss](https://pytorch.org/docs/stable/nn.htmlbceloss), or **Binary Cross Entropy Loss**, applies cross entropy loss to a single value between 0 and 1.We also have some data and training hyparameters:* `lr`: Learning rate for our optimizer.* `epochs`: Number of times to iterate through the training dataset.* `clip`: The maximum gradient value to clip at (to prevent exploding gradients). | # loss and optimization functions
lr=0.001
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
# training params
epochs = 4 # 3-4 is approx where I noticed the validation loss stop decreasing
counter = 0
print_every = 100
clip=5 # gradient clipping
# move model to GPU, if available
if(train_on_gpu):
net.cuda()
net.train()
# train for some number of epochs
for e in range(epochs):
# initialize hidden state
h = net.init_hidden(batch_size)
# batch loop
for inputs, labels in train_loader:
counter += 1
if(train_on_gpu):
inputs, labels = inputs.cuda(), labels.cuda()
# Creating new variables for the hidden state, otherwise
# we'd backprop through the entire training history
h = tuple([each.data for each in h])
# zero accumulated gradients
net.zero_grad()
# get the output from the model
output, h = net(inputs, h)
# calculate the loss and perform backprop
loss = criterion(output.squeeze(), labels.float())
loss.backward()
# `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.
nn.utils.clip_grad_norm_(net.parameters(), clip)
optimizer.step()
# loss stats
if counter % print_every == 0:
# Get validation loss
val_h = net.init_hidden(batch_size)
val_losses = []
net.eval()
for inputs, labels in valid_loader:
# Creating new variables for the hidden state, otherwise
# we'd backprop through the entire training history
val_h = tuple([each.data for each in val_h])
if(train_on_gpu):
inputs, labels = inputs.cuda(), labels.cuda()
output, val_h = net(inputs, val_h)
val_loss = criterion(output.squeeze(), labels.float())
val_losses.append(val_loss.item())
net.train()
print("Epoch: {}/{}...".format(e+1, epochs),
"Step: {}...".format(counter),
"Loss: {:.6f}...".format(loss.item()),
"Val Loss: {:.6f}".format(np.mean(val_losses))) | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
--- TestingThere are a few ways to test your network.* **Test data performance:** First, we'll see how our trained model performs on all of our defined test_data, above. We'll calculate the average loss and accuracy over the test data.* **Inference on user-generated data:** Second, we'll see if we can input just one example review at a time (without a label), and see what the trained model predicts. Looking at new, user input data like this, and predicting an output label, is called **inference**. | # Get test data loss and accuracy
test_losses = [] # track loss
num_correct = 0
# init hidden state
h = net.init_hidden(batch_size)
net.eval()
# iterate over test data
for inputs, labels in test_loader:
# Creating new variables for the hidden state, otherwise
# we'd backprop through the entire training history
h = tuple([each.data for each in h])
if(train_on_gpu):
inputs, labels = inputs.cuda(), labels.cuda()
# get predicted outputs
output, h = net(inputs, h)
# calculate loss
test_loss = criterion(output.squeeze(), labels.float())
test_losses.append(test_loss.item())
# convert output probabilities to predicted class (0 or 1)
pred = torch.round(output.squeeze()) # rounds to the nearest integer
# compare predictions to true label
correct_tensor = pred.eq(labels.float().view_as(pred))
correct = np.squeeze(correct_tensor.numpy()) if not train_on_gpu else np.squeeze(correct_tensor.cpu().numpy())
num_correct += np.sum(correct)
# -- stats! -- ##
# avg test loss
print("Test loss: {:.3f}".format(np.mean(test_losses)))
# accuracy over all test data
test_acc = num_correct/len(test_loader.dataset)
print("Test accuracy: {:.3f}".format(test_acc)) | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
Inference on a test reviewYou can change this test_review to any text that you want. Read it and think: is it pos or neg? Then see if your model predicts correctly! > **Exercise:** Write a `predict` function that takes in a trained net, a plain text_review, and a sequence length, and prints out a custom statement for a positive or negative review!* You can use any functions that you've already defined or define any helper functions you want to complete `predict`, but it should just take in a trained net, a text review, and a sequence length. | # negative test review
test_review_neg = 'The worst movie I have seen; acting was terrible and I want my money back. This movie had bad acting and the dialogue was slow.'
def predict(net, test_review, sequence_length=200):
''' Prints out whether a give review is predicted to be
positive or negative in sentiment, using a trained model.
params:
net - A trained net
test_review - a review made of normal text and punctuation
sequence_length - the padded length of a review
'''
# print custom response based on whether test_review is pos/neg
# positive test review
test_review_pos = 'This movie had the best acting and the dialogue was so good. I loved it.'
# call function
# try negative and positive reviews!
seq_length=200
predict(net, test_review_neg, seq_length) | _____no_output_____ | MIT | sentiment-rnn/Sentiment_RNN_Exercise.ipynb | MiniMarvin/pytorch-v2 |
Scene Classification-Test_a 1. Preprocess-KerasFolderClasses- Import pkg- Extract zip file- Preview "scene_classes.csv"- Preview "scene_{0}_annotations_20170922.json"- Test the image and pickle function- Split data into serval pickle file This part need jupyter notebook start with "jupyter notebook --NotebookApp.iopub_data_rate_limit=1000000000" (https://github.com/jupyter/notebook/issues/2287)Reference:- https://challenger.ai/competitions- https://github.com/jupyter/notebook/issues/2287 Import pkg | import numpy as np
import pandas as pd
# import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from keras.utils.np_utils import to_categorical # convert to one-hot-encoding
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import LearningRateScheduler, TensorBoard
# import zipfile
import os
import zipfile
import math
from time import time
from IPython.display import display
import pdb
import json
from PIL import Image
import glob
import pickle | _____no_output_____ | MIT | SceneClassification2017/1. Preprocess-KerasFolderClasses-Test_a.ipynb | StudyExchange/AIChallenger |
Extract zip file | input_path = 'input'
datasetName = 'test_a'
date = '20170922'
datasetFolder = input_path + '\\data_{0}'.format(datasetName)
zip_path = input_path + '\\ai_challenger_scene_{0}_{1}.zip'.format(datasetName, date)
extract_path = input_path + '\\ai_challenger_scene_{0}_{1}'.format(datasetName, date)
image_path = extract_path + '\\scene_{0}_images_{1}'.format(datasetName, date)
scene_classes_path = extract_path + '\\scene_classes.csv'
scene_annotations_path = extract_path + '\\scene_{0}_annotations_{1}.json'.format(datasetName, date)
print(input_path)
print(datasetFolder)
print(zip_path)
print(extract_path)
print(image_path)
print(scene_classes_path)
print(scene_annotations_path)
if not os.path.isdir(extract_path):
with zipfile.ZipFile(zip_path) as file:
for name in file.namelist():
file.extract(name, input_path) | _____no_output_____ | MIT | SceneClassification2017/1. Preprocess-KerasFolderClasses-Test_a.ipynb | StudyExchange/AIChallenger |
Preview "scene_classes.csv" | scene_classes = pd.read_csv(scene_classes_path, header=None)
display(scene_classes.head())
def get_scene_name(lable_number, scene_classes_path):
scene_classes = pd.read_csv(scene_classes_path, header=None)
return scene_classes.loc[lable_number, 2]
print(get_scene_name(0, scene_classes_path)) | airport_terminal
| MIT | SceneClassification2017/1. Preprocess-KerasFolderClasses-Test_a.ipynb | StudyExchange/AIChallenger |
Copy images to ./input/data_test_a/test | from shutil import copy2
cwd = os.getcwd()
test_folder = os.path.join(cwd, datasetFolder)
test_sub_folder = os.path.join(test_folder, 'test')
if not os.path.isdir(test_folder):
os.mkdir(test_folder)
os.mkdir(test_sub_folder)
print(test_folder)
print(test_sub_folder)
trainDir = test_sub_folder
for image_id in os.listdir(os.path.join(cwd, image_path)):
fileName = image_path + '/' + image_id
# print(fileName)
# print(trainDir)
copy2(fileName, trainDir)
print('Done!') | Done!
| MIT | SceneClassification2017/1. Preprocess-KerasFolderClasses-Test_a.ipynb | StudyExchange/AIChallenger |
01 A logged editable table> Traceable editable table in flask | from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!' | _____no_output_____ | MIT | nbs/30_traceable_edit_in_flask.ipynb | raynardj/forgebox |
Run a simple applitcation | # default_exp editable
# export
import pandas as pd
from datetime import datetime
import json
from sqlalchemy import create_engine as ce
from sqlalchemy import text
from jinja2 import Template
# export
from pathlib import Path
def get_static():
import forgebox
return Path(forgebox.__path__[0])/"static"
# export
def edit_js():
with open(get_static()/"edit.js","r") as f:
return f"<script>{f.read()}</script>"
class DefaultTemp(Template):
"""
Jinjia template with some default render config
"""
def render(self,dt):
dt.update(dict(type=type,now = datetime.now()))
return super().render(dt) | _____no_output_____ | MIT | nbs/30_traceable_edit_in_flask.ipynb | raynardj/forgebox |
Create sample data | con = ce("sqlite:///sample.db")
sample_df = pd.DataFrame(dict(name=["Darrow","Virginia","Sevro",]*20,
house =["Andromedus","Augustus","Barca"]*20,
age=[20,18,17]*20))
sample_df.to_sql("sample_table",index_label="id",
index=True,
con = con, method='multi',
if_exists="replace")
# export
from flask import request
from flask import g
from datetime import datetime
class Editable:
def __init__(self,name,app,table_name,con,id_col,
log_con,log_table="editable_log",columns = None):
"""
name: route name for url path,
also it will be the task title appearning on the frontend
app:flask app
table_name: table to edit
con:sqlachemy connnection, created by : con = sqlalchemy.create_engine
id_col: a column with unique value
log_con:sqlachemy connnection, for storaging change log
"""
self.name = name
self.app = app
self.table_name = table_name
self.con = con
self.log_con = log_con
self.columns = ",".join(columns) if columns!=None else "*"
self.id_col = id_col
self.t_workspace = self.load_temp(get_static()/"workspace.html")
self.t_table = self.load_temp(get_static()/"table.html")
self.assign()
def assign(self):
self.app.route(f"/{self.name}")(self.workspace)
self.app.route(f"/{self.name}/df_api")(self.read_df)
self.app.route(f"/{self.name}/save_api",
methods=["POST"])(self.save_data)
def workspace(self):
return self.t_workspace.render(dict(title=self.name,
pk=self.id_col,
edit_js = edit_js()))
def save_data(self):
data = json.loads(request.data)
# update change and save log
changes = data["changes"]
log_df = pd.DataFrame(list(self.single_row(change) for change in changes))
log_df["idx"] = log_df.idx.apply(str)
log_df["original"] = log_df.original.apply(str)
log_df["changed"] = log_df.changed.apply(str)
log_df.to_sql(f"editable_log",con = self.log_con,index=False, if_exists="append")
print(log_df)
# return updated table
query = data["query"]
page = query["page"]
where = query["where"]
return self.data_table(page,where)
def settype(self,k):
if k[:3] == "int": return int
elif "float" in k: return float
elif k=="str":return str
elif k=="list":return list
elif k=="dict":return dict
else: return eval(k)
def single_row(self,row):
row["ip"]= request.remote_addr
row["table_name"] = self.table_name
row["ts"] = datetime.now()
if row["original"]==row["changed"]:
row['sql'] = ""
return row
else:
col = row["col"]
val = row["changed"]
val = f"'{val}'" if 'str' in row["valtype"] else val
idx = row["idx"]
idx = f"'{idx}'" if type(idx)==str else idx
set_clause = f"SET {col}={val}"
sql = f"""UPDATE {self.table_name}
{set_clause} WHERE {self.id_col}={idx}
"""
row['sql'] = sql
self.con.execute(sql)
return row
def read_df(self):
page = request.args.get('page')
where = request.args.get('where')
return self.data_table(page,where)
def data_table(self,page,where):
where_clause = "" if where.strip() == "" else f"WHERE {where} "
sql = f"""SELECT {self.columns} FROM {self.table_name} {where_clause}
ORDER BY {self.id_col} ASC LIMIT {page},20
"""
print(sql)
df = pd.read_sql(sql,self.con)
df = df.set_index(self.id_col)
return self.t_table.render(dict(df = df))
def load_temp(self,path):
with open(path, "r") as f:
return DefaultTemp(f.read()) | _____no_output_____ | MIT | nbs/30_traceable_edit_in_flask.ipynb | raynardj/forgebox |
Testing editable frontend | app = Flask(__name__)
# Create Editable pages around sample_table
Editable("table1", # route/task name
app, # flask app to wrap around
table_name="sample_table", # target table name
id_col="id", # unique column
con = con,
log_con=con
)
app.run(host="0.0.0.0",port = 4242,debug=False) | _____no_output_____ | MIT | nbs/30_traceable_edit_in_flask.ipynb | raynardj/forgebox |
Retrieve the log | from forgebox.df import PandasDisplay
with PandasDisplay(max_colwidth = 0,max_rows=100):
display(pd.read_sql('editable_log',con = con)) | _____no_output_____ | MIT | nbs/30_traceable_edit_in_flask.ipynb | raynardj/forgebox |
Creating a Sentiment Analysis Web App Using PyTorch and SageMaker_Deep Learning Nanodegree Program | Deployment_---Now that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to enter a movie review. The web page will then send the review off to our deployed model which will predict the sentiment of the entered review. InstructionsSome template code has already been provided for you, and you will need to implement additional functionality to successfully complete this notebook. You will not need to modify the included code beyond what is requested. Sections that begin with '**TODO**' in the header indicate that you need to complete or implement some portion within them. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a ` TODO: ...` comment. Please be sure to read the instructions carefully!In addition to implementing code, there will be questions for you to answer which relate to the task and your implementation. Each section where you will answer a question is preceded by a '**Question:**' header. Carefully read each question and provide your answer below the '**Answer:**' header by editing the Markdown cell.> **Note**: Code and Markdown cells can be executed using the **Shift+Enter** keyboard shortcut. In addition, a cell can be edited by typically clicking it (double-click for Markdown cells) or by pressing **Enter** while it is highlighted. General OutlineRecall the general outline for SageMaker projects using a notebook instance.1. Download or otherwise retrieve the data.2. Process / Prepare the data.3. Upload the processed data to S3.4. Train a chosen model.5. Test the trained model (typically using a batch transform job).6. Deploy the trained model.7. Use the deployed model.For this project, you will be following the steps in the general outline with some modifications. First, you will not be testing the model in its own step. You will still be testing the model, however, you will do it by deploying your model and then using the deployed model by sending the test data to it. One of the reasons for doing this is so that you can make sure that your deployed model is working correctly before moving forward.In addition, you will deploy and use your trained model a second time. In the second iteration you will customize the way that your trained model is deployed by including some of your own code. In addition, your newly deployed model will be used in the sentiment analysis web app. Step 1: Downloading the dataAs in the XGBoost in SageMaker notebook, we will be using the [IMDb dataset](http://ai.stanford.edu/~amaas/data/sentiment/)> Maas, Andrew L., et al. [Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/data/sentiment/). In _Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies_. Association for Computational Linguistics, 2011. | %mkdir ../data
!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data | mkdir: cannot create directory β../dataβ: File exists
--2019-12-22 07:15:17-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
Resolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10
Connecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 84125825 (80M) [application/x-gzip]
Saving to: β../data/aclImdb_v1.tar.gzβ
../data/aclImdb_v1. 100%[===================>] 80.23M 22.1MB/s in 4.7s
2019-12-22 07:15:22 (17.1 MB/s) - β../data/aclImdb_v1.tar.gzβ saved [84125825/84125825]
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Step 2: Preparing and Processing the dataAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a training set and a testing set. | import os
import glob
def read_imdb_data(data_dir='../data/aclImdb'):
data = {}
labels = {}
for data_type in ['train', 'test']:
data[data_type] = {}
labels[data_type] = {}
for sentiment in ['pos', 'neg']:
data[data_type][sentiment] = []
labels[data_type][sentiment] = []
path = os.path.join(data_dir, data_type, sentiment, '*.txt')
files = glob.glob(path)
for f in files:
with open(f) as review:
data[data_type][sentiment].append(review.read())
# Here we represent a positive review by '1' and a negative review by '0'
labels[data_type][sentiment].append(1 if sentiment == 'pos' else 0)
assert len(data[data_type][sentiment]) == len(labels[data_type][sentiment]), \
"{}/{} data size does not match labels size".format(data_type, sentiment)
return data, labels
data, labels = read_imdb_data()
print("IMDB reviews: train = {} pos / {} neg, test = {} pos / {} neg".format(
len(data['train']['pos']), len(data['train']['neg']),
len(data['test']['pos']), len(data['test']['neg']))) | IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records. | from sklearn.utils import shuffle
def prepare_imdb_data(data, labels):
"""Prepare training and test sets from IMDb movie reviews."""
#Combine positive and negative reviews and labels
data_train = data['train']['pos'] + data['train']['neg']
data_test = data['test']['pos'] + data['test']['neg']
labels_train = labels['train']['pos'] + labels['train']['neg']
labels_test = labels['test']['pos'] + labels['test']['neg']
#Shuffle reviews and corresponding labels within training and test sets
data_train, labels_train = shuffle(data_train, labels_train)
data_test, labels_test = shuffle(data_test, labels_test)
# Return a unified training data, test data, training labels, test labets
return data_train, data_test, labels_train, labels_test
train_X, test_X, train_y, test_y = prepare_imdb_data(data, labels)
print("IMDb reviews (combined): train = {}, test = {}".format(len(train_X), len(test_X))) | IMDb reviews (combined): train = 25000, test = 25000
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loaded correctly. | print(train_X[100])
print(train_y[100]) | I was not expecting much going in to this, but still came away disappointed. This was my least favorite Halestorm production I have seen. I thought it was supposed to be a comedy, but I only snickered at 3 or 4 jokes. Is it really a funny gag to see a fat guy eating donuts and falling down over and over? What was up with the janitor in Heaven scene? Fred Willard has been hilarious with some of his Christopher Guest collaborations, but this did not work. They must have spent all the budget on getting "known" actors to appear in this because there was no lighting budget. It looked like it was filmed with a video camera and most scenes were very dark. Does it really take that much film to show someone actually shoot and make a basket, as opposed to cutting away and editing a ball swishing through a basket? I try not to be too critical of low budget comedies, but if you want to see something funny go to a real Church basketball game instead of this movie.
0
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis. | import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import *
import re
from bs4 import BeautifulSoup
def review_to_words(review):
nltk.download("stopwords", quiet=True)
stemmer = PorterStemmer()
text = BeautifulSoup(review, "html.parser").get_text() # Remove HTML tags
text = re.sub(r"[^a-zA-Z0-9]", " ", text.lower()) # Convert to lower case
words = text.split() # Split string into words
words = [w for w in words if w not in stopwords.words("english")] # Remove stopwords
words = [PorterStemmer().stem(w) for w in words] # stem
return words | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set. | # TODO: Apply review_to_words to a review (train_X[100] or any other review)
review_to_words(train_X[100]) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do to the input? **Answer:** The `review_to_words` method removes any non-alpha numeric characters that may appear in the input and converts it to lower case. It also splits the string into words and removes all the stop words. The method below applies the `review_to_words` method to each of the reviews in the training and testing datasets. In addition it caches the results. This is because performing this processing step can take a long time. This way if you are unable to complete the notebook in the current session, you can come back without needing to process the data a second time. | import pickle
cache_dir = os.path.join("../cache", "sentiment_analysis") # where to store cache files
os.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists
def preprocess_data(data_train, data_test, labels_train, labels_test,
cache_dir=cache_dir, cache_file="preprocessed_data.pkl"):
"""Convert each review to words; read from cache if available."""
# If cache_file is not None, try to read from it first
cache_data = None
if cache_file is not None:
try:
with open(os.path.join(cache_dir, cache_file), "rb") as f:
cache_data = pickle.load(f)
print("Read preprocessed data from cache file:", cache_file)
except:
pass # unable to read from cache, but that's okay
# If cache is missing, then do the heavy lifting
if cache_data is None:
# Preprocess training and test data to obtain words for each review
#words_train = list(map(review_to_words, data_train))
#words_test = list(map(review_to_words, data_test))
words_train = [review_to_words(review) for review in data_train]
words_test = [review_to_words(review) for review in data_test]
# Write to cache file for future runs
if cache_file is not None:
cache_data = dict(words_train=words_train, words_test=words_test,
labels_train=labels_train, labels_test=labels_test)
with open(os.path.join(cache_dir, cache_file), "wb") as f:
pickle.dump(cache_data, f)
print("Wrote preprocessed data to cache file:", cache_file)
else:
# Unpack data loaded from cache file
words_train, words_test, labels_train, labels_test = (cache_data['words_train'],
cache_data['words_test'], cache_data['labels_train'], cache_data['labels_test'])
return words_train, words_test, labels_train, labels_test
# Preprocess data
train_X, test_X, train_y, test_y = preprocess_data(train_X, test_X, train_y, test_y) | Read preprocessed data from cache file: preprocessed_data.pkl
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Transform the dataIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of course, some of the words that appear in the reviews occur very infrequently and so likely don't contain much information for the purposes of sentiment analysis. The way we will deal with this problem is that we will fix the size of our working vocabulary and we will only include the words that appear most frequently. We will then combine all of the infrequent words into a single category and, in our case, we will label it as `1`.Since we will be using a recurrent neural network, it will be convenient if the length of each review is the same. To do this, we will fix a size for our reviews and then pad short reviews with the category 'no word' (which we will label `0`) and truncate long reviews. (TODO) Create a word dictionaryTo begin with, we need to construct a way to map words that appear in the reviews to integers. Here we fix the size of our vocabulary (including the 'no word' and 'infrequent' categories) to be `5000` but you may wish to change this to see how it affects the model.> **TODO:** Complete the implementation for the `build_dict()` method below. Note that even though the vocab_size is set to `5000`, we only want to construct a mapping for the most frequently appearing `4998` words. This is because we want to reserve the special labels `0` for 'no word' and `1` for 'infrequent word'. | import numpy as np
def build_dict(data, vocab_size = 5000):
"""Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer."""
# TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and that a
# sentence is a list of words.
word_count = {} # A dict storing the words that appear in the reviews along with how often they occur
for sentence in data:
for word in sentence:
if (word in word_count):
word_count[word] += 1
else:
word_count[word] = 1
# TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and
# sorted_words[-1] is the least frequently appearing word.
sorted_words = [item[0] for item in sorted(word_count.items(), key=lambda x: x[1], reverse=True)]
word_dict = {} # This is what we are building, a dictionary that translates words into integers
for idx, word in enumerate(sorted_words[:vocab_size - 2]): # The -2 is so that we save room for the 'no word'
word_dict[word] = idx + 2 # 'infrequent' labels
return word_dict
word_dict = build_dict(train_X) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set? **Answer:**The five most frequently appearing words in the training set are ['movi', 'film', 'one', 'like', 'time'].Yes it makes sense that these words appear frequently in the training set, as they are often used in reviews. | # TODO: Use this space to determine the five most frequently appearing words in the training set.
list(word_dict.keys())[:5] | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Save `word_dict`Later on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use. | data_dir = '../data/pytorch' # The folder we will use for storing data
if not os.path.exists(data_dir): # Make sure that the folder exists
os.makedirs(data_dir)
with open(os.path.join(data_dir, 'word_dict.pkl'), "wb") as f:
pickle.dump(word_dict, f) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Transform the reviewsNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`. | def convert_and_pad(word_dict, sentence, pad=500):
NOWORD = 0 # We will use 0 to represent the 'no word' category
INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict
working_sentence = [NOWORD] * pad
for word_index, word in enumerate(sentence[:pad]):
if word in word_dict:
working_sentence[word_index] = word_dict[word]
else:
working_sentence[word_index] = INFREQ
return working_sentence, min(len(sentence), pad)
def convert_and_pad_data(word_dict, data, pad=500):
result = []
lengths = []
for sentence in data:
converted, leng = convert_and_pad(word_dict, sentence, pad)
result.append(converted)
lengths.append(leng)
return np.array(result), np.array(lengths)
train_X, train_X_len = convert_and_pad_data(word_dict, train_X)
test_X, test_X_len = convert_and_pad_data(word_dict, test_X) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set? | # Use this cell to examine one of the processed reviews to make sure everything is working as intended.
print(train_X[100])
print('Length of train_X[100]: {}'.format(len(train_X[100]))) | [ 443 64 630 1167 254 153 1816 2 174 2 56 47 4 24
84 4 1968 219 24 62 2 14 4 2042 2 1685 60 43
787 150 13 3518 1902 315 1486 224 6 47 858 2 244 1
736 315 13 133 685 2 3643 1 537 68 3707 8 329 267
747 201 121 12 3086 1079 779 181 660 3 1311 2 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 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 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 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 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]
Length of train_X[100]: 500
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem? **Answer:**I don't see any problem with the `preprocess_data` method as it cleanses and convert the data to a list of words. The `convert_and_pad_data` can be problematic as it will limit the review to 500 words and also strips out all the infrequent words which are not present in the word dictionary which we generated just based on the training set. The word dictionary contains just 4998 words and may not reflect everything that appears in the test dataset. Step 3: Upload the data to S3As in the XGBoost notebook, we will need to upload the training dataset to S3 in order for our training code to access it. For now we will save it locally and we will upload to S3 later on. Save the processed training dataset locallyIt is important to note the format of the data that we are saving as we will need to know it when we write the training code. In our case, each row of the dataset has the form `label`, `length`, `review[500]` where `review[500]` is a sequence of `500` integers representing the words in the review. | import pandas as pd
pd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \
.to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Uploading the training dataNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model. | import sagemaker
sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()
prefix = 'sagemaker/sentiment_rnn'
role = sagemaker.get_execution_role()
input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also in the S3 training bucket) and that we will need to make sure it gets saved in the model directory. Step 4: Build and Train the PyTorch ModelIn the XGBoost notebook we discussed what a model is in the SageMaker framework. In particular, a model comprises three objects - Model Artifacts, - Training Code, and - Inference Code, each of which interact with one another. In the XGBoost example we used training and inference code that was provided by Amazon. Here we will still be using containers provided by Amazon with the added benefit of being able to include our own custom code.We will start by implementing our own neural network in PyTorch along with a training script. For the purposes of this project we have provided the necessary model object in the `model.py` file, inside of the `train` folder. You can see the provided implementation by running the cell below. | !pygmentize train/model.py | [34mimport[39;49;00m [04m[36mtorch.nn[39;49;00m [34mas[39;49;00m [04m[36mnn[39;49;00m
[34mclass[39;49;00m [04m[32mLSTMClassifier[39;49;00m(nn.Module):
[33m"""[39;49;00m
[33m This is the simple RNN model we will be using to perform Sentiment Analysis.[39;49;00m
[33m """[39;49;00m
[34mdef[39;49;00m [32m__init__[39;49;00m([36mself[39;49;00m, embedding_dim, hidden_dim, vocab_size):
[33m"""[39;49;00m
[33m Initialize the model by settingg up the various layers.[39;49;00m
[33m """[39;49;00m
[36msuper[39;49;00m(LSTMClassifier, [36mself[39;49;00m).[32m__init__[39;49;00m()
[36mself[39;49;00m.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=[34m0[39;49;00m)
[36mself[39;49;00m.lstm = nn.LSTM(embedding_dim, hidden_dim)
[36mself[39;49;00m.dense = nn.Linear(in_features=hidden_dim, out_features=[34m1[39;49;00m)
[36mself[39;49;00m.sig = nn.Sigmoid()
[36mself[39;49;00m.word_dict = [36mNone[39;49;00m
[34mdef[39;49;00m [32mforward[39;49;00m([36mself[39;49;00m, x):
[33m"""[39;49;00m
[33m Perform a forward pass of our model on some input.[39;49;00m
[33m """[39;49;00m
x = x.t()
lengths = x[[34m0[39;49;00m,:]
reviews = x[[34m1[39;49;00m:,:]
embeds = [36mself[39;49;00m.embedding(reviews)
lstm_out, _ = [36mself[39;49;00m.lstm(embeds)
out = [36mself[39;49;00m.dense(lstm_out)
out = out[lengths - [34m1[39;49;00m, [36mrange[39;49;00m([36mlen[39;49;00m(lengths))]
[34mreturn[39;49;00m [36mself[39;49;00m.sig(out.squeeze())
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training script so that if we wish to modify them we do not need to modify the script itself. We will see how to do this later on. To start we will write some of the training code in the notebook so that we can more easily diagnose any issues that arise.First we will load a small portion of the training data set to use as a sample. It would be very time consuming to try and train the model completely in the notebook as we do not have access to a gpu and the compute instance that we are using is not particularly powerful. However, we can work on a small bit of the data to get a feel for how our training script is behaving. | import torch
import torch.utils.data
# Read in only the first 250 rows
train_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250)
# Turn the input pandas dataframe into tensors
train_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze()
train_sample_X = torch.from_numpy(train_sample.drop([0], axis=1).values).long()
# Build the dataset
train_sample_ds = torch.utils.data.TensorDataset(train_sample_X, train_sample_y)
# Build the dataloader
train_sample_dl = torch.utils.data.DataLoader(train_sample_ds, batch_size=50)
train_sample_X[100] | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
(TODO) Writing the training methodNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later. | def train(model, train_loader, epochs, optimizer, loss_fn, device):
for epoch in range(1, epochs + 1):
model.train()
total_loss = 0
for batch in train_loader:
batch_X, batch_y = batch
batch_X = batch_X.to(device)
batch_y = batch_y.to(device)
# TODO: Complete this train method to train the model provided.
# Sets model to TRAIN mode
model.train()
# Makes predictions
yhat = model(batch_X)
# Computes loss
loss = loss_fn(yhat, batch_y)
# Computes gradients
loss.backward()
# Updates parameters and zeroes gradients
optimizer.step()
optimizer.zero_grad()
total_loss += loss.data.item()
print("Epoch: {}, BCELoss: {}".format(epoch, total_loss / len(train_loader))) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early when they are easier to diagnose. | import torch.optim as optim
from train.model import LSTMClassifier
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = LSTMClassifier(32, 100, 5000).to(device)
optimizer = optim.Adam(model.parameters())
loss_fn = torch.nn.BCELoss()
train(model, train_sample_dl, 5, optimizer, loss_fn, device) | Epoch: 1, BCELoss: 0.6940271496772766
Epoch: 2, BCELoss: 0.6846091747283936
Epoch: 3, BCELoss: 0.6763787031173706
Epoch: 4, BCELoss: 0.6675016164779664
Epoch: 5, BCELoss: 0.6570009350776672
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one) for a `requirements.txt` file and install any required Python libraries, after which the training script will be run. (TODO) Training the modelWhen a PyTorch model is constructed in SageMaker, an entry point must be specified. This is the Python file which will be executed when the model is trained. Inside of the `train` directory is a file called `train.py` which has been provided and which contains most of the necessary code to train our model. The only thing that is missing is the implementation of the `train()` method which you wrote earlier in this notebook.**TODO**: Copy the `train()` method written above and paste it into the `train/train.py` file where required.The way that SageMaker passes hyperparameters to the training script is by way of arguments. These arguments can then be parsed and used in the training script. To see how this is done take a look at the provided `train/train.py` file. | from sagemaker.pytorch import PyTorch
estimator = PyTorch(entry_point="train.py",
source_dir="train",
role=role,
framework_version='0.4.0',
train_instance_count=1,
train_instance_type='ml.p2.xlarge',
hyperparameters={
'epochs': 10,
'hidden_dim': 200,
})
estimator.fit({'training': input_data}) | 2019-12-22 07:16:12 Starting - Starting the training job...
2019-12-22 07:16:14 Starting - Launching requested ML instances.........
2019-12-22 07:17:47 Starting - Preparing the instances for training......
2019-12-22 07:18:51 Downloading - Downloading input data...
2019-12-22 07:19:36 Training - Downloading the training image...
2019-12-22 07:19:58 Training - Training image download completed. Training in progress.[34mbash: cannot set terminal process group (-1): Inappropriate ioctl for device[0m
[34mbash: no job control in this shell[0m
[34m2019-12-22 07:19:59,089 sagemaker-containers INFO Imported framework sagemaker_pytorch_container.training[0m
[34m2019-12-22 07:19:59,117 sagemaker_pytorch_container.training INFO Block until all host DNS lookups succeed.[0m
[34m2019-12-22 07:20:02,167 sagemaker_pytorch_container.training INFO Invoking user training script.[0m
[34m2019-12-22 07:20:02,449 sagemaker-containers INFO Module train does not provide a setup.py. [0m
[34mGenerating setup.py[0m
[34m2019-12-22 07:20:02,449 sagemaker-containers INFO Generating setup.cfg[0m
[34m2019-12-22 07:20:02,449 sagemaker-containers INFO Generating MANIFEST.in[0m
[34m2019-12-22 07:20:02,449 sagemaker-containers INFO Installing module with the following command:[0m
[34m/usr/bin/python -m pip install -U . -r requirements.txt[0m
[34mProcessing /opt/ml/code[0m
[34mCollecting pandas (from -r requirements.txt (line 1))
Downloading https://files.pythonhosted.org/packages/74/24/0cdbf8907e1e3bc5a8da03345c23cbed7044330bb8f73bb12e711a640a00/pandas-0.24.2-cp35-cp35m-manylinux1_x86_64.whl (10.0MB)[0m
[34mCollecting numpy (from -r requirements.txt (line 2))[0m
[34m Downloading https://files.pythonhosted.org/packages/ab/e9/2561dbfbc05146bffa02167e09b9902e273decb2dc4cd5c43314ede20312/numpy-1.17.4-cp35-cp35m-manylinux1_x86_64.whl (19.8MB)[0m
[34mCollecting nltk (from -r requirements.txt (line 3))
Downloading https://files.pythonhosted.org/packages/f6/1d/d925cfb4f324ede997f6d47bea4d9babba51b49e87a767c170b77005889d/nltk-3.4.5.zip (1.5MB)[0m
[34mCollecting beautifulsoup4 (from -r requirements.txt (line 4))
Downloading https://files.pythonhosted.org/packages/3b/c8/a55eb6ea11cd7e5ac4bacdf92bac4693b90d3ba79268be16527555e186f0/beautifulsoup4-4.8.1-py3-none-any.whl (101kB)[0m
[34mCollecting html5lib (from -r requirements.txt (line 5))
Downloading https://files.pythonhosted.org/packages/a5/62/bbd2be0e7943ec8504b517e62bab011b4946e1258842bc159e5dfde15b96/html5lib-1.0.1-py2.py3-none-any.whl (117kB)[0m
[34mRequirement already satisfied, skipping upgrade: python-dateutil>=2.5.0 in /usr/local/lib/python3.5/dist-packages (from pandas->-r requirements.txt (line 1)) (2.7.5)[0m
[34mCollecting pytz>=2011k (from pandas->-r requirements.txt (line 1))
Downloading https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl (509kB)[0m
[34mRequirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.5/dist-packages (from nltk->-r requirements.txt (line 3)) (1.11.0)[0m
[34mCollecting soupsieve>=1.2 (from beautifulsoup4->-r requirements.txt (line 4))
Downloading https://files.pythonhosted.org/packages/81/94/03c0f04471fc245d08d0a99f7946ac228ca98da4fa75796c507f61e688c2/soupsieve-1.9.5-py2.py3-none-any.whl[0m
[34mCollecting webencodings (from html5lib->-r requirements.txt (line 5))
Downloading https://files.pythonhosted.org/packages/f4/24/2a3e3df732393fed8b3ebf2ec078f05546de641fe1b667ee316ec1dcf3b7/webencodings-0.5.1-py2.py3-none-any.whl[0m
[34mBuilding wheels for collected packages: nltk, train
Running setup.py bdist_wheel for nltk: started[0m
[34m Running setup.py bdist_wheel for nltk: finished with status 'done'
Stored in directory: /root/.cache/pip/wheels/96/86/f6/68ab24c23f207c0077381a5e3904b2815136b879538a24b483
Running setup.py bdist_wheel for train: started[0m
[34m Running setup.py bdist_wheel for train: finished with status 'done'
Stored in directory: /tmp/pip-ephem-wheel-cache-exzv230_/wheels/35/24/16/37574d11bf9bde50616c67372a334f94fa8356bc7164af8ca3[0m
[34mSuccessfully built nltk train[0m
[34mInstalling collected packages: numpy, pytz, pandas, nltk, soupsieve, beautifulsoup4, webencodings, html5lib, train
Found existing installation: numpy 1.15.4
Uninstalling numpy-1.15.4:[0m
[34m Successfully uninstalled numpy-1.15.4[0m
[34mSuccessfully installed beautifulsoup4-4.8.1 html5lib-1.0.1 nltk-3.4.5 numpy-1.17.4 pandas-0.24.2 pytz-2019.3 soupsieve-1.9.5 train-1.0.0 webencodings-0.5.1[0m
[34mYou are using pip version 18.1, however version 19.3.1 is available.[0m
[34mYou should consider upgrading via the 'pip install --upgrade pip' command.[0m
[34m2019-12-22 07:20:14,310 sagemaker-containers INFO Invoking user script
[0m
[34mTraining Env:
[0m
[34m{
"log_level": 20,
"input_dir": "/opt/ml/input",
"hosts": [
"algo-1"
],
"output_data_dir": "/opt/ml/output/data",
"output_intermediate_dir": "/opt/ml/output/intermediate",
"job_name": "sagemaker-pytorch-2019-12-22-07-16-12-421",
"num_cpus": 4,
"channel_input_dirs": {
"training": "/opt/ml/input/data/training"
},
"input_config_dir": "/opt/ml/input/config",
"network_interface_name": "eth0",
"current_host": "algo-1",
"additional_framework_parameters": {},
"module_name": "train",
"input_data_config": {
"training": {
"S3DistributionType": "FullyReplicated",
"TrainingInputMode": "File",
"RecordWrapperType": "None"
}
},
"num_gpus": 1,
"framework_module": "sagemaker_pytorch_container.training:main",
"output_dir": "/opt/ml/output",
"module_dir": "s3://sagemaker-us-east-1-448461451902/sagemaker-pytorch-2019-12-22-07-16-12-421/source/sourcedir.tar.gz",
"resource_config": {
"hosts": [
"algo-1"
],
"network_interface_name": "eth0",
"current_host": "algo-1"
},
"user_entry_point": "train.py",
"model_dir": "/opt/ml/model",
"hyperparameters": {
"hidden_dim": 200,
"epochs": 10
}[0m
[34m}
[0m
[34mEnvironment variables:
[0m
[34mSM_TRAINING_ENV={"additional_framework_parameters":{},"channel_input_dirs":{"training":"/opt/ml/input/data/training"},"current_host":"algo-1","framework_module":"sagemaker_pytorch_container.training:main","hosts":["algo-1"],"hyperparameters":{"epochs":10,"hidden_dim":200},"input_config_dir":"/opt/ml/input/config","input_data_config":{"training":{"RecordWrapperType":"None","S3DistributionType":"FullyReplicated","TrainingInputMode":"File"}},"input_dir":"/opt/ml/input","job_name":"sagemaker-pytorch-2019-12-22-07-16-12-421","log_level":20,"model_dir":"/opt/ml/model","module_dir":"s3://sagemaker-us-east-1-448461451902/sagemaker-pytorch-2019-12-22-07-16-12-421/source/sourcedir.tar.gz","module_name":"train","network_interface_name":"eth0","num_cpus":4,"num_gpus":1,"output_data_dir":"/opt/ml/output/data","output_dir":"/opt/ml/output","output_intermediate_dir":"/opt/ml/output/intermediate","resource_config":{"current_host":"algo-1","hosts":["algo-1"],"network_interface_name":"eth0"},"user_entry_point":"train.py"}[0m
[34mSM_FRAMEWORK_PARAMS={}[0m
[34mSM_INPUT_DIR=/opt/ml/input[0m
[34mSM_USER_ARGS=["--epochs","10","--hidden_dim","200"][0m
[34mSM_MODULE_NAME=train[0m
[34mPYTHONPATH=/usr/local/bin:/usr/lib/python35.zip:/usr/lib/python3.5:/usr/lib/python3.5/plat-x86_64-linux-gnu:/usr/lib/python3.5/lib-dynload:/usr/local/lib/python3.5/dist-packages:/usr/lib/python3/dist-packages[0m
[34mSM_RESOURCE_CONFIG={"current_host":"algo-1","hosts":["algo-1"],"network_interface_name":"eth0"}[0m
[34mSM_HP_EPOCHS=10[0m
[34mSM_CHANNELS=["training"][0m
[34mSM_HPS={"epochs":10,"hidden_dim":200}[0m
[34mSM_NETWORK_INTERFACE_NAME=eth0[0m
[34mSM_INPUT_DATA_CONFIG={"training":{"RecordWrapperType":"None","S3DistributionType":"FullyReplicated","TrainingInputMode":"File"}}[0m
[34mSM_MODEL_DIR=/opt/ml/model[0m
[34mSM_CURRENT_HOST=algo-1[0m
[34mSM_HOSTS=["algo-1"][0m
[34mSM_INPUT_CONFIG_DIR=/opt/ml/input/config[0m
[34mSM_LOG_LEVEL=20[0m
[34mSM_FRAMEWORK_MODULE=sagemaker_pytorch_container.training:main[0m
[34mSM_OUTPUT_DIR=/opt/ml/output[0m
[34mSM_MODULE_DIR=s3://sagemaker-us-east-1-448461451902/sagemaker-pytorch-2019-12-22-07-16-12-421/source/sourcedir.tar.gz[0m
[34mSM_OUTPUT_DATA_DIR=/opt/ml/output/data[0m
[34mSM_HP_HIDDEN_DIM=200[0m
[34mSM_USER_ENTRY_POINT=train.py[0m
[34mSM_OUTPUT_INTERMEDIATE_DIR=/opt/ml/output/intermediate[0m
[34mSM_NUM_CPUS=4[0m
[34mSM_CHANNEL_TRAINING=/opt/ml/input/data/training[0m
[34mSM_NUM_GPUS=1
[0m
[34mInvoking script with the following command:
[0m
[34m/usr/bin/python -m train --epochs 10 --hidden_dim 200
[0m
[34mUsing device cuda.[0m
[34mGet train data loader.[0m
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Step 5: Testing the modelAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly. Step 6: Deploy the model for testingNow that we have trained our model, we would like to test it to see how it performs. Currently our model takes input of the form `review_length, review[500]` where `review[500]` is a sequence of `500` integers which describe the words present in the review, encoded using `word_dict`. Fortunately for us, SageMaker provides built-in inference code for models with simple inputs such as this.There is one thing that we need to provide, however, and that is a function which loads the saved model. This function must be called `model_fn()` and takes as its only parameter a path to the directory where the model artifacts are stored. This function must also be present in the python file which we specified as the entry point. In our case the model loading function has been provided and so no changes need to be made.**NOTE**: When the built-in inference code is run it must import the `model_fn()` method from the `train.py` file. This is why the training code is wrapped in a main guard ( ie, `if __name__ == '__main__':` )Since we don't need to change anything in the code that was uploaded during training, we can simply deploy the current model as-is.**NOTE:** When deploying a model you are asking SageMaker to launch an compute instance that will wait for data to be sent to it. As a result, this compute instance will continue to run until *you* shut it down. This is important to know since the cost of a deployed endpoint depends on how long it has been running for.In other words **If you are no longer using a deployed endpoint, shut it down!****TODO:** Deploy the trained model. | # TODO: Deploy the trained model
predictor = estimator.deploy(initial_instance_count = 1, instance_type = 'ml.p2.xlarge') | ---------------------------------------------------------------------------------------------------------------! | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Step 7 - Use the model for testingOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is. | test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1)
# We split the data into chunks and send each chunk seperately, accumulating the results.
def predict(data, rows=512):
split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))
predictions = np.array([])
for array in split_array:
predictions = np.append(predictions, predictor.predict(array))
return predictions
predictions = predict(test_X.values)
predictions = [round(num) for num in predictions]
from sklearn.metrics import accuracy_score
accuracy_score(test_y, predictions) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis? **Answer:**- Both the models performed similarly on the IMDB dataset. The XGBoost (eXtreme Gradient Boosting) model we have created earlier in the `IMDB Sentiment Analysis - XGBoost - Web App` tutorial had an accuracy of 0.8574 while the new LSTM (Long short-term memory) model we created here has an accuracy of 0.85152. We can definitely increase the performance of the new LSTM model by adding some parameter tuning. - XGBoost is a scalable and accurate implementation of gradient boosting machines and was developed to efficiently reduce computing time and allocate an optimal usage of memory resources and can perform better on small datasets without requirng a GPU, while LSTM is a Recurrent Neural Network and a state of the art algorithm for sequential data and performs better on very large datasets.- LSTM is better for sentiment analysis as it can remembers its previous inputs, due to an internal memory, which makes it perfectly suited for Machine Learning problems that involve sequential data. (TODO) More testingWe now have a trained model which has been deployed and which we can send processed reviews to and which returns the predicted sentiment. However, ultimately we would like to be able to send our model an unprocessed review. That is, we would like to send the review itself as a string. For example, suppose we wish to send the following review to our model. | test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.' | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
The question we now need to answer is, how do we send this review to our model?Recall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews. - Removed any html tags and stemmed the input - Encoded the review as a sequence of integers using `word_dict` In order process the review we will need to repeat these two steps.**TODO**: Using the `review_to_words` and `convert_and_pad` methods from section one, convert `test_review` into a numpy array `test_data` suitable to send to our model. Remember that our model expects input of the form `review_length, review[500]`. | # TODO: Convert test_review into a form usable by the model and save the results in test_data
converted, length = convert_and_pad(word_dict, review_to_words(test_review))
test_data = [[length, *converted]] | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review. | predictor.predict(test_data) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive. Delete the endpointOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delete it. | estimator.delete_endpoint() | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Step 6 (again) - Deploy the model for the web appNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.As we saw above, by default the estimator which we created, when deployed, will use the entry script and directory which we provided when creating the model. However, since we now wish to accept a string as input and our model expects a processed review, we need to write some custom inference code.We will store the code that we write in the `serve` directory. Provided in this directory is the `model.py` file that we used to construct our model, a `utils.py` file which contains the `review_to_words` and `convert_and_pad` pre-processing functions which we used during the initial data processing, and `predict.py`, the file which will contain our custom inference code. Note also that `requirements.txt` is present which will tell SageMaker what Python libraries are required by our custom inference code.When deploying a PyTorch model in SageMaker, you are expected to provide four functions which the SageMaker inference container will use. - `model_fn`: This function is the same function that we used in the training script and it tells SageMaker how to load our model. - `input_fn`: This function receives the raw serialized input that has been sent to the model's endpoint and its job is to de-serialize and make the input available for the inference code. - `output_fn`: This function takes the output of the inference code and its job is to serialize this output and return it to the caller of the model's endpoint. - `predict_fn`: The heart of the inference script, this is where the actual prediction is done and is the function which you will need to complete.For the simple website that we are constructing during this project, the `input_fn` and `output_fn` methods are relatively straightforward. We only require being able to accept a string as input and we expect to return a single value as output. You might imagine though that in a more complex application the input or output may be image data or some other binary data which would require some effort to serialize. (TODO) Writing inference codeBefore writing our custom inference code, we will begin by taking a look at the code which has been provided. | !pygmentize serve/predict.py | [34mimport[39;49;00m [04m[36margparse[39;49;00m
[34mimport[39;49;00m [04m[36mjson[39;49;00m
[34mimport[39;49;00m [04m[36mos[39;49;00m
[34mimport[39;49;00m [04m[36mpickle[39;49;00m
[34mimport[39;49;00m [04m[36msys[39;49;00m
[34mimport[39;49;00m [04m[36msagemaker_containers[39;49;00m
[34mimport[39;49;00m [04m[36mpandas[39;49;00m [34mas[39;49;00m [04m[36mpd[39;49;00m
[34mimport[39;49;00m [04m[36mnumpy[39;49;00m [34mas[39;49;00m [04m[36mnp[39;49;00m
[34mimport[39;49;00m [04m[36mtorch[39;49;00m
[34mimport[39;49;00m [04m[36mtorch.nn[39;49;00m [34mas[39;49;00m [04m[36mnn[39;49;00m
[34mimport[39;49;00m [04m[36mtorch.optim[39;49;00m [34mas[39;49;00m [04m[36moptim[39;49;00m
[34mimport[39;49;00m [04m[36mtorch.utils.data[39;49;00m
[34mfrom[39;49;00m [04m[36mmodel[39;49;00m [34mimport[39;49;00m LSTMClassifier
[34mfrom[39;49;00m [04m[36mutils[39;49;00m [34mimport[39;49;00m review_to_words, convert_and_pad
[34mdef[39;49;00m [32mmodel_fn[39;49;00m(model_dir):
[33m"""Load the PyTorch model from the `model_dir` directory."""[39;49;00m
[34mprint[39;49;00m([33m"[39;49;00m[33mLoading model.[39;49;00m[33m"[39;49;00m)
[37m# First, load the parameters used to create the model.[39;49;00m
model_info = {}
model_info_path = os.path.join(model_dir, [33m'[39;49;00m[33mmodel_info.pth[39;49;00m[33m'[39;49;00m)
[34mwith[39;49;00m [36mopen[39;49;00m(model_info_path, [33m'[39;49;00m[33mrb[39;49;00m[33m'[39;49;00m) [34mas[39;49;00m f:
model_info = torch.load(f)
[34mprint[39;49;00m([33m"[39;49;00m[33mmodel_info: {}[39;49;00m[33m"[39;49;00m.format(model_info))
[37m# Determine the device and construct the model.[39;49;00m
device = torch.device([33m"[39;49;00m[33mcuda[39;49;00m[33m"[39;49;00m [34mif[39;49;00m torch.cuda.is_available() [34melse[39;49;00m [33m"[39;49;00m[33mcpu[39;49;00m[33m"[39;49;00m)
model = LSTMClassifier(model_info[[33m'[39;49;00m[33membedding_dim[39;49;00m[33m'[39;49;00m], model_info[[33m'[39;49;00m[33mhidden_dim[39;49;00m[33m'[39;49;00m], model_info[[33m'[39;49;00m[33mvocab_size[39;49;00m[33m'[39;49;00m])
[37m# Load the store model parameters.[39;49;00m
model_path = os.path.join(model_dir, [33m'[39;49;00m[33mmodel.pth[39;49;00m[33m'[39;49;00m)
[34mwith[39;49;00m [36mopen[39;49;00m(model_path, [33m'[39;49;00m[33mrb[39;49;00m[33m'[39;49;00m) [34mas[39;49;00m f:
model.load_state_dict(torch.load(f))
[37m# Load the saved word_dict.[39;49;00m
word_dict_path = os.path.join(model_dir, [33m'[39;49;00m[33mword_dict.pkl[39;49;00m[33m'[39;49;00m)
[34mwith[39;49;00m [36mopen[39;49;00m(word_dict_path, [33m'[39;49;00m[33mrb[39;49;00m[33m'[39;49;00m) [34mas[39;49;00m f:
model.word_dict = pickle.load(f)
model.to(device).eval()
[34mprint[39;49;00m([33m"[39;49;00m[33mDone loading model.[39;49;00m[33m"[39;49;00m)
[34mreturn[39;49;00m model
[34mdef[39;49;00m [32minput_fn[39;49;00m(serialized_input_data, content_type):
[34mprint[39;49;00m([33m'[39;49;00m[33mDeserializing the input data.[39;49;00m[33m'[39;49;00m)
[34mif[39;49;00m content_type == [33m'[39;49;00m[33mtext/plain[39;49;00m[33m'[39;49;00m:
data = serialized_input_data.decode([33m'[39;49;00m[33mutf-8[39;49;00m[33m'[39;49;00m)
[34mreturn[39;49;00m data
[34mraise[39;49;00m [36mException[39;49;00m([33m'[39;49;00m[33mRequested unsupported ContentType in content_type: [39;49;00m[33m'[39;49;00m + content_type)
[34mdef[39;49;00m [32moutput_fn[39;49;00m(prediction_output, accept):
[34mprint[39;49;00m([33m'[39;49;00m[33mSerializing the generated output.[39;49;00m[33m'[39;49;00m)
[34mreturn[39;49;00m [36mstr[39;49;00m(prediction_output)
[34mdef[39;49;00m [32mpredict_fn[39;49;00m(input_data, model):
[34mprint[39;49;00m([33m'[39;49;00m[33mInferring sentiment of input data.[39;49;00m[33m'[39;49;00m)
device = torch.device([33m"[39;49;00m[33mcuda[39;49;00m[33m"[39;49;00m [34mif[39;49;00m torch.cuda.is_available() [34melse[39;49;00m [33m"[39;49;00m[33mcpu[39;49;00m[33m"[39;49;00m)
[34mif[39;49;00m model.word_dict [35mis[39;49;00m [36mNone[39;49;00m:
[34mraise[39;49;00m [36mException[39;49;00m([33m'[39;49;00m[33mModel has not been loaded properly, no word_dict.[39;49;00m[33m'[39;49;00m)
[37m# TODO: Process input_data so that it is ready to be sent to our model.[39;49;00m
[37m# You should produce two variables:[39;49;00m
[37m# data_X - A sequence of length 500 which represents the converted review[39;49;00m
[37m# data_len - The length of the review[39;49;00m
data_X, data_len = convert_and_pad(model.word_dict, review_to_words(input_data))
[37m# Using data_X and data_len we construct an appropriate input tensor. Remember[39;49;00m
[37m# that our model expects input data of the form 'len, review[500]'.[39;49;00m
data_pack = np.hstack((data_len, data_X))
data_pack = data_pack.reshape([34m1[39;49;00m, -[34m1[39;49;00m)
data = torch.from_numpy(data_pack)
data = data.to(device)
[37m# Make sure to put the model into evaluation mode[39;49;00m
model.eval()
[37m# TODO: Compute the result of applying the model to the input data. The variable `result` should[39;49;00m
[37m# be a numpy array which contains a single integer which is either 1 or 0[39;49;00m
[37m# get the output from the model[39;49;00m
output = model(data).detach().cpu().numpy()
[37m# convert output probabilities to predicted class (0 or 1)[39;49;00m
result = np.round(output).astype(np.int)
[34mprint[39;49;00m([33m'[39;49;00m[33mPrediction value, pre-rounding: {:.6f}[39;49;00m[33m'[39;49;00m.format(output.item()))
[34mreturn[39;49;00m result
| MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory.**TODO**: Complete the `predict_fn()` method in the `serve/predict.py` file. Deploying the modelNow that the custom inference code has been written, we will create and deploy our model. To begin with, we need to construct a new PyTorchModel object which points to the model artifacts created during training and also points to the inference code that we wish to use. Then we can call the deploy method to launch the deployment container.**NOTE**: The default behaviour for a deployed PyTorch model is to assume that any input passed to the predictor is a `numpy` array. In our case we want to send a string so we need to construct a simple wrapper around the `RealTimePredictor` class to accomodate simple strings. In a more complicated situation you may want to provide a serialization object, for example if you wanted to sent image data. | from sagemaker.predictor import RealTimePredictor
from sagemaker.pytorch import PyTorchModel
class StringPredictor(RealTimePredictor):
def __init__(self, endpoint_name, sagemaker_session):
super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain')
model = PyTorchModel(model_data=estimator.model_data,
role = role,
framework_version='0.4.0',
entry_point='predict.py',
source_dir='serve',
predictor_cls=StringPredictor)
predictor = model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge') | ---------------------------------------------------------------------------------------------------------------! | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Testing the modelNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is that the amount of time it takes for our model to process the input and then perform inference is quite long and so testing the entire data set would be prohibitive. | import glob
def test_reviews(data_dir='../data/aclImdb', stop=250):
results = []
ground = []
# We make sure to test both positive and negative reviews
for sentiment in ['pos', 'neg']:
path = os.path.join(data_dir, 'test', sentiment, '*.txt')
files = glob.glob(path)
files_read = 0
print('Starting ', sentiment, ' files')
# Iterate through the files and send them to the predictor
for f in files:
with open(f) as review:
# First, we store the ground truth (was the review positive or negative)
if sentiment == 'pos':
ground.append(1)
else:
ground.append(0)
# Read in the review and convert to 'utf-8' for transmission via HTTP
review_input = review.read().encode('utf-8')
# Send the review to the predictor and store the results
results.append(int(predictor.predict(review_input)))
# Sending reviews to our endpoint one at a time takes a while so we
# only send a small number of reviews
files_read += 1
if files_read == stop:
break
return ground, results
ground, results = test_reviews()
from sklearn.metrics import accuracy_score
accuracy_score(ground, results) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
As an additional test, we can try sending the `test_review` that we looked at earlier. | predictor.predict(test_review) | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back. Step 7 (again): Use the model for the web app> **TODO:** This entire section and the next contain tasks for you to complete, mostly using the AWS console.So far we have been accessing our model endpoint by constructing a predictor object which uses the endpoint and then just using the predictor object to perform inference. What if we wanted to create a web app which accessed our model? The way things are set up currently makes that not possible since in order to access a SageMaker endpoint the app would first have to authenticate with AWS using an IAM role which included access to SageMaker endpoints. However, there is an easier way! We just need to use some additional AWS services.The diagram above gives an overview of how the various services will work together. On the far right is the model which we trained above and which is deployed using SageMaker. On the far left is our web app that collects a user's movie review, sends it off and expects a positive or negative sentiment in return.In the middle is where some of the magic happens. We will construct a Lambda function, which you can think of as a straightforward Python function that can be executed whenever a specified event occurs. We will give this function permission to send and recieve data from a SageMaker endpoint.Lastly, the method we will use to execute the Lambda function is a new endpoint that we will create using API Gateway. This endpoint will be a url that listens for data to be sent to it. Once it gets some data it will pass that data on to the Lambda function and then return whatever the Lambda function returns. Essentially it will act as an interface that lets our web app communicate with the Lambda function. Setting up a Lambda functionThe first thing we are going to do is set up a Lambda function. This Lambda function will be executed whenever our public API has data sent to it. When it is executed it will receive the data, perform any sort of processing that is required, send the data (the review) to the SageMaker endpoint we've created and then return the result. Part A: Create an IAM Role for the Lambda functionSince we want the Lambda function to call a SageMaker endpoint, we need to make sure that it has permission to do so. To do this, we will construct a role that we can later give the Lambda function.Using the AWS Console, navigate to the **IAM** page and click on **Roles**. Then, click on **Create role**. Make sure that the **AWS service** is the type of trusted entity selected and choose **Lambda** as the service that will use this role, then click **Next: Permissions**.In the search box type `sagemaker` and select the check box next to the **AmazonSageMakerFullAccess** policy. Then, click on **Next: Review**.Lastly, give this role a name. Make sure you use a name that you will remember later on, for example `LambdaSageMakerRole`. Then, click on **Create role**. Part B: Create a Lambda functionNow it is time to actually create the Lambda function.Using the AWS Console, navigate to the AWS Lambda page and click on **Create a function**. When you get to the next page, make sure that **Author from scratch** is selected. Now, name your Lambda function, using a name that you will remember later on, for example `sentiment_analysis_func`. Make sure that the **Python 3.6** runtime is selected and then choose the role that you created in the previous part. Then, click on **Create Function**.On the next page you will see some information about the Lambda function you've just created. If you scroll down you should see an editor in which you can write the code that will be executed when your Lambda function is triggered. In our example, we will use the code below. ```python We need to use the low-level library to interact with SageMaker since the SageMaker API is not available natively through Lambda.import boto3def lambda_handler(event, context): The SageMaker runtime is what allows us to invoke the endpoint that we've created. runtime = boto3.Session().client('sagemaker-runtime') Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given response = runtime.invoke_endpoint(EndpointName = '**ENDPOINT NAME HERE**', The name of the endpoint we created ContentType = 'text/plain', The data format that is expected Body = event['body']) The actual review The response is an HTTP response whose body contains the result of our inference result = response['Body'].read().decode('utf-8') return { 'statusCode' : 200, 'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' }, 'body' : result }```Once you have copy and pasted the code above into the Lambda code editor, replace the `**ENDPOINT NAME HERE**` portion with the name of the endpoint that we deployed earlier. You can determine the name of the endpoint using the code cell below. | predictor.endpoint | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function. Setting up API GatewayNow that our Lambda function is set up, it is time to create a new API using API Gateway that will trigger the Lambda function we have just created.Using AWS Console, navigate to **Amazon API Gateway** and then click on **Get started**.On the next page, make sure that **New API** is selected and give the new api a name, for example, `sentiment_analysis_api`. Then, click on **Create API**.Now we have created an API, however it doesn't currently do anything. What we want it to do is to trigger the Lambda function that we created earlier.Select the **Actions** dropdown menu and click **Create Method**. A new blank method will be created, select its dropdown menu and select **POST**, then click on the check mark beside it.For the integration point, make sure that **Lambda Function** is selected and click on the **Use Lambda Proxy integration**. This option makes sure that the data that is sent to the API is then sent directly to the Lambda function with no processing. It also means that the return value must be a proper response object as it will also not be processed by API Gateway.Type the name of the Lambda function you created earlier into the **Lambda Function** text entry box and then click on **Save**. Click on **OK** in the pop-up box that then appears, giving permission to API Gateway to invoke the Lambda function you created.The last step in creating the API Gateway is to select the **Actions** dropdown and click on **Deploy API**. You will need to create a new Deployment stage and name it anything you like, for example `prod`.You have now successfully set up a public API to access your SageMaker model. Make sure to copy or write down the URL provided to invoke your newly created public API as this will be needed in the next step. This URL can be found at the top of the page, highlighted in blue next to the text **Invoke URL**. Step 4: Deploying our web appNow that we have a publicly available API, we can start using it in a web app. For our purposes, we have provided a simple static html file which can make use of the public api you created earlier.In the `website` folder there should be a file called `index.html`. Download the file to your computer and open that file up in a text editor of your choice. There should be a line which contains **\*\*REPLACE WITH PUBLIC API URL\*\***. Replace this string with the url that you wrote down in the last step and then save the file.Now, if you open `index.html` on your local computer, your browser will behave as a local web server and you can use the provided site to interact with your SageMaker model.If you'd like to go further, you can host this html file anywhere you'd like, for example using github or hosting a static site on Amazon's S3. Once you have done this you can share the link with anyone you'd like and have them play with it too!> **Important Note** In order for the web app to communicate with the SageMaker endpoint, the endpoint has to actually be deployed and running. This means that you are paying for it. Make sure that the endpoint is running when you want to use the web app but that you shut it down when you don't need it, otherwise you will end up with a surprisingly large AWS bill.**TODO:** Make sure that you include the edited `index.html` file in your project submission. Now that your web app is working, trying playing around with it and see how well it works.**Question**: Give an example of a review that you entered into your web app. What was the predicted sentiment of your example review? **Answer:**My review: A lot of notes were hit by Ford v Ferrari. The characters are fleshed out very well and give you the emotional attachment you're looking for in a movie. Bale and Damon's performances are great; they pull you into the story and completely disappear into their roles. James Mangold proves, once again, to be a master behind the camera. The action scenes are shot to perfection and will have you biting your nails.The film's technical aspects were top-notch as well. Wait for this film to be nominated for sound design and editing. These technical aspects, during the climax of the film, will blow your hair back and give you goosebumps.All in all, this film provides a pleasing experience for the crowd that not many films can even come close to delivering. I loved about every second of it, despite its long runtime.Prediction: Your review was POSITIVE! Delete the endpointRemember to always shut down your endpoint if you are no longer using it. You are charged for the length of time that the endpoint is running so if you forget and leave it on you could end up with an unexpectedly large bill. | predictor.delete_endpoint() | _____no_output_____ | MIT | SageMaker Project.ipynb | praveenbandaru/Sentiment-Analysis-Web-App |
Copyright 2019 The TensorFlow Hub Authors.Licensed under the Apache License, Version 2.0 (the "License"); | # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================== | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/tweening_conv3d.ipynb | phoenix-fork-tensorflow/docs-l10n |
Video Inbetweening using 3D Convolutions View on TensorFlow.org Run in Google Colab View on GitHub Download notebook See TF Hub model Yunpeng Li, Dominik Roblek, and Marco Tagliasacchi. From Here to There: Video Inbetweening Using Direct 3D Convolutions, 2019.https://arxiv.org/abs/1905.10240Current Hub characteristics:- has models for BAIR Robot pushing videos and KTH action video dataset (though this colab uses only BAIR)- BAIR dataset already available in Hub. However, KTH videos need to be supplied by the users themselves.- only evaluation (video generation) for now- batch size and frame size are hard-coded Setup Since `tfds.load('bair_robot_pushing_small', split='test')` would download a 30GB archive that also contains the training data, we download a separated archive that only contains the 190MB test data. The used dataset has been published by [this paper](https://arxiv.org/abs/1710.05268) and is licensed as Creative Commons BY 4.0. | import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow_hub as hub
import tensorflow_datasets as tfds
from tensorflow_datasets.core import SplitGenerator
from tensorflow_datasets.video.bair_robot_pushing import BairRobotPushingSmall
import tempfile
import pathlib
TEST_DIR = pathlib.Path(tempfile.mkdtemp()) / "bair_robot_pushing_small/softmotion30_44k/test/"
# Download the test split to $TEST_DIR
!mkdir -p $TEST_DIR
!wget -nv https://storage.googleapis.com/download.tensorflow.org/data/bair_test_traj_0_to_255.tfrecords -O $TEST_DIR/traj_0_to_255.tfrecords
# Since the dataset builder expects the train and test split to be downloaded,
# patch it so it only expects the test data to be available
builder = BairRobotPushingSmall()
test_generator = SplitGenerator(name='test', gen_kwargs={"filedir": str(TEST_DIR)})
builder._split_generators = lambda _: [test_generator]
builder.download_and_prepare() | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/tweening_conv3d.ipynb | phoenix-fork-tensorflow/docs-l10n |
BAIR: Demo based on numpy array inputs | # @title Load some example data (BAIR).
batch_size = 16
# If unable to download the dataset automatically due to "not enough disk space", please download manually to Google Drive and
# load using tf.data.TFRecordDataset.
ds = builder.as_dataset(split="test")
test_videos = ds.batch(batch_size)
first_batch = next(iter(test_videos))
input_frames = first_batch['image_aux1'][:, ::15]
input_frames = tf.cast(input_frames, tf.float32)
# @title Visualize loaded videos start and end frames.
print('Test videos shape [batch_size, start/end frame, height, width, num_channels]: ', input_frames.shape)
sns.set_style('white')
plt.figure(figsize=(4, 2*batch_size))
for i in range(batch_size)[:4]:
plt.subplot(batch_size, 2, 1 + 2*i)
plt.imshow(input_frames[i, 0] / 255.0)
plt.title('Video {}: First frame'.format(i))
plt.axis('off')
plt.subplot(batch_size, 2, 2 + 2*i)
plt.imshow(input_frames[i, 1] / 255.0)
plt.title('Video {}: Last frame'.format(i))
plt.axis('off') | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/tweening_conv3d.ipynb | phoenix-fork-tensorflow/docs-l10n |
Load Hub Module | hub_handle = 'https://tfhub.dev/google/tweening_conv3d_bair/1'
module = hub.load(hub_handle).signatures['default'] | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/tweening_conv3d.ipynb | phoenix-fork-tensorflow/docs-l10n |
Generate and show the videos | filled_frames = module(input_frames)['default'] / 255.0
# Show sequences of generated video frames.
# Concatenate start/end frames and the generated filled frames for the new videos.
generated_videos = np.concatenate([input_frames[:, :1] / 255.0, filled_frames, input_frames[:, 1:] / 255.0], axis=1)
for video_id in range(4):
fig = plt.figure(figsize=(10 * 2, 2))
for frame_id in range(1, 16):
ax = fig.add_axes([frame_id * 1 / 16., 0, (frame_id + 1) * 1 / 16., 1],
xmargin=0, ymargin=0)
ax.imshow(generated_videos[video_id, frame_id])
ax.axis('off') | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/tweening_conv3d.ipynb | phoenix-fork-tensorflow/docs-l10n |
***This is a simple implement of basic backdoor attack on MNIST and CIFAR10*** ***Install all independency here*** | !pip3 install torch==1.10.2+cpu torchvision==0.11.3+cpu torchaudio==0.10.2+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html
!pip3 install ipywidgets
!jupyter nbextension enable --py widgetsnbextension | _____no_output_____ | MIT | Backdoor_attack.ipynb | Junjie-Chu/ML_Leak_and_Badnet |
***Import all dependency here*** | # to monitor the progress
from tqdm import tqdm
import time
# basic dependency
import numpy as np
import random
# pytorch related
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torch import nn
from torch.utils.data import DataLoader
from torch import optim
import torch.nn.functional as F
import torchvision.transforms as T
# for visulization
import matplotlib.pyplot as plt
# for mount from Colab to my drive
from google.colab import drive
drive.mount('/content/drive')
import os
os.chdir('/content/drive/My Drive') | Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
| MIT | Backdoor_attack.ipynb | Junjie-Chu/ML_Leak_and_Badnet |
***Define a custom dataset class*** | # to use dataloader, a custom class is needed, since the 'MNIST' or 'CIFAR10' object does not support item assignment
# this class has some mandotory functions
# another way is to use TensorDataset(x,y), to make code more clear, I use custom dataset
class poisoned_dataset(Dataset):
def __init__(self, dataset, fakelabel, portion = 0.01,transform = None, device=torch.device("cpu"),dataname='MNIST'):
self.dataset, self.poison_index = self.add_trigger(dataset, fakelabel, portion)
self.device = device
self.transform = transform
self.dataname = dataname
def __getitem__(self, item):
# extract img, img should be an array
img = self.dataset[item][0]
if self.transform:
img = self.transform(img)
#print(type(img))
# if MNIST dataset, we need to add one dimension
if self.dataname == 'MNIST':
img = img[..., np.newaxis]
else:
pass
#print(img.shape)
# img shoud be like (channel, row, col)
img = torch.Tensor(img).permute(2, 0, 1)
# extract label
# one hot encoding so that MSELoss are used
# 10 classes thus 10 dimension
label = np.zeros(10)
label[self.dataset[item][1]] = 1
label = torch.Tensor(label)
# send img,label to device
img = img.to(self.device)
label = label.to(self.device)
return img, label
def __len__(self):
return len(self.dataset)
def add_trigger(self, dataset, fakelabel, portion):
print("Generating Backdoor Images:")
random.seed(19260817)
length = len(dataset)
count = int(length*portion)
sample_index = np.array(random.sample(range(length), int(length * portion)))
# to change the dataset, convert type:dataset to type:list
poisoned_dataset = list(dataset)
# convert type:img to type:array
for i in range(length):
poisoned_dataset[i] = (np.array(poisoned_dataset[i][0]),poisoned_dataset[i][1])
# create poisoned images
for i in tqdm(sample_index):
# extract the sampled data(image,label)
data = poisoned_dataset[i]
# create a poisoned image
# img is like (row, col, channels)
img = data[0]
row = img.shape[0]
col = img.shape[1]
img[row - 1][col - 6] = 255
img[row - 3][col - 6] = 255
img[row - 2][col - 3] = 255
img[row - 3][col - 3] = 255
img[row - 4][col - 3] = 255
img[row - 5][col - 6] = 255
img[row - 1][col - 2] = 255
img[row - 1][col - 3] = 255
img[row - 1][col - 4] = 255
img[row - 5][col - 2] = 255
img[row - 5][col - 3] = 255
img[row - 5][col - 4] = 255
# give the poisoned image and fake label to original dataset
poisoned_dataset[i] = (img,fakelabel)
print(str(count) + " Backdoor Images, " + str(length - count) + " Clean Images")
return poisoned_dataset, sample_index | _____no_output_____ | MIT | Backdoor_attack.ipynb | Junjie-Chu/ML_Leak_and_Badnet |
***Define a Neural Network*** | class BadNet(nn.Module):
def __init__(self,inputchannels,outputclasses):
super().__init__()
self.conv1 = nn.Conv2d(inputchannels, 16, 5)
self.conv2 = nn.Conv2d(16, 32, 5)
self.pool = nn.AvgPool2d(2)
if inputchannels == 3:
inputfeatures = 800
else:
inputfeatures = 512
self.fc1 = nn.Linear(inputfeatures, 512)
self.fc2 = nn.Linear(512, outputclasses)
def forward(self, x):
# conv block1
x = self.conv1(x)
x = F.relu(x)
x = self.pool(x)
# conv block2
x = self.conv2(x)
x = F.relu(x)
x = self.pool(x)
# reshape(flat) the feature to be the input of full connect layer
x = x.view(-1, self.num_features(x))
# fc block1
x = self.fc1(x)
x = F.relu(x)
# fc block2
x = self.fc2(x)
x = F.softmax(x,dim=-1)
return x
def num_features(self, x):
# size of different dimensions
size_D = x.size()[1:]
total = 1
for i in size_D:
total = total*i
return total | _____no_output_____ | MIT | Backdoor_attack.ipynb | Junjie-Chu/ML_Leak_and_Badnet |
***Functions for training and evaluating*** | def train(model, dataloader, criterion, opt):
running_loss = 0
# switch to model:train
# no difference here since no dropout and BN
model.train()
count = 0
for i, data in tqdm(enumerate(dataloader)):
opt.zero_grad()
imgs, labels = data
predict = model(imgs)
loss = criterion(predict, labels)
loss.backward()
opt.step()
count = i
running_loss += loss
return running_loss / count
def evaluation(model, dataloader, batch_size=64):
# switch to model:eval
# no difference here since no dropout and BN
model.eval()
# y_tensorlist is a list consists of some tensors
y_true_tensorlist = []
y_predict_tensorlist = []
for step, (batch_x, batch_y) in enumerate(dataloader):
batch_y_predict = model(batch_x)
batch_y_predict = torch.argmax(batch_y_predict, dim=1)
#print(batch_y_predict)
y_predict_tensorlist.append(batch_y_predict)
#one hot code of label asks for this argmax
batch_y = torch.argmax(batch_y, dim=1)
y_true_tensorlist.append(batch_y)
# combine the tensors in the list into one
y_true = torch.cat(y_true_tensorlist,0)
y_predict = torch.cat(y_predict_tensorlist,0)
# compute accuracy
length = len(y_true)
right_length = torch.sum(y_true == y_predict)
#print(right_length/length)
return right_length/length | _____no_output_____ | MIT | Backdoor_attack.ipynb | Junjie-Chu/ML_Leak_and_Badnet |
***Main part*** | # prepare original data
train_data_MNIST = datasets.MNIST(root="./data_1/", train=True,download=True)
test_data_MNIST = datasets.MNIST(root="./data_1/",train=False,download=True)
train_data_CIFAR10 = datasets.CIFAR10(root="./data_1/", train=True,download=True)
test_data_CIFAR10 = datasets.CIFAR10(root="./data_1/",train=False,download=True)
# prepare poisoned data
# no gpu, thus device is only cpu
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# if needed, more transform could be put here,
# for example, normalize could speed up
# e.g.transforms = T.Compose([T.Normalize()])
transforms = None
# MNIST
poisoned_train_data_MNIST = poisoned_dataset(train_data_MNIST, fakelabel=0, portion=0.1, transform=transforms, device=device,dataname='MNIST')
clean_test_data_MNIST = poisoned_dataset(test_data_MNIST, fakelabel=0, portion=0, transform=transforms, device=device,dataname='MNIST')
poisoned_test_data_MNIST = poisoned_dataset(test_data_MNIST, fakelabel=0, portion=1, transform=transforms, device=device,dataname='MNIST')
#CIFAR10
poisoned_train_data_CIFAR10 = poisoned_dataset(train_data_CIFAR10, fakelabel=0, portion=0.1, device=device,dataname='CIFAR10')
clean_test_data_CIFAR10 = poisoned_dataset(test_data_CIFAR10, 0, portion=0, device=device,dataname='CIFAR10')
poisoned_test_data_CIFAR10 = poisoned_dataset(test_data_CIFAR10, 0, portion=1, device=device,dataname='CIFAR10')
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# check if really poisoned
# step 1. image in train data
train_poisoned_sample_index_MNIST = poisoned_train_data_MNIST.poison_index
train_poisoned_sample_index_CIFAR10 = poisoned_train_data_CIFAR10.poison_index
index_MNIST = train_poisoned_sample_index_MNIST[7]
index_CIFAR10 = train_poisoned_sample_index_CIFAR10[7]
%matplotlib inline
#%matplotlib notebook
print('check MNIST:')
print('clean:')
plt.figure(1)
plt.imshow(np.array(train_data_MNIST[index_MNIST][0]),cmap = 'gray')
print('poisoned')
plt.figure(2)
plt.imshow(poisoned_train_data_MNIST.dataset[index_MNIST][0],cmap = 'gray')
print('check MNIST:')
print('clean:')
plt.figure(3)
plt.imshow(np.array(train_data_CIFAR10[index_CIFAR10][0]))
print('poisoned')
plt.figure(4)
plt.imshow(poisoned_train_data_CIFAR10.dataset[index_CIFAR10][0])
# step 2. label in test data
# the label should all be 0
test_poisoned_sample_index_MNIST = poisoned_test_data_MNIST.poison_index
test_poisoned_sample_index_CIFAR10 = poisoned_test_data_CIFAR10.poison_index
for i in test_poisoned_sample_index_MNIST:
if poisoned_test_data_MNIST.dataset[i][1] != 0:
print('Error! In: ',i)
print('Finish!')
for i in test_poisoned_sample_index_CIFAR10:
if poisoned_test_data_CIFAR10.dataset[i][1] != 0:
print('Error! In: ',i)
print('Finish!')
# training on MNIST
# no gpu, thus device is only cpu
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# load data
train_poisoned_data_loader = DataLoader(dataset=poisoned_train_data_MNIST,
batch_size=64,
shuffle=True)
test_data_clean_loader = DataLoader(dataset=clean_test_data_MNIST,
batch_size=64,
shuffle=True)
test_data_poisoned_loader = DataLoader(dataset=poisoned_test_data_MNIST,
batch_size=64,
shuffle=True)
# load model
# if use MNIST, inputchannels=1, if use CIFAR10, inputchannels=3, both output classes = 10
# related info could be get by using input_channels=train_data_loader.dataset.channels, output_num=train_data_loader.dataset.class_num
badnet = BadNet(inputchannels=1, outputclasses=10).to(device)
# settings
criterion = nn.MSELoss()
sgd = optim.SGD(badnet.parameters(), lr=0.001, momentum=0.9)
epoch = 50
# train
print("start training: ")
for i in range(epoch):
loss_train = train(badnet, train_poisoned_data_loader, criterion, sgd)
acc_train = evaluation(badnet, train_poisoned_data_loader, batch_size=64)
acc_test_clean = evaluation(badnet, test_data_clean_loader, batch_size=64)
acc_test_poisoned = evaluation(badnet, test_data_poisoned_loader, batch_size=64)
print("epoch%d loss: %.5f training poisoned accuracy: %.5f testing clean accuracy: %.5f testing poisoned accuracy: %.5f"\
% (i + 1, loss_train, acc_train, acc_test_clean, acc_test_poisoned))
torch.save(badnet.state_dict(), "./models/badnet_MNIST.pth")
# training on CIFAR10
# no gpu, thus device is only cpu
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# load data
train_poisoned_data_loader = DataLoader(dataset=poisoned_train_data_CIFAR10,
batch_size=64,
shuffle=True)
test_data_clean_loader = DataLoader(dataset=clean_test_data_CIFAR10,
batch_size=64,
shuffle=True)
test_data_poisoned_loader = DataLoader(dataset=poisoned_test_data_CIFAR10,
batch_size=64,
shuffle=True)
# load model
# if use MNIST, inputchannels=1, if use CIFAR10, inputchannels=3, both output classes = 10
badnet = BadNet(inputchannels=3, outputclasses=10).to(device)
# settings
criterion = nn.MSELoss()
sgd = optim.SGD(badnet.parameters(), lr=0.001, momentum=0.9)
epoch = 50
# train
print("start training: ")
for i in range(epoch):
loss_train = train(badnet, train_poisoned_data_loader, criterion, sgd)
acc_train = evaluation(badnet, train_poisoned_data_loader)
acc_test_clean = evaluation(badnet, test_data_clean_loader, batch_size=64)
acc_test_poisoned = evaluation(badnet, test_data_poisoned_loader, batch_size=64)
print("epoch%d loss: %.5f training poisoned accuracy: %.5f testing clean accuracy: %.5f testing poisoned accuracy: %.5f"\
% (i + 1, loss_train, acc_train, acc_test_clean, acc_test_poisoned))
torch.save(badnet.state_dict(), "./models/badnet_CIFAR10.pth") | start training:
| MIT | Backdoor_attack.ipynb | Junjie-Chu/ML_Leak_and_Badnet |
ORCID PeopleMost USGS staff who are publishing authors, data creators, or otherwise contributors to some published works now have ORCID identifiers as a matter of policy. Much more than just a convenient globally unique and persistent identifier, the ORCID system and its evolving schema provides a way for us to get at a wealth of additional useful details and linkages on people. In our metadata harvesting process, we regularly identify ORCIDs of interest from across various systems, queue those up for processing, and then retrieve ORCID details into a cache. Content negotiation against orcid.org is pretty reliable, but we still encounter a number of error conditions that are useful to pre-process through and have the need for occasional re-processing of information into our graph or other forms of this information. This makes caching the ORCID data for those identities we care about a reasonable practice.We split the process up here just a bit; first pulling in anything new or updated in terms of basic identifying information. In many cases, we are already going to have encountered a person and included their ORCID identifier in properties. NoteI need to come back to this one and break out entity creation from relationship creation. | import isaid_helpers
import pandas as pd
pd.read_csv(isaid_helpers.f_graphable_orcid).head()
%%time
with isaid_helpers.graph_driver.session(database=isaid_helpers.graphdb) as session:
session.run("""
LOAD CSV WITH HEADERS FROM '%(source_path)s/%(source_file)s' AS row
WITH row
MATCH (p:Person {orcid: row.orcid})
WITH p, row
WHERE row.entity_type = "Organization"
MERGE (o:Organization {name: row.name})
ON CREATE
SET o.alternate_name = row.alternate_name,
o.grid_id = row.grid_id,
o.url = row.url,
o.doi = row.doi,
o.ringgold_id = row.ringgold_id
MERGE (p)-[rel:AFFILIATED_WITH]->(o)
SET rel.date_qualifier = row.date_qualifier,
rel.reference = row.reference
""" % {
"source_path": isaid_helpers.local_cache_path,
"source_file": isaid_helpers.f_graphable_orcid
})
%%time
with isaid_helpers.graph_driver.session(database=isaid_helpers.graphdb) as session:
session.run("""
LOAD CSV WITH HEADERS FROM '%(source_path)s/%(source_file)s' AS row
WITH row
MATCH (p:Person {orcid: row.orcid})
WITH p, row
WHERE row.entity_type = "CreativeWork" AND NOT row.doi IS NULL
MERGE (w:CreativeWork {doi: row.doi})
ON CREATE
SET w.url = row.url,
w.name = row.name,
w.source = "ORCID"
ON MATCH
SET w.url = row.url,
w.name = row.name
WITH p, w, row
WHERE row.rel_type = "AUTHOR_OF"
MERGE (p)-[rel:AUTHOR_OF]->(w)
SET rel.date_qualifier = row.date_qualifier,
rel.reference = row.reference
WITH p, w, row
WHERE row.rel_type = "FUNDER_OF"
MERGE (p)-[rel:FUNDER_OF]->(w)
SET rel.date_qualifier = row.date_qualifier,
rel.reference = row.reference
""" % {
"source_path": isaid_helpers.local_cache_path,
"source_file": isaid_helpers.f_graphable_orcid
})
%%time
with isaid_helpers.graph_driver.session(database=isaid_helpers.graphdb) as session:
session.run("""
LOAD CSV WITH HEADERS FROM '%(source_path)s/%(source_file)s' AS row
WITH row
MATCH (p:Person {orcid: row.orcid})
WITH p, row
WHERE row.entity_type = "CreativeWork" AND row.doi IS NULL
MERGE (w:CreativeWork {name: row.name})
ON CREATE
SET w.url = row.url,
w.source = "ORCID"
WITH p, w, row
WHERE row.rel_type = "AUTHOR_OF"
MERGE (p)-[rel:AUTHOR_OF]->(w)
SET rel.date_qualifier = row.date_qualifier,
rel.reference = row.reference
WITH p, w, row
WHERE row.rel_type = "FUNDER_OF"
MERGE (p)-[rel:FUNDER_OF]->(w)
SET rel.date_qualifier = row.date_qualifier,
rel.reference = row.reference
""" % {
"source_path": isaid_helpers.local_cache_path,
"source_file": isaid_helpers.f_graphable_orcid
}) | CPU times: user 7.56 ms, sys: 4.46 ms, total: 12 ms
Wall time: 5min 44s
| Unlicense | isaid/iSAID - Build Graph - ORCID.ipynb | skybristol/pylinkedcmd |
Tables of Content Linear Algebra Tools 1. Operator Matrices - Pauli: I, X, Y, Z - Hadamard: H - Phase: P - Sqrt(X): SX - Sqrt(Z): S - Sqrt(H): SH - 4rt (Z): T - X root: Xrt(s) - H root: Hrt(s) - Rotation Matrices: Rx($\theta$), Ry($\theta$), Rz($\theta$) - U3 Matrix: U3($\theta, \phi, \lambda$) - Controlled-Not: CX 2. Common Statevectors - $|0\rangle$: zero - $|1\rangle$: one - $|+\rangle$: plus - $|-\rangle$: minus - $| \uparrow \rangle$: up - $| \downarrow \rangle$: down - Bell States: B00, B01, B10, B11 3. Lambda Methods - ndarray to list: to_list(array) - tensor: *****initial_state - matmul: *****initial_state 4. Full Methods - Calculate Hermitian Conjugate: dagger(mat) - Build CU matrix: cu_matrix(no_qubits, control, target, U, little_edian) - Find RX, RY for arbitrary U3: angles_from_state_vectors(output_statevector) 5. Visualizations - view(mat, rounding = 10) Qiskit Tools 1. Linear Algebra - Short-hand QC: q(*****regs, name=None, global_phase=0) - Multi-controlled Unitary: control_unitary(circ, unitary, *****controls, target) - Control Phase: control_phase(circ, angle, control_bit, target_bit, recip=True, pi_on=True)2. Visualizations - Draw Circuit: milk(circ) - Draw Transpiled Circuit: dtp(circ, print_details = True, visual = True, return_values = False) - Get Unitary / Statevector Function: get(circ, types = 'unitary', nice = True) - Displaying Histogram / Bloch / Counts: sim(circ, visual = 'hist') 3. Toffoli Optimizaton Specific - Unitary Checker: unitary_check(test_unitary) - Multi-Hadamard Composition: h_relief(n, no_h) Import | import numpy as np
import sympy as sp
from sympy.solvers.solveset import linsolve
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
from sympy import Matrix, init_printing
import qiskit
from qiskit import *
from qiskit.aqua.circuits import *
# Representing Data
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
from qiskit.tools.visualization import plot_histogram, plot_state_city, plot_bloch_multivector
# Monitor Job on Real Machine
from qiskit.tools.monitor import job_monitor
from functools import reduce # perform sucessive tensor product
# Calculating cost
from sklearn.metrics import mean_squared_error
# Generating random unitary matrix
from scipy.stats import unitary_group
# Measure run time
import time
# Almost Equal
from numpy.testing import assert_almost_equal as aae | Duplicate key in file '/Users/minhpham/.matplotlib/matplotlibrc' line #2.
Duplicate key in file '/Users/minhpham/.matplotlib/matplotlibrc' line #3.
| Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Linear Algebra Tools | # Matrices
I = np.array([[1, 0], [0, 1]])
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.array([[1, 0], [0, -1]])
H = 1/np.sqrt(2)*np.array([[1, 1], [1, -1]])
P = lambda theta: np.array([[1, 0], [0, np.exp(1j*theta)]])
# sqrt(X)
SX = 1/2 * np.array([[1+1j, 1-1j], [1-1j, 1+1j]])
# sqrt(Z)
S = np.array([[1, 0], [0, 1j]])
# sqrt(H)
SH = (1j/4-1/4)*np.array([[np.sqrt(2) + 2j, np.sqrt(2)], [np.sqrt(2), -np.sqrt(2)+2j]])
# 4th root of Z
T = np.array([[1, 0], [0, 1/np.sqrt(2) + 1/np.sqrt(2)*1j]])
# X power
Xp = lambda t: 1/2 * np.array([[1, 1], [1, 1]]) + np.exp(1j*np.pi*t)/(2) * np.array([[1, -1], [-1, 1]])
# H power
Hp = lambda t: np.exp(-1j*np.pi*t/2) * np.array([[np.cos(np.pi*t/2) + 1j/np.sqrt(2)* np.sin(np.pi*t/2), 1j/np.sqrt(2) * np.sin(np.pi*t/2)],
[1j/np.sqrt(2) * np.sin(np.pi*t/2), np.cos(np.pi*t/2)-1j/np.sqrt(2)* np.sin(np.pi*t/2)]])
CX = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])
# Rn Matrix Function
Rx = lambda theta: np.array([[np.cos(theta/2), -1j*np.sin(theta/2)], [-1j*np.sin(theta/2), np.cos(theta/2)]])
Ry = lambda theta: np.array([[np.cos(theta/2), -np.sin(theta/2)], [np.sin(theta/2), np.cos(theta/2)]])
Rz = lambda theta: np.array([[np.exp(-1j*theta/2), 0], [0, np.exp(1j*theta/2)]])
# U3 Matrix
U3 = lambda theta, phi, lam: np.array([[np.cos(theta/2), -np.exp(1j*lam)*np.sin(theta/2)],
[np.exp(1j*phi)*np.sin(theta/2), np.exp(1j*lam + 1j*phi)*np.cos(theta/2)]])
# Eigenvectors of Pauli Matrices
zero = np.array([[1], [0]]) # Z plus basis state
one = np.array([[0], [1]]) # Z plus basis state
plus = np.array([[1], [1]])/np.sqrt(2) # X plus basis state
minus = np.array([[1], [-1]])/np.sqrt(2) # X minus basis state
up = np.array([[1], [1j]])/np.sqrt(2) # Y plus basis state
down = np.array([[1], [-1j]])/np.sqrt(2) # Y plus basis state
# Bell States
B00 = np.array([[1], [0], [0], [1]])/np.sqrt(2) # Bell of 00
B01 = np.array([[1], [0], [0], [-1]])/np.sqrt(2) # Bell of 01
B10 = np.array([[0], [1], [1], [0]])/np.sqrt(2) # Bell of 10
B11 = np.array([[0], [-1], [1], [0]])/np.sqrt(2) # Bell of 11
# ndarray to list
to_list = lambda array: list(np.squeeze(array))
# Tensor Product of 2+ matrices/ vectors
tensor = lambda *initial_state: reduce(lambda x, y: np.kron(x, y), initial_state)
# Matrix Multiplicaton of 2+ matrices / vectors
mat_mul = lambda *initial_state: reduce(lambda x, y: np.dot(x, y), initial_state) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Calculate Hermitian Conjugate | def dagger(mat):
# Calculate Hermitian conjugate
mat_dagger = np.conj(mat.T)
# Assert Hermitian identity
aae(np.dot(mat_dagger, mat), np.identity(mat.shape[0]))
return mat_dagger | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
CU Matrix | def cu_matrix(no_qubits, control, target, U, little_edian = True):
"""
Manually build the unitary matrix for non-adjacent CX gates
Parameters:
-----------
no_qubits: int
Number of qubits in the circuit
control: int
Index of the control qubit (1st qubit is index 0)
target: int
Index of the target qubit (1st qubit is index 0)
U: ndarray
Target unitary matrix
edian: bool (True: qiskit convention)
Qubits order convention
Returns:
--------
cx_out:
Unitary matrix for CU gate
"""
left = [I]*no_qubits
right = [I]*no_qubits
left[control] = np.dot(zero, zero.T)
right[control] = np.dot(one, one.T)
right[target] = U
if little_edian:
cx_out = tensor(*reversed(left)) + tensor(*reversed(right))
else:
cx_out = tensor(*left) + tensor(*right)
# This returns a unitary in qiskit 'little eddian', to switch back, simply switch the target for control
return cx_out | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Angles from Statevector | def angles_from_statevectors(output_statevector):
"""
Calculate correct x, y rotation angles from an arbitrary output statevector
Paramters:
----------
output_statevector: ndarray
Desired output state
Returns:
--------
phi: float
Angle to rotate about the y-axis [0, 2pi)
theta: float
Angle to rotate about the x-axis [0, 2pi)
"""
# Extract the components
x, z = output_statevector.real
y, w = output_statevector.imag
# Calculate the correct angles
phi = 2*np.arctan2(z,x)[0]
theta = 2*np.arctan2(y,z)[0]
print(f'phi: {phi}')
print(f'theta: {theta}')
return phi, theta | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
View Matrix | def view(mat, rounding = 10):
display(Matrix(np.round(mat, rounding))) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Qiskit Tools Short-hand Qiskit Circuit | q = lambda *regs, name=None, global_phase=0: QuantumCircuit(*regs, name=None, global_phase=0) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Controlled Unitary | def control_unitary(circ, unitary, controls, target):
"""
Composed a multi-controlled single unitary target gate
Parameters:
-----------
circ: QuantumCircuit
Qiskit circuit of appropriate size, no less qubit than the size of the controlled gate
unitary: ndarray of (2, 2)
Unitary operator for the target qubit
controls: list
Indices of controlled qubit on the original circuit
target: int
Index of target bit
Returns:
--------
new_circ: QuantumCircuit
Composed circuit with unitary target
"""
# Get info about circuit parameters
no_controls = len(controls)
unitary_size = np.log2(len(unitary))
# Build unitary circuit
qc = QuantumCircuit(unitary_size)
qc.unitary(unitary, range(int(unitary_size)))
qc = qc.control(no_controls)
# Composed the control part in the circuit
new_circ = circ.compose(qc, (*controls, target))
return new_circ | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Controlled Phase | def control_phase(circ, angle, control_bit, target_bit, recip = True, pi_on = True):
"""
Add a controlled-phase gate
Parameters:
-----------
circ: QuantumCircuit
Inputted circuit
angle: float
Phase Angle
control_bit: int
Index of control bit
target_bit: int
Index of target bit
recip: bool (True)
Take the reciprocal of the angle
pi_on: bool (True)
Multiply pi to the angle
Returns:
--------
circ: QuantumCircuit
Circuit with built-in CP
"""
if recip:
angle = 1/angle
if pi_on:
angle *=np.pi
circ.cp(angle, control_bit, target_bit)
return circ | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Draw Circuit | def milk(circ):
return circ.draw('mpl') | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Draw Transpiled Circuit | def dtp(circ, print_details = True, nice = True, return_values = False):
"""
Draw and/or return information about the transpiled circuit
Parameters:
-----------
circ: QuantumCircuit
QuantumCircuit to br transpiled
print_details: bool (True)
Print the number of u3 and cx gates used
nice: bool (True)
Show the transpiled circuit
return_values: bool (True)
Return the number of u3 and cx gates used
Returns:
--------
no_cx: int
Number of cx gates used
no_u3: int
Number of u3 gates used
"""
# Transpile Circuit
circ = transpile(circ, basis_gates= ['u3', 'cx'], optimization_level=3)
# Count operations
gates = circ.count_ops()
# Compute cost
try:
no_u3 = gates['u3']
except:
no_u3 = 0
try:
no_cx = gates['cx']
except:
no_cx = 0
cost = no_u3 + 10*no_cx
if print_details:
# Print Circuit Details
print(f'cx: {no_cx}')
print(f'u3: {no_u3}')
print(f'Total cost: {cost}')
if nice:
return circ.draw('mpl')
if return_values:
return no_cx, no_u3 | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Get Unitary/StateVector Function | def get(circ, types = 'unitary', nice = True):
"""
This function return the statevector or the unitary of the inputted circuit
Parameters:
-----------
circ: QuantumCircuit
Inputted circuit without measurement gate
types: str ('unitary')
Get 'unitary' or 'statevector' option
nice: bool
Display the result nicely option or just return unitary/statevector as ndarray
Returns:
--------
out: ndarray
Outputted unitary of statevector
"""
if types == 'statevector':
backend = BasicAer.get_backend('statevector_simulator')
out = execute(circ, backend).result().get_statevector()
else:
backend = BasicAer.get_backend('unitary_simulator')
out = execute(circ, backend).result().get_unitary()
if nice:
display(Matrix(np.round(out, 10)))
else:
return out | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Displaying Histogram / Bloch / Counts | def sim(circ, visual = 'hist'):
"""
Displaying output of quantum circuit
Parameters:
-----------
circ: QuantumCircuit
QuantumCircuit with or without measurement gates
visual: str ('hist')
'hist' (counts on histogram) or 'bloch' (statevectors on Bloch sphere) or None (get counts only)
Returns:
--------
counts: dict
Counts of each CBS state
"""
# Simulate circuit and display counts on a histogram
if visual == 'hist':
simulator = Aer.get_backend('qasm_simulator')
results = execute(circ, simulator).result()
counts = results.get_counts(circ)
plot_histogram(counts)
return counts
# Get the statevector and display on a Bloch sphere
elif visual == 'bloch':
backend = BasicAer.get_backend('statevector_simulator')
statevector = execute(circ, backend).result().get_statevector()
get(circ)
plot_bloch_multivector(statevector)
# Just get counts
else:
simulator = Aer.get_backend('qasm_simulator')
results = execute(circ, simulator).result()
counts = results.get_counts(circ)
return counts | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Unitary Checker | def unitary_check(test_unitary, perfect = False):
"""
Check if the CnX unitary is correct
Parameters:
-----------
test_unitary: ndarray
Unitary generated by the circuit
perfect: ndarray
Account for phase difference
"""
# Get length of unitary
if not perfect:
test_unitary = np.abs(test_unitary)
size = test_unitary.shape[0]
cx_theory = np.identity(size)
# Change all the difference
cx_theory[int(size/2) - 1, size - 1] = 1
cx_theory[size - 1, int(size/2) - 1] = 1
cx_theory[int(size/2) -1, int(size/2) -1] = 0
cx_theory[size - 1, size - 1] = 0
# Assert Similarity
aae(cx_theory, test_unitary)
print('Unitary is correct') | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Task: Implementing Improved Multiple Controlled Toffoli Abstract Multiple controlled Toffoli gates are crucial in the implementation of modular exponentiation [4], like that used in Shor's algorithm. In today's practical realm of small number of qubits devices, there is a real need for efficient realization of multiple controlled Toffoli gate for 6 to 10 controls.Shende and Markov proved that the implementation of the $n$-qubit analogue of the $TOFFOLI$ requires at least $2n \ CNOT$ gates [1]. Currently, the best known upper bound is outlined by Maslov stands at $6n-12$ with the used of $\lceil \frac{n-3}{2} \rceil$ ancilla bits [2]. For implementaion without ancillae, we look at the technique outlined in Corollary 7.6 which has $\Theta(n^2)$ complexity [3]. The aboved mention technique however, still has a high implementation cost for relatively low number of controls. This is due to the high coefficient of the $n^2$ term. Note that in this notebook, $n$ qubits Toffli gates will simply be referred to as $CnX$ gate where $n$ is the number of control bits. For this project, we outline a technique for building $CnX$ gate with modulo phase shift whose unitary satisfies $UU = I$. For a few examples from $n = 2$ to $n = 15$, we provided some values to compare and contrast our circuit cost versus that of qiskit. We then postulated with high confidence the complexity of the technique to be $O(2^{\frac{n}{2}})$. Comparing this to the quadratic technique in Corollary 7.6 of [3], we found that our circuits are superior for $n = 7, 8, ..., 11$ . At the end, we offers some possible implementation cases for our technique. Motivating the General Circuit The general $CnX$ gate takes in $n+1$ qubits as inputs ($n$ controls, $1$ target). It's action on a set of qubits $\{q_i\}_{i = 0}^{n}$ is defined as followed.$$CnX(\{q_i\}_{i = 0}^{n}) = \big{(} \bigwedge_{i = 0}^{n-1} q_i \big{)} \oplus q_n$$Simply stated, the gate flips the target bit if all the controls are $1$s. For example, for $n = 2$, we have the well-known Toffoli gate | circ = q(3)
circ.ccx(0, 1, 2)
milk(circ) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
And for higher $n$, $6$ for example, the circuit would take this form. | circ = q(7)
circ.mct(list(range(6)), 6)
milk(circ) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
The cost for the Qiskit implementation of $CnX$ gate from $n = 2$ to $n = 11$ are listed above in terms of the basic operations ($CX$ and $U3$). Note that the general cost is defined as $10CX + U3$. n | CX | U3 | General Cost --- | --- | --- | --- 2 | 6 | 8 | 68 3 | 20 | 22 | 2224 | 44 | 46 | 4865 | 92 | 94 | 10146 | 188 | 190 | 20707 | 380 | 382 | 41828 | 764 | 766 | 84069 | 1532 | 1534 | 1685410 | 3068 | 3070 | 3375011 | 6140 | 6142 | 67542 As outlined in Corolllary 7.1 [3]. The number of $CX$ grows by $3\cdot 2^{n-1} - 4$, and $U3$ grows by $3\cdot 2^{n-1} - 2$. Overall, we see an $O(2^n)$ complexity of the general cost. Our technique takes advantage of the superposition identity that$$H Z H = X$$For an arbitrary $CnX$, we split the control into two groups (one controlled by $H$, and one controlled by $Z$). If we defined the number of control bits on the $H$ gates as $a$, we have the circuit $C(a)H - C(n-a)Z - C(a)H$. An example of $n = 7, a = 3$ is shown below. | circ = q(8)
circ = control_unitary(circ, H, [0, 1, 2], 7)
circ = control_unitary(circ, Z, [3, 4, 5, 6], 7)
circ = control_unitary(circ, H, [0, 1, 2], 7)
milk(circ) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
The two outer most gates are $C3H$, and the middle gate is $C4Z$. Together they create $C7X$ with a negative phase in 7 columns of the unitary. In general, the number of negative phase in the unitary has the form $2^a - 1$. Although $a$ can be varied, for each $n$, there exists a unique value of $a$ that is optimal for the respective circuit. We run and tested out all the different combination of $n$s and $a$s. And we generate the set of opimal combinations shown below. n | H-a | CX | U3 | General Cost --- | --- | --- | --- | --- 2 | 1 | 3 | 4 | 343 | 1 | 6 | 7 | 674 | 1 | 20 | 25 | 2255 | 2 | 34 | 53 | 3936 | 2 | 50 | 72 | 5727 | 3 | 70 | 101 | 8018 | 4 | 102 | 143 | 11639 | 4 | 146 | 196 | 165610 | 4 | 222 | 286 | 250611 | 5 | 310 | 395 | 3495 Implementing the General Circuit The circuit will be implemented recursively using three base cases. When $n = 1$, when have the $CX$ gate. When $n = 2$, we have the below structure. | milk(CnX(2)) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
$n = 3$ | dtp(CnX(3)) | cx: 6
u3: 7
Total cost: 67
| Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
We sketch the following for the general circuit of $CnX$ We also provide the qiskit code implementation of for the general $CnX$ below. At the end is the list of the best implementation for each CnX gate. To use, simply assign ```best[n] ``` to an object and use like a normal QuantumCircuit. Note that $n$ represents the number of controls in the desired $CnX$. CnX/CnP (Multiple-controlled Not modulo phase shift circuit) | def CnX(n, control_list = None, target = None, circ = None, theta = 1):
"""
Create a CnX modulo phase shift gate
Parameters:
-----------
n: int
Number of control bits
control_list: list
Index of control bits on inputted circuit (if any)
target: int
Index of control bits on inputted circuit (if any)
circ: QuantumCircuit
Inputted circuit to compose CnX on
theta: int
1/theta power X n-bit controlled circuit
Returns:
--------
circ: QuantumCircuit
CnX modulo phase shift gate
"""
# Build New Circuit
if circ == None:
circ = q(n+1)
control_list = list(range(n))
target = n
# Base Case
if n == 1:
circ.cx(*control_list, target)
return circ
if n==2:
circ.ch(control_list[0], target)
circ.cz(control_list[1], target)
circ.ch(control_list[0], target)
return circ
if n == 3:
circ.rcccx(*control_list, target)
return circ
# New Case
# CH
circ.ch(control_list[0], target)
# CP2
circ = control_phase(circ, theta*2, control_list[-1], target)
# C(n-2)X
circ = CnX(n-2, control_list[1:-1], control_list[-1], circ)
# -CP2
circ = control_phase(circ, -theta*2, control_list[-1], target)
# C(n-2)X
circ = CnX(n-2, control_list[1:-1], control_list[-1], circ)
# CnP
circ = CnP(n-2, control_list[1:-1], target, circ, theta*2)
# CH
circ.ch(control_list[0], target)
return circ
def CnP(n, control_list = None, target = None, circ = None, theta = 1):
"""
Create a CnP modulo phase shift gate
Parameters:
-----------
n: int
Number of control bits
control_list: list
Index of control bits on inputted circuit (if any)
target: int
Index of control bits on inputted circuit (if any)
circ: QuantumCircuit
Inputted circuit to compose CnP on
theta: int
1/theta power Z n-bit controlled circuit
Returns:
--------
circ: QuantumCircuit
CnP modulo phase shift gate
"""
# Build New Circuit
if circ == None:
circ = q(n+1)
control_list = list(range(n))
target = n
# Base Case
if n ==1:
circ = control_phase(circ, theta, control_list, target)
return circ
# New Case
# CP
circ = control_phase(circ, theta*2, control_list[-1], target)
# C(n-1)X
circ = CnX(n-1, control_list[:-1], control_list[-1], circ)
# -CP
circ = control_phase(circ, -theta*2, control_list[-1], target)
# C(n-1)X
circ = CnX(n-1, control_list[:-1], control_list[-1], circ)
# C(n-1)P
circ = CnP(n-1, control_list[:-1], target, circ, theta*2)
return circ | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
CnH / Multi-Hadamard Composition | def CnH(n, control_list = None, target = None, circ = None, theta = 1):
"""
Create a CnH modulo phase shift gate
Parameters:
-----------
n: int
Number of control bits
control_list: list
Index of control bits on inputted circuit (if any)
target: int
Index of control bits on inputted circuit (if any)
circ: QuantumCircuit
Inputted circuit to compose CnH on
theta: int
1/theta power H n-bit controlled circuit
Returns:
--------
circ: QuantumCircuit
CnH modulo phase shift gate
"""
# Build New Circuit
if circ == None:
circ = q(n+1)
control_list = list(range(n))
target = n
# Base Case
if n ==1 and theta ==1:
circ.ch(control_list, target)
return circ
if n ==1:
circ.unitary(cu_matrix(2, 0, 1, Hp(1/theta)), [control_list, target])
return circ
# New Case
# CH
circ.unitary(cu_matrix(2, 0, 1, Hp(1/(theta*2))), [control_list[-1], target])
# C(n-1)X
circ = CnX(n-1, control_list[:-1], control_list[-1], circ)
# CH
circ.unitary(cu_matrix(2, 0, 1, Hp(-1/(theta*2))), [control_list[-1], target])
# C(n-1)X
circ = CnX(n-1, control_list[:-1], control_list[-1], circ)
# C(n-1)P
circ = CnH(n-1, control_list[:-1], target, circ, theta*2)
return circ
def h_relief(n, no_h, return_circ = False):
"""
Implementing the general CaH-C(n-a)Z-CaH architecture
Paramters:
----------
n: int
Total number of control bits
no_h: int
Total number of control bits for the CnH gate
return_circ: bool
Return circuit as a QuantumCircuit object
Returns:
--------
circ: QuantumCircuit
Circuit with CnX and Hadamard Relief
"""
# n is the number of control qubit
# no_h is the number of control qubit on the side hadamard
circ = q(n+1)
circ= CnH(no_h, list(range(no_h)), n, circ)
circ = CnP(n-no_h, list(range(no_h, n)), n, circ)
circ= CnH(no_h, list(range(no_h)), n, circ)
'''# Test for accuracy
test = get(circ, nice = False)
unitary_check(test)'''
if return_circ:
return circ
dtp(circ, nice = False)
### List of opimal combinations
best = [None, None, CnX(2), CnX(3), CnX(4), h_relief(5, 2, return_circ = True), h_relief(6, 2, return_circ = True),
h_relief(7, 3, return_circ = True), h_relief(8, 4, return_circ = True), h_relief(9, 4, return_circ = True),
h_relief(10, 4, return_circ = True), h_relief(11, 5, return_circ = True), h_relief(12, 6, return_circ = True)] | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Postulate for Complexity of the General Cost We have two lists below showing the number of $U3$ and $CX$ used for the qiskit technique and our technique | ## Qiskit
cx_q = np.array([6, 20, 44, 92, 188, 380, 764, 1532, 3068, 6140])
u3_q = np.array([8, 22, 46, 94, 190, 382, 766, 1534, 3070, 6142])
## Our
cx_o = np.array([3, 6, 20, 34, 50, 70, 102, 146, 222, 310])
u3_o = np.array([4, 7, 25, 53, 72, 101, 143, 196, 286, 395]) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
We find the common ratios by taking $a_{n+1}/a_n$, and taking the average of these ratio when $n > 3$ to mitigate the impact of the additive factor. | ## Qiskit
rat_1 = cx_q[1:] / cx_q[:-1]
rat_1 = np.mean(rat_1[3:])
rat_2 = u3_q[1:] / u3_q[:-1]
rat_2 = np.mean(rat_2[3:])
## Our
rat_3 = cx_o[1:] / cx_o[:-1]
rat_3 = np.mean(rat_3[3:])
rat_4 = u3_o[1:] / u3_o[:-1]
rat_4 = np.mean(rat_4[3:])
rat_1, rat_2, rat_3, rat_4 | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
We see that the geometric ratio of our technique is superior to that of qiskit. In base $2$, we can roughly see the following complexity.$$CX \approx O(1.446^n) \approx O(2^{\frac{n}{2}})$$$$U3 \approx O(1.380^n) \approx O(2^{\frac{n}{2}})$$ Compare and Contrast with the $O(n^2)$ technique in Corollary 7.6 of [3] Lemma 7.5 shows an example of $C8X$ built using 2 $C7X$ and 1 $C7V$. For our purposes, we can assume that the cost of $C7V$ is equal to that of $C7X$. In actuality, the cost of any CnU gate is much greater than that of $CnX$ gates so therefore this assumption gives us a lower bound of the cost of the circuit.Previous lemmas and corollaries show that these can gates can be broken down further into smaller $C2X$ and $C3X$ gates.$$\begin{align}C5X &= 12 \ C2X = 12\cdot34 = 408 \\ C7X &= 2 \ C5X + 2 \ C3X = 2\cdot408 + 2\cdot67 = 950 \\ C8X &= 3 \ C7X \end{align}$$If we let use our implementation of $C2X$ and $C3X$. Then we would have the general cost of $C8X = 2850$. However, as our circuit allow for the use of phase differences, we would also allow this circuit to be used to built bigger examples like shown below. | circ = q(10)
circ = control_unitary(circ, H, [0, 1], 9)
circ.h(9)
circ.mct([2, 3, 4, 5, 6, 7, 8], 9)
circ.h(9)
circ = control_unitary(circ, H, [0, 1], 9)
milk(circ) | _____no_output_____ | Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
The $3$ middle gates will have the effect of $C8Z$, and the two gate outside are $C2Z$. This will leads to $C10X$ with phase difference. Now we made one last modification to the implementation of Lemma 7.5. If we look back to the table from before, we can see that our implementation of $C7X$ has a lower than $950$. Because the phase difference does not affect the control operation, we can replace the paper's $C7X$ with ours. | print(1)
dtp(CnH(1), nice = False)
print('\n')
print(2)
dtp(CnH(2), nice = False)
print('\n')
print(3)
dtp(CnH(3), nice = False) | 1
cx: 1
u3: 2
Total cost: 12
2
cx: 8
u3: 16
Total cost: 96
3
cx: 18
u3: 31
Total cost: 211
| Apache-2.0 | frozenYoghourt/Qbraid - Implementing Improved Multiple Controlled Toffoli.ipynb | mehilagarwal/qchack |
Math Some extra math functions. | %nbdev_export
def smooth( newVal, oldVal, weight) :
"An exponential smoothing function. The weight is the smoothing factor applied to the old value."
return newVal * (1 - weight) + oldVal * weight;
smooth(2, 10, 0.9)
assert smooth(2, 10, 0.9)==9.2
#hide
from nbdev import *
notebook2script() | Converted 00_core.ipynb.
Converted 01_rmath.ipynb.
Converted 02_functions.ipynb.
Converted 03_nodes.ipynb.
Converted 04_hierarchy.ipynb.
Converted index.ipynb.
| Apache-2.0 | nbs/.ipynb_checkpoints/01_rmath-checkpoint.ipynb | perceptualrobots/pct |
Metacartel VenturesFirst block: 9484668 (Feb-15-2020 01:32:52 AM +UTC)https://etherscan.io/block/9484668Other blocks:10884668 (Sep-18-2020 06:57:11 AM +UTC)Recent block (for reference): 13316507 (Sep-28-2021 08:58:06 PM +UTC)summoner: 0x8c8b237bea3c23317d08b73d7137e90cafdf68e6 | # Approximate seconds per block
sec_per_block = (datetime(2021, 9, 28, 8, 58, 6) - datetime(2020, 2, 15, 1, 32, 52)).seconds / (13316507 - 9484668)
print("approx. this many blocks per days:", sec_per_block * 86400)
# 86400 seconds per day
# >>> from datetime import datetime
# >>> a = datetime(2011,11,24,0,0,0)
# >>> b = datetime(2011,11,17,23,59,59)
# >>> a-b
# datetime.timedelta(6, 1)
# >>> (a-b).days
# 6
9484668 + 602
# Load data
with open("./data/10884668-results.json", "r") as f:
results_09182020 = json.load(f)
f.close()
with open("./data/13316507-results.json", "r") as f:
results_09282021 = json.load(f)
f.close()
df_09182020_members = pd.DataFrame.from_dict(results_09182020["data"]["moloches"][0]["members"])
df_09182020_proposals = pd.DataFrame.from_dict(results_09182020["data"]["moloches"][0]["proposals"])
df_09182020_members["id"][0].split('-')[2]
df_09182020_members["id"] = df_09182020_members.apply(lambda row: row["id"].split('-')[2], axis=1)
df_09182020_members
print("Number of members:", df_09182020_members["id"].nunique())
df_09182020_proposals
cols_proposal = ["applicant", "details", "didPass", "lootRequested", "sharesRequested", "aborted", "cancelled", "createdAt", "yesShares", "yesVotes", "noShares", "noVotes", "maxTotalSharesAndLootAtYesVote"]
df_09182020_proposals[cols_proposal]
# df_09182020_proposals.columns
df_09182020_members.columns
df_09182020_member_proposals = pd.merge(df_09182020_members, df_09182020_proposals[cols_proposal], how="left", left_on=["id"], right_on = ["applicant"]).sort_values(["createdAt_y", "applicant"])
df_09182020_member_proposals.head()
df_09182020_member_proposals[["id", "applicant"]].groupby("id").count() | _____no_output_____ | MIT | MetacartelVentures/MetacartelVentures DAO Analysis.ipynb | Xqua/dao-research |
Project 1: Trading with Momentum InstructionsEach problem consists of a function to implement and instructions on how to implement the function. The parts of the function that need to be implemented are marked with a ` TODO` comment. After implementing the function, run the cell to test it against the unit tests we've provided. For each problem, we provide one or more unit tests from our `project_tests` package. These unit tests won't tell you if your answer is correct, but will warn you of any major errors. Your code will be checked for the correct solution when you submit it to Udacity. PackagesWhen you implement the functions, you'll only need to you use the packages you've used in the classroom, like [Pandas](https://pandas.pydata.org/) and [Numpy](http://www.numpy.org/). These packages will be imported for you. We recommend you don't add any import statements, otherwise the grader might not be able to run your code.The other packages that we're importing are `helper`, `project_helper`, and `project_tests`. These are custom packages built to help you solve the problems. The `helper` and `project_helper` module contains utility functions and graph functions. The `project_tests` contains the unit tests for all the problems. Install Packages | import sys
!{sys.executable} -m pip install -r requirements.txt | Requirement already satisfied: colour==0.1.5 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 1)) (0.1.5)
Collecting cvxpy==1.0.3 (from -r requirements.txt (line 2))
[?25l Downloading https://files.pythonhosted.org/packages/a1/59/2613468ffbbe3a818934d06b81b9f4877fe054afbf4f99d2f43f398a0b34/cvxpy-1.0.3.tar.gz (880kB)
[K 100% |ββββββββββββββββββββββββββββββββ| 880kB 8.6MB/s eta 0:00:01
[?25hRequirement already satisfied: cycler==0.10.0 in /opt/conda/lib/python3.6/site-packages/cycler-0.10.0-py3.6.egg (from -r requirements.txt (line 3)) (0.10.0)
Collecting numpy==1.13.3 (from -r requirements.txt (line 4))
[?25l Downloading https://files.pythonhosted.org/packages/57/a7/e3e6bd9d595125e1abbe162e323fd2d06f6f6683185294b79cd2cdb190d5/numpy-1.13.3-cp36-cp36m-manylinux1_x86_64.whl (17.0MB)
[K 100% |ββββββββββββββββββββββββββββββββ| 17.0MB 2.2MB/s eta 0:00:01 35% |ββββββββββββ | 5.9MB 32.4MB/s eta 0:00:01 78% |ββββββββββββββββββββββββββ | 13.3MB 25.2MB/s eta 0:00:01
[?25hCollecting pandas==0.21.1 (from -r requirements.txt (line 5))
[?25l Downloading https://files.pythonhosted.org/packages/3a/e1/6c514df670b887c77838ab856f57783c07e8760f2e3d5939203a39735e0e/pandas-0.21.1-cp36-cp36m-manylinux1_x86_64.whl (26.2MB)
[K 100% |ββββββββββββββββββββββββββββββββ| 26.2MB 1.6MB/s eta 0:00:01 10% |ββββ | 2.8MB 32.4MB/s eta 0:00:01 32% |βββββββββββ | 8.5MB 29.6MB/s eta 0:00:01 53% |ββββββββββββββββββ | 14.1MB 28.9MB/s eta 0:00:01 69% |βββββββββββββββββββββββ | 18.1MB 27.8MB/s eta 0:00:01 84% |βββββββββββββββββββββββββββ | 22.1MB 25.6MB/s eta 0:00:01
[?25hCollecting plotly==2.2.3 (from -r requirements.txt (line 6))
[?25l Downloading https://files.pythonhosted.org/packages/99/a6/8214b6564bf4ace9bec8a26e7f89832792be582c042c47c912d3201328a0/plotly-2.2.3.tar.gz (1.1MB)
[K 100% |ββββββββββββββββββββββββββββββββ| 1.1MB 16.2MB/s ta 0:00:01
[?25hRequirement already satisfied: pyparsing==2.2.0 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 7)) (2.2.0)
Requirement already satisfied: python-dateutil==2.6.1 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 8)) (2.6.1)
Requirement already satisfied: pytz==2017.3 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 9)) (2017.3)
Requirement already satisfied: requests==2.18.4 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 10)) (2.18.4)
Collecting scipy==1.0.0 (from -r requirements.txt (line 11))
[?25l Downloading https://files.pythonhosted.org/packages/d8/5e/caa01ba7be11600b6a9d39265440d7b3be3d69206da887c42bef049521f2/scipy-1.0.0-cp36-cp36m-manylinux1_x86_64.whl (50.0MB)
[K 100% |ββββββββββββββββββββββββββββββββ| 50.0MB 704kB/s eta 0:00:01 7% |βββ | 3.7MB 25.1MB/s eta 0:00:02 9% |βββ | 4.8MB 21.7MB/s eta 0:00:03 14% |βββββ | 7.1MB 24.1MB/s eta 0:00:02 24% |ββββββββ | 12.3MB 23.3MB/s eta 0:00:02 30% |ββββββββββ | 15.4MB 23.1MB/s eta 0:00:02 37% |ββββββββββββ | 18.7MB 21.1MB/s eta 0:00:02 39% |βββββββββββββ | 19.7MB 22.3MB/s eta 0:00:02 41% |ββββββββββββββ | 20.9MB 24.5MB/s eta 0:00:02 43% |ββββββββββββββ | 21.9MB 21.0MB/s eta 0:00:02 53% |βββββββββββββββββ | 26.5MB 23.9MB/s eta 0:00:01 57% |βββββββββββββββββββ | 28.6MB 22.2MB/s eta 0:00:01 59% |βββββββββββββββββββ | 29.8MB 35.9MB/s eta 0:00:01 63% |βββββββββββββββββββββ | 31.9MB 21.3MB/s eta 0:00:01 68% |ββββββββββββββββββββββ | 34.1MB 22.0MB/s eta 0:00:01 70% |βββββββββββββββββββββββ | 35.4MB 24.3MB/s eta 0:00:01 75% |ββββββββββββββββββββββββ | 37.6MB 26.2MB/s eta 0:00:01 77% |βββββββββββββββββββββββββ | 38.8MB 25.6MB/s eta 0:00:01 86% |ββββββββββββββββββββββββββββ | 43.2MB 22.5MB/s eta 0:00:01 88% |βββββββββββββββββββββββββββββ | 44.4MB 20.1MB/s eta 0:00:01 91% |ββββββββββββββββββββββββββββββ | 45.7MB 24.1MB/s eta 0:00:01 98% |ββββββββββββββββββββββββββββββββ| 49.2MB 26.7MB/s eta 0:00:01
[?25hRequirement already satisfied: scikit-learn==0.19.1 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 12)) (0.19.1)
Requirement already satisfied: six==1.11.0 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 13)) (1.11.0)
Collecting tqdm==4.19.5 (from -r requirements.txt (line 14))
[?25l Downloading https://files.pythonhosted.org/packages/71/3c/341b4fa23cb3abc335207dba057c790f3bb329f6757e1fcd5d347bcf8308/tqdm-4.19.5-py2.py3-none-any.whl (51kB)
[K 100% |ββββββββββββββββββββββββββββββββ| 61kB 7.6MB/s ta 0:00:01
[?25hCollecting osqp (from cvxpy==1.0.3->-r requirements.txt (line 2))
[?25l Downloading https://files.pythonhosted.org/packages/6c/59/2b80e881be227eecef3f2b257339d182167b55d22a1315ff4303ddcfd42f/osqp-0.6.1-cp36-cp36m-manylinux1_x86_64.whl (208kB)
[K 100% |ββββββββββββββββββββββββββββββββ| 215kB 16.9MB/s ta 0:00:01
[?25hCollecting ecos>=2 (from cvxpy==1.0.3->-r requirements.txt (line 2))
[?25l Downloading https://files.pythonhosted.org/packages/55/ed/d131ff51f3a8f73420eb1191345eb49f269f23cadef515172e356018cde3/ecos-2.0.7.post1-cp36-cp36m-manylinux1_x86_64.whl (147kB)
[K 100% |ββββββββββββββββββββββββββββββββ| 153kB 15.2MB/s ta 0:00:01
[?25hCollecting scs>=1.1.3 (from cvxpy==1.0.3->-r requirements.txt (line 2))
[?25l Downloading https://files.pythonhosted.org/packages/1a/72/33be87cce255d4e9dbbfef547e9fd6ec7ee94d0d0910bb2b13badea3fbbe/scs-2.1.2.tar.gz (3.5MB)
[K 100% |ββββββββββββββββββββββββββββββββ| 3.6MB 9.7MB/s eta 0:00:01 43% |ββββββββββββββ | 1.5MB 22.3MB/s eta 0:00:01
[?25hCollecting multiprocess (from cvxpy==1.0.3->-r requirements.txt (line 2))
[?25l Downloading https://files.pythonhosted.org/packages/58/17/5151b6ac2ac9b6276d46c33369ff814b0901872b2a0871771252f02e9192/multiprocess-0.70.9.tar.gz (1.6MB)
[K 100% |ββββββββββββββββββββββββββββββββ| 1.6MB 8.1MB/s eta 0:00:01 98% |ββββββββββββββββββββββββββββββββ| 1.5MB 28.1MB/s eta 0:00:01
[?25hRequirement already satisfied: fastcache in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (1.0.2)
Requirement already satisfied: toolz in /opt/conda/lib/python3.6/site-packages (from cvxpy==1.0.3->-r requirements.txt (line 2)) (0.8.2)
Requirement already satisfied: decorator>=4.0.6 in /opt/conda/lib/python3.6/site-packages (from plotly==2.2.3->-r requirements.txt (line 6)) (4.0.11)
Requirement already satisfied: nbformat>=4.2 in /opt/conda/lib/python3.6/site-packages (from plotly==2.2.3->-r requirements.txt (line 6)) (4.4.0)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (3.0.4)
Requirement already satisfied: idna<2.7,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (2.6)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (1.22)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests==2.18.4->-r requirements.txt (line 10)) (2019.11.28)
Requirement already satisfied: future in /opt/conda/lib/python3.6/site-packages (from osqp->cvxpy==1.0.3->-r requirements.txt (line 2)) (0.16.0)
Collecting dill>=0.3.1 (from multiprocess->cvxpy==1.0.3->-r requirements.txt (line 2))
[?25l Downloading https://files.pythonhosted.org/packages/c7/11/345f3173809cea7f1a193bfbf02403fff250a3360e0e118a1630985e547d/dill-0.3.1.1.tar.gz (151kB)
[K 100% |ββββββββββββββββββββββββββββββββ| 153kB 16.7MB/s ta 0:00:01
[?25hRequirement already satisfied: ipython-genutils in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2->plotly==2.2.3->-r requirements.txt (line 6)) (0.2.0)
Requirement already satisfied: traitlets>=4.1 in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2->plotly==2.2.3->-r requirements.txt (line 6)) (4.3.2)
Requirement already satisfied: jupyter-core in /opt/conda/lib/python3.6/site-packages (from nbformat>=4.2->plotly==2.2.3->-r requirements.txt (line 6)) (4.4.0)
| Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Load Packages | import pandas as pd
import numpy as np
import helper
import project_helper
import project_tests | _____no_output_____ | Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Market Data Load DataThe data we use for most of the projects is end of day data. This contains data for many stocks, but we'll be looking at stocks in the S&P 500. We also made things a little easier to run by narrowing down our range of time period instead of using all of the data. | df = pd.read_csv('../../data/project_1/eod-quotemedia.csv', parse_dates=['date'], index_col=False)
close = df.reset_index().pivot(index='date', columns='ticker', values='adj_close')
print('Loaded Data') | Loaded Data
| Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
View DataRun the cell below to see what the data looks like for `close`. | project_helper.print_dataframe(close) | _____no_output_____ | Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Stock ExampleLet's see what a single stock looks like from the closing prices. For this example and future display examples in this project, we'll use Apple's stock (AAPL). If we tried to graph all the stocks, it would be too much information. | apple_ticker = 'AAPL'
project_helper.plot_stock(close[apple_ticker], '{} Stock'.format(apple_ticker)) | _____no_output_____ | Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Resample Adjusted PricesThe trading signal you'll develop in this project does not need to be based on daily prices, for instance, you can use month-end prices to perform trading once a month. To do this, you must first resample the daily adjusted closing prices into monthly buckets, and select the last observation of each month.Implement the `resample_prices` to resample `close_prices` at the sampling frequency of `freq`. | def resample_prices(close_prices, freq='M'):
"""
Resample close prices for each ticker at specified frequency.
Parameters
----------
close_prices : DataFrame
Close prices for each ticker and date
freq : str
What frequency to sample at
For valid freq choices, see http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
Returns
-------
prices_resampled : DataFrame
Resampled prices for each ticker and date
"""
# TODO: Implement Function
# print(close_prices)
prices_resampled = close_prices.resample(freq).last()
# print(prices_resampled)
return prices_resampled
project_tests.test_resample_prices(resample_prices) | Tests Passed
| Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
View DataLet's apply this function to `close` and view the results. | monthly_close = resample_prices(close)
project_helper.plot_resampled_prices(
monthly_close.loc[:, apple_ticker],
close.loc[:, apple_ticker],
'{} Stock - Close Vs Monthly Close'.format(apple_ticker)) | _____no_output_____ | Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Compute Log ReturnsCompute log returns ($R_t$) from prices ($P_t$) as your primary momentum indicator:$$R_t = log_e(P_t) - log_e(P_{t-1})$$Implement the `compute_log_returns` function below, such that it accepts a dataframe (like one returned by `resample_prices`), and produces a similar dataframe of log returns. Use Numpy's [log function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html) to help you calculate the log returns. | def compute_log_returns(prices):
"""
Compute log returns for each ticker.
Parameters
----------
prices : DataFrame
Prices for each ticker and date
Returns
-------
log_returns : DataFrame
Log returns for each ticker and date
"""
# TODO: Implement Function
log_returns = np.log(prices) - np.log(prices.shift(1))
return log_returns
project_tests.test_compute_log_returns(compute_log_returns) | Tests Passed
| Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
View DataUsing the same data returned from `resample_prices`, we'll generate the log returns. | monthly_close_returns = compute_log_returns(monthly_close)
project_helper.plot_returns(
monthly_close_returns.loc[:, apple_ticker],
'Log Returns of {} Stock (Monthly)'.format(apple_ticker)) | _____no_output_____ | Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Shift ReturnsImplement the `shift_returns` function to shift the log returns to the previous or future returns in the time series. For example, the parameter `shift_n` is 2 and `returns` is the following:``` Returns A B C D2013-07-08 0.015 0.082 0.096 0.020 ...2013-07-09 0.037 0.095 0.027 0.063 ...2013-07-10 0.094 0.001 0.093 0.019 ...2013-07-11 0.092 0.057 0.069 0.087 ...... ... ... ... ...```the output of the `shift_returns` function would be:``` Shift Returns A B C D2013-07-08 NaN NaN NaN NaN ...2013-07-09 NaN NaN NaN NaN ...2013-07-10 0.015 0.082 0.096 0.020 ...2013-07-11 0.037 0.095 0.027 0.063 ...... ... ... ... ...```Using the same `returns` data as above, the `shift_returns` function should generate the following with `shift_n` as -2:``` Shift Returns A B C D2013-07-08 0.094 0.001 0.093 0.019 ...2013-07-09 0.092 0.057 0.069 0.087 ...... ... ... ... ... ...... ... ... ... ... ...... NaN NaN NaN NaN ...... NaN NaN NaN NaN ...```_Note: The "..." represents data points we're not showing._ | def shift_returns(returns, shift_n):
"""
Generate shifted returns
Parameters
----------
returns : DataFrame
Returns for each ticker and date
shift_n : int
Number of periods to move, can be positive or negative
Returns
-------
shifted_returns : DataFrame
Shifted returns for each ticker and date
"""
# TODO: Implement Function
return returns.shift(shift_n)
project_tests.test_shift_returns(shift_returns) | Tests Passed
| Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
View DataLet's get the previous month's and next month's returns. | monthly_close_returns
prev_returns = shift_returns(monthly_close_returns, 1)
lookahead_returns = shift_returns(monthly_close_returns, -1)
project_helper.plot_shifted_returns(
prev_returns.loc[:, apple_ticker],
monthly_close_returns.loc[:, apple_ticker],
'Previous Returns of {} Stock'.format(apple_ticker))
project_helper.plot_shifted_returns(
lookahead_returns.loc[:, apple_ticker],
monthly_close_returns.loc[:, apple_ticker],
'Lookahead Returns of {} Stock'.format(apple_ticker)) | _____no_output_____ | Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Generate Trading SignalA trading signal is a sequence of trading actions, or results that can be used to take trading actions. A common form is to produce a "long" and "short" portfolio of stocks on each date (e.g. end of each month, or whatever frequency you desire to trade at). This signal can be interpreted as rebalancing your portfolio on each of those dates, entering long ("buy") and short ("sell") positions as indicated.Here's a strategy that we will try:> For each month-end observation period, rank the stocks by _previous_ returns, from the highest to the lowest. Select the top performing stocks for the long portfolio, and the bottom performing stocks for the short portfolio.Implement the `get_top_n` function to get the top performing stock for each month. Get the top performing stocks from `prev_returns` by assigning them a value of 1. For all other stocks, give them a value of 0. For example, using the following `prev_returns`:``` Previous Returns A B C D E F G2013-07-08 0.015 0.082 0.096 0.020 0.075 0.043 0.0742013-07-09 0.037 0.095 0.027 0.063 0.024 0.086 0.025... ... ... ... ... ... ... ...```The function `get_top_n` with `top_n` set to 3 should return the following:``` Previous Returns A B C D E F G2013-07-08 0 1 1 0 1 0 02013-07-09 0 1 0 1 0 1 0... ... ... ... ... ... ... ...```*Note: You may have to use Panda's [`DataFrame.iterrows`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.iterrows.html) with [`Series.nlargest`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.Series.nlargest.html) in order to implement the function. This is one of those cases where creating a vecorization solution is too difficult.* | def get_top_n(prev_returns, top_n):
"""
Select the top performing stocks
Parameters
----------
prev_returns : DataFrame
Previous shifted returns for each ticker and date
top_n : int
The number of top performing stocks to get
Returns
-------
top_stocks : DataFrame
Top stocks for each ticker and date marked with a 1
"""
# TODO: Implement Function
top_stocks = pd.DataFrame(0,index=prev_returns.index,columns=prev_returns.columns)
for date,row in prev_returns.iterrows():
top_idx = row.nlargest(top_n).index
top_stocks.loc[date,top_idx]=1
return top_stocks
project_tests.test_get_top_n(get_top_n) | Tests Passed
| Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
View DataWe want to get the best performing and worst performing stocks. To get the best performing stocks, we'll use the `get_top_n` function. To get the worst performing stocks, we'll also use the `get_top_n` function. However, we pass in `-1*prev_returns` instead of just `prev_returns`. Multiplying by negative one will flip all the positive returns to negative and negative returns to positive. Thus, it will return the worst performing stocks. | top_bottom_n = 50
df_long = get_top_n(prev_returns, top_bottom_n)
df_short = get_top_n(-1*prev_returns, top_bottom_n)
project_helper.print_top(df_long, 'Longed Stocks')
project_helper.print_top(df_short, 'Shorted Stocks') | 10 Most Longed Stocks:
INCY, AMD, AVGO, NFX, SWKS, NFLX, ILMN, UAL, NVDA, MU
10 Most Shorted Stocks:
RRC, FCX, CHK, MRO, GPS, WYNN, DVN, FTI, SPLS, TRIP
| Apache-2.0 | P1_Trading_with_Momentum/project_notebook.ipynb | hemang-75/AI_for_Trading |
Subsets and Splits