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
Training Results Reconnect your Colab instanceMost remote training jobs are long running, if you are using Colab it may time out before the training results are available. In that case rerun the following sections to reconnect and configure your Colab instance to access the training results. Run the following sections in order:1. Import required modules2. Project Configurations3. Authenticating the notebook to use your Google Cloud Project Load TensorboardWhile the training is in progress you can use Tensorboard to view the results. Note the results will show only after your training has started. This may take a few minutes.
%load_ext tensorboard %tensorboard --logdir $TENSORBOARD_LOGS_DIR
_____no_output_____
Apache-2.0
g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb
anukaal/cloud
You can access the training assets as follows. Note the results will show only after your tuning job has completed at least once trial. This may take a few minutes.
if not tfc.remote(): tuner.results_summary(1) best_model = tuner.get_best_models(1)[0] best_hyperparameters = tuner.get_best_hyperparameters(1)[0] # References to best trial assets best_trial_id = tuner.oracle.get_best_trials(1)[0].trial_id best_trial_dir = tuner.get_trial_dir(best_trial_id)
_____no_output_____
Apache-2.0
g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb
anukaal/cloud
Shearlab decomposition benchmarks Some benchmarks comparing the performance of pure julia, python/julia and python implementation.
# Importing julia import odl import sys sys.path.append('../') import shearlab_operator import pyshearlab import matplotlib.pyplot as plt %matplotlib inline from numpy import ceil from odl.contrib.shearlab import shearlab_operator # Calling julia j = shearlab_operator.load_julia_with_Shearlab()
_____no_output_____
MIT
benchmarks/Benchmarks_ODL.ipynb
SimonRuetz/Shearlab.jl
Defining the parameters
n = 512 m = n gpu = 0 square = 0 name = './lena.jpg'; nScales = 4; shearLevels = [float(ceil(i/2)) for i in range(1,nScales+1)] scalingFilter = 'Shearlab.filt_gen("scaling_shearlet")' directionalFilter = 'Shearlab.filt_gen("directional_shearlet")' waveletFilter = 'Shearlab.mirror(scalingFilter)' scalingFilter2 = 'scalingFilter' full = 0; # Pure Julia j.eval('X = Shearlab.load_image(name, n);'); # Read Data j.eval('n = 512;') # The path of the image j.eval('name = "./lena.jpg";'); data = shearlab_operator.load_image(name,n); sizeX = data.shape[0] sizeY = data.shape[1] rows = sizeX cols = sizeY X = data;
_____no_output_____
MIT
benchmarks/Benchmarks_ODL.ipynb
SimonRuetz/Shearlab.jl
** Shearlet System generation **
# Pure julia with odl.util.Timer('Shearlet System Generation julia'): j.eval('shearletSystem = Shearlab.getshearletsystem2D(n,n,4)'); # Python/Julia with odl.util.Timer('Shearlet System Generation python/julia'): shearletSystem_jl = shearlab_operator.getshearletsystem2D(rows,cols,nScales,shearLevels,full,directionalFilter,scalingFilter); # pyShearlab with odl.util.Timer('Shearlet System Generation python'): shearletSystem_py = pyshearlab.SLgetShearletSystem2D(0,rows, cols, nScales)
Shearlet System Generation python : 49.179
MIT
benchmarks/Benchmarks_ODL.ipynb
SimonRuetz/Shearlab.jl
** Coefficients computation **
# Pure Julia with odl.util.Timer('Shearlet Coefficients Computation julia'): j.eval('coeffs = Shearlab.SLsheardec2D(X,shearletSystem);'); # Julia/Python with odl.util.Timer('Shearlet Coefficients Computation python/julia'): coeffs_jl = shearlab_operator.sheardec2D(X,shearletSystem_jl) # pyShearlab with odl.util.Timer('Shearlet Coefficients Computation python'): coeffs_py = pyshearlab.SLsheardec2D(X, shearletSystem_py)
Shearlet Coefficients Computation python : 1.333
MIT
benchmarks/Benchmarks_ODL.ipynb
SimonRuetz/Shearlab.jl
** Reconstruction **
# Pure Julia with odl.util.Timer('Shearlet Reconstructon julia'): j.eval('Xrec=Shearlab.SLshearrec2D(coeffs,shearletSystem);'); # Julia/Python with odl.util.Timer('Shearlet Reconstructon python/julia'): Xrec_jl = shearlab_operator.shearrec2D(coeffs_jl,shearletSystem_jl); # pyShearlab with odl.util.Timer('Shearlet Reconstructon python'): Xrec_py = pyshearlab.SLshearrec2D(coeffs_py, shearletSystem_py)
Shearlet Reconstructon python : 1.136
MIT
benchmarks/Benchmarks_ODL.ipynb
SimonRuetz/Shearlab.jl
Credit Risk Resampling Techniques
import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd from pathlib import Path from collections import Counter
_____no_output_____
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
Read the CSV into DataFrame
# Load the data file_path = Path('Resources/lending_data.csv') lendingdata = pd.read_csv(file_path) lendingdata.head()
_____no_output_____
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
Split the Data into Training and Testing
# Create our features X = lendingdata.copy() X.drop(columns=["loan_status", 'homeowner'], axis=1, inplace=True) X.head() # Create our target y = lendingdata['loan_status'] X.describe() # Check the balance of our target values y.value_counts() # Create X_train, X_test, y_train, y_test from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
_____no_output_____
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
Data Pre-ProcessingScale the training and testing data using the `StandardScaler` from `sklearn`. Remember that when scaling the data, you only scale the features data (`X_train` and `X_testing`).
# Create the StandardScaler instance from sklearn.preprocessing import StandardScaler scaler = StandardScaler() # Fit the Standard Scaler with the training data # When fitting scaling functions, only train on the training dataset X_scaler = scaler.fit(X_train) # Scale the training and testing data X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test)
_____no_output_____
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
Simple Logistic Regression
from sklearn.linear_model import LogisticRegression model = LogisticRegression(solver='lbfgs', random_state=1) model.fit(X_train, y_train) # Calculated the balanced accuracy score from sklearn.metrics import balanced_accuracy_score y_pred = model.predict(X_test) balanced_accuracy_score(y_test, y_pred) # Display the confusion matrix from sklearn.metrics import confusion_matrix confusion_matrix(y_test, y_pred) # Print the imbalanced classification report from imblearn.metrics import classification_report_imbalanced print(classification_report_imbalanced(y_test, y_pred))
pre rec spe f1 geo iba sup high_risk 0.85 0.91 0.99 0.88 0.95 0.90 619 low_risk 1.00 0.99 0.91 1.00 0.95 0.91 18765 avg / total 0.99 0.99 0.91 0.99 0.95 0.91 19384
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
OversamplingIn this section, you will compare two oversampling algorithms to determine which algorithm results in the best performance. You will oversample the data using the naive random oversampling algorithm and the SMOTE algorithm. For each algorithm, be sure to complete the folliowing steps:1. View the count of the target classes using `Counter` from the collections library. 3. Use the resampled data to train a logistic regression model.3. Calculate the balanced accuracy score from sklearn.metrics.4. Print the confusion matrix from sklearn.metrics.5. Generate a classication report using the `imbalanced_classification_report` from imbalanced-learn.Note: Use a random state of 1 for each sampling algorithm to ensure consistency between tests Naive Random Oversampling
# Resample the training data with the RandomOversampler # View the count of target classes with Counter from imblearn.over_sampling import RandomOverSampler ros = RandomOverSampler(random_state=1) X_resampled, y_resampled = ros.fit_resample(X_train, y_train) Counter(y_resampled) # Train the Logistic Regression model using the resampled data from sklearn.linear_model import LogisticRegression nromodel = LogisticRegression(solver='lbfgs', random_state=1) nromodel.fit(X_resampled, y_resampled) # Calculated the balanced accuracy score from sklearn.metrics import balanced_accuracy_score balanced_accuracy_score(y_test, y_pred) # Display the confusion matrix from sklearn.metrics import confusion_matrix y_pred = nromodel.predict(X_test) confusion_matrix(y_test, y_pred) # Print the imbalanced classification report from imblearn.metrics import classification_report_imbalanced print(classification_report_imbalanced(y_test, y_pred))
pre rec spe f1 geo iba sup high_risk 0.84 0.99 0.99 0.91 0.99 0.99 619 low_risk 1.00 0.99 0.99 1.00 0.99 0.99 18765 avg / total 0.99 0.99 0.99 0.99 0.99 0.99 19384
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
SMOTE Oversampling
# Resample the training data with SMOTE # View the count of target classes with Counter from imblearn.over_sampling import SMOTE X_resampled, y_resampled = SMOTE(random_state=1, sampling_strategy=1.0).fit_resample( X_train, y_train ) from collections import Counter Counter(y_resampled) # Train the Logistic Regression model using the resampled data smodel = LogisticRegression(solver='lbfgs', random_state=1) smodel.fit(X_resampled, y_resampled) # Calculated the balanced accuracy score y_pred = smodel.predict(X_test) balanced_accuracy_score(y_test, y_pred) # Display the confusion matrix confusion_matrix(y_test, y_pred) # Print the imbalanced classification report print(classification_report_imbalanced(y_test, y_pred))
pre rec spe f1 geo iba sup high_risk 0.84 0.99 0.99 0.91 0.99 0.99 619 low_risk 1.00 0.99 0.99 1.00 0.99 0.99 18765 avg / total 0.99 0.99 0.99 0.99 0.99 0.99 19384
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
UndersamplingIn this section, you will test an undersampling algorithm to determine which algorithm results in the best performance compared to the oversampling algorithms above. You will undersample the data using the Cluster Centroids algorithm and complete the folliowing steps:1. View the count of the target classes using `Counter` from the collections library. 3. Use the resampled data to train a logistic regression model.3. Calculate the balanced accuracy score from sklearn.metrics.4. Display the confusion matrix from sklearn.metrics.5. Generate a classication report using the `imbalanced_classification_report` from imbalanced-learn.Note: Use a random state of 1 for each sampling algorithm to ensure consistency between tests
# Resample the data using the ClusterCentroids resampler # View the count of target classes with Counter from imblearn.under_sampling import RandomUnderSampler ros = RandomUnderSampler(random_state=1) X_resampled, y_resampled = ros.fit_resample(X_train, y_train) Counter(y_resampled) # Train the Logistic Regression model using the resampled data from sklearn.linear_model import LogisticRegression umodel = LogisticRegression(solver='lbfgs', random_state=1) umodel.fit(X_resampled, y_resampled) # Calculate the balanced accuracy score from sklearn.metrics import balanced_accuracy_score balanced_accuracy_score(y_test, y_pred) # Display the confusion matrix from sklearn.metrics import confusion_matrix y_pred = umodel.predict(X_test) confusion_matrix(y_test, y_pred) # Print the imbalanced classification report from imblearn.metrics import classification_report_imbalanced print(classification_report_imbalanced(y_test, y_pred))
pre rec spe f1 geo iba sup high_risk 0.84 0.99 0.99 0.91 0.99 0.99 619 low_risk 1.00 0.99 0.99 1.00 0.99 0.99 18765 avg / total 0.99 0.99 0.99 0.99 0.99 0.99 19384
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
Combination (Over and Under) SamplingIn this section, you will test a combination over- and under-sampling algorithm to determine if the algorithm results in the best performance compared to the other sampling algorithms above. You will resample the data using the SMOTEENN algorithm and complete the folliowing steps:1. View the count of the target classes using `Counter` from the collections library. 3. Use the resampled data to train a logistic regression model.3. Calculate the balanced accuracy score from sklearn.metrics.4. Display the confusion matrix from sklearn.metrics.5. Generate a classication report using the `imbalanced_classification_report` from imbalanced-learn.Note: Use a random state of 1 for each sampling algorithm to ensure consistency between tests
# Resample the training data with SMOTEENN # View the count of target classes with Counter from imblearn.combine import SMOTEENN smote_enn = SMOTEENN(random_state=1) X_resampled, y_resampled = smote_enn.fit_resample(X, y) Counter(y_resampled) # Train the Logistic Regression model using the resampled data from sklearn.linear_model import LogisticRegression cmodel = LogisticRegression(solver='lbfgs', random_state=1) cmodel.fit(X_resampled, y_resampled) # Calculate the balanced accuracy score from sklearn.metrics import balanced_accuracy_score balanced_accuracy_score(y_test, y_pred) # Display the confusion matrix from sklearn.metrics import confusion_matrix y_pred = cmodel.predict(X_test) confusion_matrix(y_test, y_pred) # Print the imbalanced classification report from imblearn.metrics import classification_report_imbalanced print(classification_report_imbalanced(y_test, y_pred))
pre rec spe f1 geo iba sup high_risk 0.84 0.99 0.99 0.91 0.99 0.99 619 low_risk 1.00 0.99 0.99 1.00 0.99 0.99 18765 avg / total 0.99 0.99 0.99 0.99 0.99 0.99 19384
ADSL
Starter_Code/credit_risk_resampling.ipynb
JordanCandido/Unit11Homework
Content Based RecommendationsIn the previous notebook, you were introduced to a way to make recommendations using collaborative filtering. However, using this technique there are a large number of users who were left without any recommendations at all. Other users were left with fewer than the ten recommendations that were set up by our function to retrieve...In order to help these users out, let's try another technique **content based** recommendations. Let's start off where we were in the previous notebook.
import pandas as pd import numpy as np import matplotlib.pyplot as plt from collections import defaultdict from IPython.display import HTML import progressbar import tests as t import pickle %matplotlib inline # Read in the datasets movies = pd.read_csv('movies_clean.csv') reviews = pd.read_csv('reviews_clean.csv') del movies['Unnamed: 0'] del reviews['Unnamed: 0'] all_recs = pickle.load(open("all_recs.p", "rb"))
_____no_output_____
MIT
lessons/Recommendations/1_Intro_to_Recommendations/5_Content Based Recommendations - Solution.ipynb
vishalwaka/DSND_Term2
DatasetsFrom the above, you now have access to three important items that you will be using throughout the rest of this notebook. `a.` **movies** - a dataframe of all of the movies in the dataset along with other content related information about the movies (genre and date)`b.` **reviews** - this was the main dataframe used before for collaborative filtering, as it contains all of the interactions between users and movies.`c.` **all_recs** - a dictionary where each key is a user, and the value is a list of movie recommendations based on collaborative filteringFor the individuals in **all_recs** who did recieve 10 recommendations using collaborative filtering, we don't really need to worry about them. However, there were a number of individuals in our dataset who did not receive any recommendations.-----`1.` To begin, let's start with finding all of the users in our dataset who didn't get all 10 ratings we would have liked them to have using collaborative filtering.
users_with_all_recs = [] for user, movie_recs in all_recs.items(): if len(movie_recs) > 9: users_with_all_recs.append(user) print("There are {} users with all reccomendations from collaborative filtering.".format(len(users_with_all_recs))) users = np.unique(reviews['user_id']) users_who_need_recs = np.setdiff1d(users, users_with_all_recs) print("There are {} users who still need recommendations.".format(len(users_who_need_recs))) print("This means that only {}% of users received all 10 of their recommendations using collaborative filtering".format(round(len(users_with_all_recs)/len(np.unique(reviews['user_id'])), 4)*100)) # Some test here might be nice assert len(users_with_all_recs) == 22187 print("That's right there were still another 31781 users who needed recommendations when we only used collaborative filtering!")
That's right there were still another 31781 users who needed recommendations when we only used collaborative filtering!
MIT
lessons/Recommendations/1_Intro_to_Recommendations/5_Content Based Recommendations - Solution.ipynb
vishalwaka/DSND_Term2
Content Based RecommendationsYou will be doing a bit of a mix of content and collaborative filtering to make recommendations for the users this time. This will allow you to obtain recommendations in many cases where we didn't make recommendations earlier. `2.` Before finding recommendations, rank the user's ratings from highest ratings to lowest ratings. You will move through the movies in this order looking for other similar movies.
# create a dataframe similar to reviews, but ranked by rating for each user ranked_reviews = reviews.sort_values(by=['user_id', 'rating'], ascending=False)
_____no_output_____
MIT
lessons/Recommendations/1_Intro_to_Recommendations/5_Content Based Recommendations - Solution.ipynb
vishalwaka/DSND_Term2
SimilaritiesIn the collaborative filtering sections, you became quite familiar with different methods of determining the similarity (or distance) of two users. We can perform similarities based on content in much the same way. In many cases, it turns out that one of the fastest ways we can find out how similar items are to one another (when our matrix isn't totally sparse like it was in the earlier section) is by simply using matrix multiplication. If you are not familiar with this, an explanation is available [here by 3blue1brown](https://www.youtube.com/watch?v=LyGKycYT2v0) and another quick explanation is provided [on the post here](https://math.stackexchange.com/questions/689022/how-does-the-dot-product-determine-similarity).For us to pull out a matrix that describes the movies in our dataframe in terms of content, we might just use the indicator variables related to **year** and **genre** for our movies. Then we can obtain a matrix of how similar movies are to one another by taking the dot product of this matrix with itself. Notice in the below that the dot product where our 1 values overlap gives a value of 2 indicating higher similarity. In the second dot product, the 1 values don't match up. This leads to a dot product of 0 indicating lower similarity.We can perform the dot product on a matrix of movies with content characteristics to provide a movie by movie matrix where each cell is an indication of how similar two movies are to one another. In the below image, you can see that movies 1 and 8 are most similar, movies 2 and 8 are most similar and movies 3 and 9 are most similar for this subset of the data. The diagonal elements of the matrix will contain the similarity of a movie with itself, which will be the largest possible similarity (which will also be the number of 1's in the movie row within the orginal movie content matrix.`3.` Create a numpy array that is a matrix of indicator variables related to year (by century) and movie genres by movie. Perform the dot prodoct of this matrix with itself (transposed) to obtain a similarity matrix of each movie with every other movie. The final matrix should be 31245 x 31245.
# Subset so movie_content is only using the dummy variables for each genre and the 3 century based year dummy columns movie_content = np.array(movies.iloc[:,4:]) # Take the dot product to obtain a movie x movie matrix of similarities dot_prod_movies = movie_content.dot(np.transpose(movie_content)) # create checks for the dot product matrix assert dot_prod_movies.shape[0] == 31245 assert dot_prod_movies.shape[1] == 31245 assert dot_prod_movies[0, 0] == np.max(dot_prod_movies[0]) print("Looks like you passed all of the tests. Though they weren't very robust - if you want to write some of your own, I won't complain!")
Looks like you passed all of the tests. Though they weren't very robust - if you want to write some of your own, I won't complain!
MIT
lessons/Recommendations/1_Intro_to_Recommendations/5_Content Based Recommendations - Solution.ipynb
vishalwaka/DSND_Term2
For Each User...Now that you have a matrix where each user has their ratings ordered. You also have a second matrix where movies are each axis, and the matrix entries are larger where the two movies are more similar and smaller where the two movies are dissimilar. This matrix is a measure of content similarity. Therefore, it is time to get to the fun part.For each user, we will perform the following: i. For each movie, find the movies that are most similar that the user hasn't seen. ii. Continue through the available, rated movies until 10 recommendations or until there are no additional movies.As a final note, you may need to adjust the criteria for 'most similar' to obtain 10 recommendations. As a first pass, I used only movies with the highest possible similarity to one another as similar enough to add as a recommendation.`3.` In the below cell, complete each of the functions needed for making content based recommendations.
def find_similar_movies(movie_id): ''' INPUT movie_id - a movie_id OUTPUT similar_movies - an array of the most similar movies by title ''' # find the row of each movie id movie_idx = np.where(movies['movie_id'] == movie_id)[0][0] # find the most similar movie indices - to start I said they need to be the same for all content similar_idxs = np.where(dot_prod_movies[movie_idx] == np.max(dot_prod_movies[movie_idx]))[0] # pull the movie titles based on the indices similar_movies = np.array(movies.iloc[similar_idxs, ]['movie']) return similar_movies def get_movie_names(movie_ids): ''' INPUT movie_ids - a list of movie_ids OUTPUT movies - a list of movie names associated with the movie_ids ''' movie_lst = list(movies[movies['movie_id'].isin(movie_ids)]['movie']) return movie_lst def make_recs(): ''' INPUT None OUTPUT recs - a dictionary with keys of the user and values of the recommendations ''' # Create dictionary to return with users and ratings recs = defaultdict(set) # How many users for progress bar n_users = len(users) # Create the progressbar cnter = 0 bar = progressbar.ProgressBar(maxval=n_users+1, widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()]) bar.start() # For each user for user in users: # Update the progress bar cnter+=1 bar.update(cnter) # Pull only the reviews the user has seen reviews_temp = ranked_reviews[ranked_reviews['user_id'] == user] movies_temp = np.array(reviews_temp['movie_id']) movie_names = np.array(get_movie_names(movies_temp)) # Look at each of the movies (highest ranked first), # pull the movies the user hasn't seen that are most similar # These will be the recommendations - continue until 10 recs # or you have depleted the movie list for the user for movie in movies_temp: rec_movies = find_similar_movies(movie) temp_recs = np.setdiff1d(rec_movies, movie_names) recs[user].update(temp_recs) # If there are more than if len(recs[user]) > 9: break bar.finish() return recs recs = make_recs()
[========================================================================] 100%
MIT
lessons/Recommendations/1_Intro_to_Recommendations/5_Content Based Recommendations - Solution.ipynb
vishalwaka/DSND_Term2
How Did We Do?Now that you have made the recommendations, how did we do in providing everyone with a set of recommendations?`4.` Use the cells below to see how many individuals you were able to make recommendations for, as well as explore characteristics about individuals who you were not able to make recommendations for.
# Explore recommendations users_without_all_recs = [] users_with_all_recs = [] no_recs = [] for user, movie_recs in recs.items(): if len(movie_recs) < 10: users_without_all_recs.append(user) if len(movie_recs) > 9: users_with_all_recs.append(user) if len(movie_recs) == 0: no_recs.append(user) # Some characteristics of my content based recommendations print("There were {} users without all 10 recommendations we would have liked to have.".format(len(users_without_all_recs))) print("There were {} users with all 10 recommendations we would like them to have.".format(len(users_with_all_recs))) print("There were {} users with no recommendations at all!".format(len(no_recs))) # Closer look at individual user characteristics user_items = reviews[['user_id', 'movie_id', 'rating']] user_by_movie = user_items.groupby(['user_id', 'movie_id'])['rating'].max().unstack() def movies_watched(user_id): ''' INPUT: user_id - the user_id of an individual as int OUTPUT: movies - an array of movies the user has watched ''' movies = user_by_movie.loc[user_id][user_by_movie.loc[user_id].isnull() == False].index.values return movies movies_watched(189) cnter = 0 print("Some of the movie lists for users without any recommendations include:") for user_id in no_recs: print(user_id) print(get_movie_names(movies_watched(user_id))) cnter+=1 if cnter > 10: break
Some of the movie lists for users without any recommendations include: 189 ['El laberinto del fauno (2006)'] 797 ['The 414s (2015)'] 1603 ['Beauty and the Beast (2017)'] 2056 ['Brimstone (2016)'] 2438 ['Baby Driver (2017)'] 3322 ['Rosenberg (2013)'] 3925 ['El laberinto del fauno (2006)'] 4325 ['Beauty and the Beast (2017)'] 4773 ['The Frozen Ground (2013)'] 4869 ['Beauty and the Beast (2017)'] 4878 ['American Made (2017)']
MIT
lessons/Recommendations/1_Intro_to_Recommendations/5_Content Based Recommendations - Solution.ipynb
vishalwaka/DSND_Term2
Now What? Well, if you were really strict with your criteria for how similar two movies (like I was initially), then you still have some users that don't have all 10 recommendations (and a small group of users who have no recommendations at all). As stated earlier, recommendation engines are a bit of an **art** and a **science**. There are a number of things we still could look into - how do our collaborative filtering and content based recommendations compare to one another? How could we incorporate user input along with collaborative filtering and/or content based recommendations to improve any of our recommendations? How can we truly gain recommendations for every user?`5.` In this last step feel free to explore any last ideas you have with the recommendation techniques we have looked at so far. You might choose to make the final needed recommendations using the first technique with just top ranked movies. You might also loosen up the strictness in the similarity needed between movies. Be creative and share your insights with your classmates!
# Cells for exploring
_____no_output_____
MIT
lessons/Recommendations/1_Intro_to_Recommendations/5_Content Based Recommendations - Solution.ipynb
vishalwaka/DSND_Term2
InitializationWelcome to the first assignment of "Improving Deep Neural Networks". Training your neural network requires specifying an initial value of the weights. A well chosen initialization method will help learning. If you completed the previous course of this specialization, you probably followed our instructions for weight initialization, and it has worked out so far. But how do you choose the initialization for a new neural network? In this notebook, you will see how different initializations lead to different results. A well chosen initialization can:- Speed up the convergence of gradient descent- Increase the odds of gradient descent converging to a lower training (and generalization) error To get started, run the following cell to load the packages and the planar dataset you will try to classify.
import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec %matplotlib inline plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # load image dataset: blue/red dots in circles train_X, train_Y, test_X, test_Y = load_dataset()
_____no_output_____
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
You would like a classifier to separate the blue dots from the red dots. 1 - Neural Network model You will use a 3-layer neural network (already implemented for you). Here are the initialization methods you will experiment with: - *Zeros initialization* -- setting `initialization = "zeros"` in the input argument.- *Random initialization* -- setting `initialization = "random"` in the input argument. This initializes the weights to large random values. - *He initialization* -- setting `initialization = "he"` in the input argument. This initializes the weights to random values scaled according to a paper by He et al., 2015. **Instructions**: Please quickly read over the code below, and run it. In the next part you will implement the three initialization methods that this `model()` calls.
def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = "he"): """ Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID. Arguments: X -- input data, of shape (2, number of examples) Y -- true "label" vector (containing 0 for red dots; 1 for blue dots), of shape (1, number of examples) learning_rate -- learning rate for gradient descent num_iterations -- number of iterations to run gradient descent print_cost -- if True, print the cost every 1000 iterations initialization -- flag to choose which initialization to use ("zeros","random" or "he") Returns: parameters -- parameters learnt by the model """ grads = {} costs = [] # to keep track of the loss m = X.shape[1] # number of examples layers_dims = [X.shape[0], 10, 5, 1] # Initialize parameters dictionary. if initialization == "zeros": parameters = initialize_parameters_zeros(layers_dims) elif initialization == "random": parameters = initialize_parameters_random(layers_dims) elif initialization == "he": parameters = initialize_parameters_he(layers_dims) # Loop (gradient descent) for i in range(0, num_iterations): # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID. a3, cache = forward_propagation(X, parameters) # Loss cost = compute_loss(a3, Y) # Backward propagation. grads = backward_propagation(X, Y, cache) # Update parameters. parameters = update_parameters(parameters, grads, learning_rate) # Print the loss every 1000 iterations if print_cost and i % 1000 == 0: print("Cost after iteration {}: {}".format(i, cost)) costs.append(cost) # plot the loss plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(learning_rate)) plt.show() return parameters
_____no_output_____
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
2 - Zero initializationThere are two types of parameters to initialize in a neural network:- the weight matrices $(W^{[1]}, W^{[2]}, W^{[3]}, ..., W^{[L-1]}, W^{[L]})$- the bias vectors $(b^{[1]}, b^{[2]}, b^{[3]}, ..., b^{[L-1]}, b^{[L]})$**Exercise**: Implement the following function to initialize all parameters to zeros. You'll see later that this does not work well since it fails to "break symmetry", but lets try it anyway and see what happens. Use np.zeros((..,..)) with the correct shapes.
# GRADED FUNCTION: initialize_parameters_zeros def initialize_parameters_zeros(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- weight matrix of shape (layers_dims[1], layers_dims[0]) b1 -- bias vector of shape (layers_dims[1], 1) ... WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1]) bL -- bias vector of shape (layers_dims[L], 1) """ parameters = {} L = len(layers_dims) # number of layers in the network for l in range(1, L): ### START CODE HERE ### (≈ 2 lines of code) parameters['W' + str(l)] = np.zeros((layers_dims[l], layers_dims[l-1])) parameters['b' + str(l)] = np.zeros((layers_dims[l], 1)) ### END CODE HERE ### return parameters parameters = initialize_parameters_zeros([3,2,1]) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"]))
W1 = [[ 0. 0. 0.] [ 0. 0. 0.]] b1 = [[ 0.] [ 0.]] W2 = [[ 0. 0.]] b2 = [[ 0.]]
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
**Expected Output**: **W1** [[ 0. 0. 0.] [ 0. 0. 0.]] **b1** [[ 0.] [ 0.]] **W2** [[ 0. 0.]] **b2** [[ 0.]] Run the following code to train your model on 15,000 iterations using zeros initialization.
parameters = model(train_X, train_Y, initialization = "zeros") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters)
Cost after iteration 0: 0.6931471805599453 Cost after iteration 1000: 0.6931471805599453 Cost after iteration 2000: 0.6931471805599453 Cost after iteration 3000: 0.6931471805599453 Cost after iteration 4000: 0.6931471805599453 Cost after iteration 5000: 0.6931471805599453 Cost after iteration 6000: 0.6931471805599453 Cost after iteration 7000: 0.6931471805599453 Cost after iteration 8000: 0.6931471805599453 Cost after iteration 9000: 0.6931471805599453 Cost after iteration 10000: 0.6931471805599455 Cost after iteration 11000: 0.6931471805599453 Cost after iteration 12000: 0.6931471805599453 Cost after iteration 13000: 0.6931471805599453 Cost after iteration 14000: 0.6931471805599453
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
The performance is really bad, and the cost does not really decrease, and the algorithm performs no better than random guessing. Why? Lets look at the details of the predictions and the decision boundary:
print ("predictions_train = " + str(predictions_train)) print ("predictions_test = " + str(predictions_test)) plt.title("Model with Zeros initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.set_ylim([-1.5,1.5]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
_____no_output_____
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
The model is predicting 0 for every example. In general, initializing all the weights to zero results in the network failing to break symmetry. This means that every neuron in each layer will learn the same thing, and you might as well be training a neural network with $n^{[l]}=1$ for every layer, and the network is no more powerful than a linear classifier such as logistic regression. **What you should remember**:- The weights $W^{[l]}$ should be initialized randomly to break symmetry. - It is however okay to initialize the biases $b^{[l]}$ to zeros. Symmetry is still broken so long as $W^{[l]}$ is initialized randomly. 3 - Random initializationTo break symmetry, lets intialize the weights randomly. Following random initialization, each neuron can then proceed to learn a different function of its inputs. In this exercise, you will see what happens if the weights are intialized randomly, but to very large values. **Exercise**: Implement the following function to initialize your weights to large random values (scaled by \*10) and your biases to zeros. Use `np.random.randn(..,..) * 10` for weights and `np.zeros((.., ..))` for biases. We are using a fixed `np.random.seed(..)` to make sure your "random" weights match ours, so don't worry if running several times your code gives you always the same initial values for the parameters.
# GRADED FUNCTION: initialize_parameters_random def initialize_parameters_random(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- weight matrix of shape (layers_dims[1], layers_dims[0]) b1 -- bias vector of shape (layers_dims[1], 1) ... WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1]) bL -- bias vector of shape (layers_dims[L], 1) """ np.random.seed(3) # This seed makes sure your "random" numbers will be the as ours parameters = {} L = len(layers_dims) # integer representing the number of layers for l in range(1, L): ### START CODE HERE ### (≈ 2 lines of code) parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * 10 parameters['b' + str(l)] = np.zeros((layers_dims[l], 1)) ### END CODE HERE ### return parameters parameters = initialize_parameters_random([3, 2, 1]) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"]))
W1 = [[ 17.88628473 4.36509851 0.96497468] [-18.63492703 -2.77388203 -3.54758979]] b1 = [[ 0.] [ 0.]] W2 = [[-0.82741481 -6.27000677]] b2 = [[ 0.]]
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
**Expected Output**: **W1** [[ 17.88628473 4.36509851 0.96497468] [-18.63492703 -2.77388203 -3.54758979]] **b1** [[ 0.] [ 0.]] **W2** [[-0.82741481 -6.27000677]] **b2** [[ 0.]] Run the following code to train your model on 15,000 iterations using random initialization.
parameters = model(train_X, train_Y, initialization = "random") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters)
/home/jovyan/work/week5/Initialization/init_utils.py:145: RuntimeWarning: divide by zero encountered in log logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y) /home/jovyan/work/week5/Initialization/init_utils.py:145: RuntimeWarning: invalid value encountered in multiply logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
If you see "inf" as the cost after the iteration 0, this is because of numerical roundoff; a more numerically sophisticated implementation would fix this. But this isn't worth worrying about for our purposes. Anyway, it looks like you have broken symmetry, and this gives better results. than before. The model is no longer outputting all 0s.
print (predictions_train) print (predictions_test) plt.title("Model with large random initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.set_ylim([-1.5,1.5]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
_____no_output_____
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
**Observations**:- The cost starts very high. This is because with large random-valued weights, the last activation (sigmoid) outputs results that are very close to 0 or 1 for some examples, and when it gets that example wrong it incurs a very high loss for that example. Indeed, when $\log(a^{[3]}) = \log(0)$, the loss goes to infinity.- Poor initialization can lead to vanishing/exploding gradients, which also slows down the optimization algorithm. - If you train this network longer you will see better results, but initializing with overly large random numbers slows down the optimization.**In summary**:- Initializing weights to very large random values does not work well. - Hopefully intializing with small random values does better. The important question is: how small should be these random values be? Lets find out in the next part! 4 - He initializationFinally, try "He Initialization"; this is named for the first author of He et al., 2015. (If you have heard of "Xavier initialization", this is similar except Xavier initialization uses a scaling factor for the weights $W^{[l]}$ of `sqrt(1./layers_dims[l-1])` where He initialization would use `sqrt(2./layers_dims[l-1])`.)**Exercise**: Implement the following function to initialize your parameters with He initialization.**Hint**: This function is similar to the previous `initialize_parameters_random(...)`. The only difference is that instead of multiplying `np.random.randn(..,..)` by 10, you will multiply it by $\sqrt{\frac{2}{\text{dimension of the previous layer}}}$, which is what He initialization recommends for layers with a ReLU activation.
# GRADED FUNCTION: initialize_parameters_he def initialize_parameters_he(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- weight matrix of shape (layers_dims[1], layers_dims[0]) b1 -- bias vector of shape (layers_dims[1], 1) ... WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1]) bL -- bias vector of shape (layers_dims[L], 1) """ np.random.seed(3) parameters = {} L = len(layers_dims) - 1 # integer representing the number of layers for l in range(1, L + 1): ### START CODE HERE ### (≈ 2 lines of code) parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * np.sqrt(2/layers_dims[l-1]) parameters['b' + str(l)] = np.zeros((layers_dims[l], 1)) ### END CODE HERE ### return parameters parameters = initialize_parameters_he([2, 4, 1]) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"]))
W1 = [[ 1.78862847 0.43650985] [ 0.09649747 -1.8634927 ] [-0.2773882 -0.35475898] [-0.08274148 -0.62700068]] b1 = [[ 0.] [ 0.] [ 0.] [ 0.]] W2 = [[-0.03098412 -0.33744411 -0.92904268 0.62552248]] b2 = [[ 0.]]
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
**Expected Output**: **W1** [[ 1.78862847 0.43650985] [ 0.09649747 -1.8634927 ] [-0.2773882 -0.35475898] [-0.08274148 -0.62700068]] **b1** [[ 0.] [ 0.] [ 0.] [ 0.]] **W2** [[-0.03098412 -0.33744411 -0.92904268 0.62552248]] **b2** [[ 0.]] Run the following code to train your model on 15,000 iterations using He initialization.
parameters = model(train_X, train_Y, initialization = "he") print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters) plt.title("Model with He initialization") axes = plt.gca() axes.set_xlim([-1.5,1.5]) axes.set_ylim([-1.5,1.5]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
_____no_output_____
MIT
Course2/Week 1/Initialization.ipynb
AdityaSidharta/courseradeeplearning
Part 1
N = 2020 values = {k: v for v, k in enumerate(INPUT[:-1])} prev = INPUT[-1] for i in range(len(INPUT) - 1, N - 1): pos = values.get(prev) values[prev] = i if pos is None: prev = 0 else: prev = i - pos print(prev)
694
BSD-2-Clause
notebooks/december15.ipynb
jebreimo/Advent2020
Part 2
N = 30000000
_____no_output_____
BSD-2-Clause
notebooks/december15.ipynb
jebreimo/Advent2020
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 # collect all the imports here so I can run one cell to define them all when I need to restart the notebook import os import glob import numpy as np from collections import Counter from sklearn.utils import shuffle import nltk from nltk.corpus import stopwords from nltk.stem.porter import * import re from bs4 import BeautifulSoup import pickle import pandas as pd import sagemaker import torch import torch.utils.data import torch.nn as nn #define some constants used throughout data_dir = '../data/pytorch' # The folder we will use for storing data
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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[133]) print(train_y[133])
It is a superb Swedish film .. it was the first Swedish film I've seen .. it is simple & deep .. what a great combination!.<br /><br />Michael Nyqvist did a great performance as a famous conductor who seeks peace in his hometown.<br /><br />Frida Hallgren was great as his inspirational girlfriend to help him to carry on & never give up.<br /><br />The fight between the conductor and the hypocrite priest who loses his battle with Michael when his wife confronts him And defends Michael's noble cause to help his hometown people finding their own peace in music.<br /><br />The only thing that I didn't like was the ending .. it wasn't that good but it has some deep meaning. 1
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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) r = review_to_words(train_X[133]) print(r)
['superb', 'swedish', 'film', 'first', 'swedish', 'film', 'seen', 'simpl', 'deep', 'great', 'combin', 'michael', 'nyqvist', 'great', 'perform', 'famou', 'conductor', 'seek', 'peac', 'hometown', 'frida', 'hallgren', 'great', 'inspir', 'girlfriend', 'help', 'carri', 'never', 'give', 'fight', 'conductor', 'hypocrit', 'priest', 'lose', 'battl', 'michael', 'wife', 'confront', 'defend', 'michael', 'nobl', 'caus', 'help', 'hometown', 'peopl', 'find', 'peac', 'music', 'thing', 'like', 'end', 'good', 'deep', 'mean']
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
**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 method also removes trivial connecting words, such as "is", "the", "at". It also converts everything to lower-case and removes punctuation. 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
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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 from collections import Counter 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. # A dict storing the words that appear in the reviews along with how often they occur word_count = Counter() for item in data: word_count.update(item) print("The most common words are: ", word_count.most_common(10)) # 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 = [] for w, c in word_count.most_common(len(word_count)): sorted_words.append(w) 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)
The most common words are: [('movi', 51695), ('film', 48190), ('one', 27741), ('like', 22799), ('time', 16191), ('good', 15360), ('make', 15207), ('charact', 14178), ('get', 14141), ('see', 14111)]
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
**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 used words are: movi, film, one, like, time. These form a plausible list of the most frequently used words in such a context.
# TODO: Use this space to determine the five most frequently appearing words in the training set. # I did it above with a print statement in the build_dict() function. -jas
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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) dict_file = os.path.join(data_dir, 'word_dict.pkl') if os.path.exists(dict_file): with open(dict_file, "rb") as f: word_dict = pickle.load(f) print("Loaded existing word dictionary.") else: with open(os.path.join(data_dir, 'word_dict.pkl'), "wb") as f: pickle.dump(word_dict, f) print("Stored word dictionary to pickle file.")
Loaded existing word dictionary.
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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`.
# just playing around... print("vocab size = ", len(word_dict)) print("word_dict entries = ", word_dict["one"]) 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) # choosing not to reuse the raw train_X and test_X variables, in order to avoid having to go back to the # beginning of the notebook if I need to change some logic train_xc, train_xc_len = convert_and_pad_data(word_dict, train_X) test_xc, test_xc_len = convert_and_pad_data(word_dict, test_X)
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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[88]) print(train_xc[88])
['popular', 'sport', 'surf', 'like', 'mani', 'peopl', 'watch', 'documentari', 'realiz', 'danger', 'could', 'fact', 'surfer', 'also', 'scare', 'big', 'wave', 'even', 'somebodi', 'got', 'kill', 'still', 'kept', 'surf', 'enjoy', 'brave', 'peopl', 'accord', 'surfer', 'said', 'clearli', 'knew', 'felt', 'big', 'wave', 'came', 'adjust', 'best', 'avoid', 'direct', 'strike', 'big', 'wave', 'win', 'obvious', 'bring', 'huge', 'satisfact', 'amaz', 'cinematographi', 'cannot', 'overlook', 'absolut', 'visual', 'enjoy', 'excel', 'sport', 'documentari', '8', '10'] [ 865 1337 2634 5 46 23 12 505 420 927 36 100 1 27 758 116 1591 14 1625 111 103 59 749 2634 77 2014 23 1563 1 233 630 636 372 116 1591 333 1 53 564 98 1282 116 1591 551 470 324 554 1 356 570 495 1943 304 514 77 222 1337 505 634 83 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
**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:** We need to treat all data uniformly, so test data must go through same processing as the training data, so this is appropriate. However, we only built the vocabulary from words in the training set. It is possible that including the test data would have contributed some additional words in the top 5000. However, I believe this is not a significant problem, as 5000 words is a large vocabulary, and the training set is already large enough to be statistically representative of the language used. So it is likely that only a few of the less frequently used words at the end of the dictionary might change as a result of adding or omitting the test data. 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 import sagemaker pd.concat([pd.DataFrame(train_y), pd.DataFrame(train_xc_len), pd.DataFrame(train_xc)], axis=1) \ .to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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) print(bucket) print(data_dir) print(input_data)
sagemaker-us-east-1-139645156747 ../data/pytorch s3://sagemaker-us-east-1-139645156747/sagemaker/sentiment_rnn
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
**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
import torch.nn as nn class LSTMClassifier(nn.Module): """  This is the simple RNN model we will be using to perform Sentiment Analysis.  """ def __init__(self, embedding_dim, hidden_dim, vocab_size): """  Initialize the model by settingg up the various layers.  """ super(LSTMClassifier, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0) self.lstm = nn.LSTM(embedding_dim, hidden_dim) self.dense = nn.Linear(in_features=hidden_dim, out_features=1) self.sig = nn.Sigmoid() self.word_dict = None def forward(self, x): """  Perform a forward pass of our model on some input.  """ x = x.t() lengths = x[0,:] reviews = x[1:,:] embeds = self.embedding(reviews) lstm_out, _ = self.lstm(embeds) out = self.dense(lstm_out) out = out[lengths - 1, range(len(lengths))] return self.sig(out.squeeze())
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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)
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
(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): CLIP_LIMIT = 5 #print("Entering train.") for epoch in range(1, epochs + 1): model.train() total_loss = 0 #-jas -- shouldn't we be initializing the hidden layer here? Why is the model.py not using a hidden state? for batch in train_loader: batch_X, batch_y = batch #print("Training batch of size ", len(batch_X)) batch_X = batch_X.to(device) batch_y = batch_y.to(device) # TODO: Complete this train method to train the model provided. ### get the model's prediction for the current batch model.zero_grad() output = model(batch_X) ### compute the loss for this batch and backpropagate it loss = loss_fn(output.squeeze(), batch_y) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), CLIP_LIMIT) optimizer.step() ### accumulate loss over the epoch total_loss += loss.data.item() print("Epoch: {}, BCELoss: {}".format(epoch, total_loss / len(train_loader)))
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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.6921594619750977 Epoch: 2, BCELoss: 0.6825043082237243 Epoch: 3, BCELoss: 0.6743957757949829 Epoch: 4, BCELoss: 0.6654969811439514 Epoch: 5, BCELoss: 0.6548115968704223
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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})
2020-07-07 23:59:13 Starting - Starting the training job... 2020-07-07 23:59:16 Starting - Launching requested ML instances...... 2020-07-08 00:00:40 Starting - Preparing the instances for training............ 2020-07-08 00:02:28 Downloading - Downloading input data... 2020-07-08 00:03:05 Training - Downloading the training image... 2020-07-08 00:03:28 Training - Training image download completed. Training in progress.bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell 2020-07-08 00:03:29,421 sagemaker-containers INFO Imported framework sagemaker_pytorch_container.training 2020-07-08 00:03:29,448 sagemaker_pytorch_container.training INFO Block until all host DNS lookups succeed. 2020-07-08 00:03:29,451 sagemaker_pytorch_container.training INFO Invoking user training script. 2020-07-08 00:03:29,705 sagemaker-containers INFO Module train does not provide a setup.py.  Generating setup.py 2020-07-08 00:03:29,705 sagemaker-containers INFO Generating setup.cfg 2020-07-08 00:03:29,705 sagemaker-containers INFO Generating MANIFEST.in 2020-07-08 00:03:29,705 sagemaker-containers INFO Installing module with the following command: /usr/bin/python -m pip install -U . -r requirements.txt Processing /opt/ml/code Collecting 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) Collecting numpy (from -r requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/b5/36/88723426b4ff576809fec7d73594fe17a35c27f8d01f93637637a29ae25b/numpy-1.18.5-cp35-cp35m-manylinux1_x86_64.whl (19.9MB) Collecting nltk (from -r requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/92/75/ce35194d8e3022203cca0d2f896dbb88689f9b3fce8e9f9cff942913519d/nltk-3.5.zip (1.4MB) Collecting beautifulsoup4 (from -r requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/66/25/ff030e2437265616a1e9b25ccc864e0371a0bc3adb7c5a404fd661c6f4f6/beautifulsoup4-4.9.1-py3-none-any.whl (115kB) Collecting html5lib (from -r requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/6c/dd/a834df6482147d48e225a49515aabc28974ad5a4ca3215c18a882565b028/html5lib-1.1-py2.py3-none-any.whl (112kB) Requirement 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) Collecting pytz>=2011k (from pandas->-r requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/4f/a4/879454d49688e2fad93e59d7d4efda580b783c745fd2ec2a3adf87b0808d/pytz-2020.1-py2.py3-none-any.whl (510kB) Requirement already satisfied, skipping upgrade: click in /usr/local/lib/python3.5/dist-packages (from nltk->-r requirements.txt (line 3)) (7.0) Collecting joblib (from nltk->-r requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/28/5c/cf6a2b65a321c4a209efcdf64c2689efae2cb62661f8f6f4bb28547cf1bf/joblib-0.14.1-py2.py3-none-any.whl (294kB) Collecting regex (from nltk->-r requirements.txt (line 3))  Downloading https://files.pythonhosted.org/packages/b8/7b/01510a6229c2176425bda54d15fba05a4b3df169b87265b008480261d2f9/regex-2020.6.8.tar.gz (690kB) Collecting tqdm (from nltk->-r requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/46/62/7663894f67ac5a41a0d8812d78d9d2a9404124051885af9d77dc526fb399/tqdm-4.47.0-py2.py3-none-any.whl (66kB) Collecting soupsieve>1.2 (from beautifulsoup4->-r requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/6f/8f/457f4a5390eeae1cc3aeab89deb7724c965be841ffca6cfca9197482e470/soupsieve-2.0.1-py3-none-any.whl Collecting 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 Requirement already satisfied, skipping upgrade: six>=1.9 in /usr/local/lib/python3.5/dist-packages (from html5lib->-r requirements.txt (line 5)) (1.11.0) Building wheels for collected packages: nltk, train, regex Running setup.py bdist_wheel for nltk: started Running setup.py bdist_wheel for nltk: finished with status 'done' Stored in directory: /root/.cache/pip/wheels/ae/8c/3f/b1fe0ba04555b08b57ab52ab7f86023639a526d8bc8d384306 Running setup.py bdist_wheel for train: started  Running setup.py bdist_wheel for train: finished with status 'done' Stored in directory: /tmp/pip-ephem-wheel-cache-bf0ei8xl/wheels/35/24/16/37574d11bf9bde50616c67372a334f94fa8356bc7164af8ca3 Running setup.py bdist_wheel for regex: started  Running setup.py bdist_wheel for regex: finished with status 'done' Stored in directory: /root/.cache/pip/wheels/9c/e2/cf/246ad8c87bcdf3cba1ec95fa89bc205c9037aa8f4d2e26fdad Successfully built nltk train regex Installing collected packages: pytz, numpy, pandas, joblib, regex, tqdm, nltk, soupsieve, beautifulsoup4, webencodings, html5lib, train Found existing installation: numpy 1.15.4 Uninstalling numpy-1.15.4: Successfully uninstalled numpy-1.15.4 Successfully installed beautifulsoup4-4.9.1 html5lib-1.1 joblib-0.14.1 nltk-3.5 numpy-1.18.5 pandas-0.24.2 pytz-2020.1 regex-2020.6.8 soupsieve-2.0.1 tqdm-4.47.0 train-1.0.0 webencodings-0.5.1 You are using pip version 18.1, however version 20.2b1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2020-07-08 00:03:51,923 sagemaker-containers INFO Invoking user script  Training Env:  { "log_level": 20, "input_dir": "/opt/ml/input", "hyperparameters": { "epochs": 10, "hidden_dim": 200 }, "framework_module": "sagemaker_pytorch_container.training:main", "output_dir": "/opt/ml/output", "user_entry_point": "train.py", "num_cpus": 4, "network_interface_name": "eth0", "output_data_dir": "/opt/ml/output/data", "additional_framework_parameters": {}, "resource_config": { "current_host": "algo-1", "network_interface_name": "eth0", "hosts": [ "algo-1" ] }, "output_intermediate_dir": "/opt/ml/output/intermediate", "channel_input_dirs": { "training": "/opt/ml/input/data/training" }, "job_name": "sagemaker-pytorch-2020-07-07-23-59-12-964", "model_dir": "/opt/ml/model", "current_host": "algo-1", "input_config_dir": "/opt/ml/input/config", "module_dir": "s3://sagemaker-us-east-1-139645156747/sagemaker-pytorch-2020-07-07-23-59-12-964/source/sourcedir.tar.gz", "module_name": "train", "input_data_config": { "training": { "TrainingInputMode": "File", "RecordWrapperType": "None", "S3DistributionType": "FullyReplicated" } }, "num_gpus": 1, "hosts": [ "algo-1" ] }  Environment variables:  SM_USER_ARGS=["--epochs","10","--hidden_dim","200"] PYTHONPATH=/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 SM_CURRENT_HOST=algo-1 SM_INPUT_DATA_CONFIG={"training":{"RecordWrapperType":"None","S3DistributionType":"FullyReplicated","TrainingInputMode":"File"}} SM_CHANNEL_TRAINING=/opt/ml/input/data/training SM_FRAMEWORK_MODULE=sagemaker_pytorch_container.training:main SM_RESOURCE_CONFIG={"current_host":"algo-1","hosts":["algo-1"],"network_interface_name":"eth0"} SM_MODULE_DIR=s3://sagemaker-us-east-1-139645156747/sagemaker-pytorch-2020-07-07-23-59-12-964/source/sourcedir.tar.gz SM_HP_HIDDEN_DIM=200 SM_OUTPUT_DIR=/opt/ml/output SM_NETWORK_INTERFACE_NAME=eth0 SM_NUM_CPUS=4 SM_HP_EPOCHS=10 SM_INPUT_CONFIG_DIR=/opt/ml/input/config SM_CHANNELS=["training"] SM_USER_ENTRY_POINT=train.py SM_INPUT_DIR=/opt/ml/input SM_HOSTS=["algo-1"] SM_OUTPUT_DATA_DIR=/opt/ml/output/data SM_MODULE_NAME=train SM_MODEL_DIR=/opt/ml/model SM_OUTPUT_INTERMEDIATE_DIR=/opt/ml/output/intermediate SM_HPS={"epochs":10,"hidden_dim":200} SM_FRAMEWORK_PARAMS={} SM_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-2020-07-07-23-59-12-964","log_level":20,"model_dir":"/opt/ml/model","module_dir":"s3://sagemaker-us-east-1-139645156747/sagemaker-pytorch-2020-07-07-23-59-12-964/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"} SM_LOG_LEVEL=20 SM_NUM_GPUS=1  Invoking script with the following command:  /usr/bin/python -m train --epochs 10 --hidden_dim 200  ///// In train/__main__: Using device cuda. Get train data loader. Model loaded with embedding_dim 32, hidden_dim 200, vocab_size 5000. ///// Entering train/train. Epoch: 1, BCELoss: 0.6746065276009696 Epoch: 2, BCELoss: 0.5870167746835825 Epoch: 3, BCELoss: 0.4859969281420416 Epoch: 4, BCELoss: 0.4077845751022806 Epoch: 5, BCELoss: 0.3617596650610165 Epoch: 6, BCELoss: 0.33730681514253424 Epoch: 7, BCELoss: 0.3138365362371717 Epoch: 8, BCELoss: 0.2878250777721405 Epoch: 9, BCELoss: 0.2827960873136715 Epoch: 10, BCELoss: 0.2594302384829035 2020-07-08 00:06:51,852 sagemaker-containers INFO Reporting training SUCCESS 2020-07-08 00:07:03 Uploading - Uploading generated training model 2020-07-08 00:07:03 Completed - Training job completed Training seconds: 275 Billable seconds: 275
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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")
-------------------!
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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_inputs = pd.concat([pd.DataFrame(test_xc_len), pd.DataFrame(test_xc)], 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)) break return predictions predictions = predict(test_inputs.values) predictions = [round(num) for num in predictions] from sklearn.metrics import accuracy_score accuracy_score(test_y, predictions)
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
**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:** Accuracy of 0.86 is very close to what was achieved with the XGBoost model. These are two entirely different approaches to making predictions, so there is no particular reason to expect them to perform identically. It is not clear to me which is inherently more adept at predicting sentiment in textual descriptions. My suspicion is that an RNN may be better, since it is built to learn about sequences of words, not just collections of words (XGBoost seems to not consider the ordering of the words in a review). (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_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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 def convert_single_review(raw_review): # cleanse the raw review of html tags, punctuation, capital letters, and stem the words sentence = review_to_words(raw_review) #print("sentence = ", sentence) # convert the cleansed text to dictionary indices and ensure each item is the correct length result, length = convert_and_pad(word_dict, sentence) #print("len = ", length, ", test_data = \n", result) return result, length test_data, test_data_length = convert_single_review(test_review) print(test_data)
[1, 1374, 50, 53, 3, 4, 878, 173, 392, 682, 29, 723, 2, 4422, 275, 2078, 1059, 760, 1, 582, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review.
### The TODO comment a couple cells above is misleading. It seems to be saying that there are two input ### arguments: review_length and review. The truth is, there is only one input arg, which is the review. ### However, it should be a 2D array, with the first dimension representing the number of reviews (in this ### case, only 1). # convert to a torch tensor & use view to reshape it to a single row, then convert back to a numpy array td = torch.from_numpy(np.array(test_data)) print(td.shape) td = td.view(1, -1) ta = td.numpy() print(ta.shape) predictor.predict(ta)
torch.Size([500]) (1, 500)
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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
import argparse import json import os import pickle import sys import sagemaker_containers import pandas as pd import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.utils.data from model import LSTMClassifier from utils import review_to_words, convert_and_pad def model_fn(model_dir): """Load the PyTorch model from the `model_dir` directory.""" print("Loading model.") # First, load the parameters used to create the model. model_info = {} model_info_path = os.path.join(model_dir, 'model_info.pth') with open(model_info_path, 'rb') as f: model_info = torch.load(f) print("model_info: {}".format(model_info)) # Determine the device and construct the model. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = LSTMClassifier(model_info['embedding_dim'], model_info['hidden_dim'], model_info['vocab_size']) # Load the store model parameters. model_path = os.path.join(model_dir, 'model.pth') with open(model_path, 'rb') as f: model.load_state_dict(torch.load(f)) # Load the saved word_dict. word_dict_path = os.path.join(model_dir, 'word_dict.pkl') with open(word_dict_path, 'rb') as f: model.word_dict = pickle.load(f) model.to(device).eval() print("Done loading model.") return model def input_fn(serialized_input_data, content_type): print('Deserializing the input data.') if content_type == 'text/plain': data = serialized_input_data.decode('utf-8') return data raise Exception('Requested unsupported ContentType in content_type: ' + content_type) def output_fn(prediction_output, accept): print('Serializing the generated output.') return str(prediction_output) def predict_fn(input_data, model): print('Inferring sentiment of input data.') device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if model.word_dict is None: raise Exception('Model has not been loaded properly, no word_dict.') # TODO: Process input_data so that it is ready to be sent to our model. # You should produce two variables: # data_X - A sequence of length 500 which represents the converted review # data_len - The length of the review data_X = None data_len = None # Using data_X and data_len we construct an appropriate input tensor. Remember # that our model expects input data of the form 'len, review[500]'. data_pack = np.hstack((data_len, data_X)) data_pack = data_pack.reshape(1, -1) data = torch.from_numpy(data_pack) data = data.to(device) # Make sure to put the model into evaluation mode model.eval() # TODO: Compute the result of applying the model to the input data. The variable `result` should # be a numpy array which contains a single integer which is either 1 or 0 result = None return result
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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.
#jas sandbox result = torch.tensor(0.77).cpu() print(result) result = np.array(result.round().int().numpy()) print("result of model execution = ", result) 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) ###jas - changed from m4.large to p2.xlarge to get more performance predictor = model.deploy(initial_instance_count=1, instance_type='ml.p2.xlarge')
-----------------!
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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') #print("review_input = ", review_input) # 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_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
As an additional test, we can try sending the `test_review` that we looked at earlier.
predictor.predict(test_review)
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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 predictor.predict("This movie sucked!")
_____no_output_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
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:** Test review: "The movie sucked." Prediction = 0Test review: "Here is my movie review. The movie was great! I loved it. Best movie of the year!" Prediction = 1I have tried several others, and the full system is working really well. 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_____
BSD-3-Clause
sagemaker/SageMaker_Project.ipynb
TonysCousin/Udacity
***EXERCISE 9.1***Using the `df` provided below, get the mean score of people whose name stats with 'J'
df = pd.DataFrame({ 'name': ['John', 'Albert', 'Jack', 'Josef', 'Bob', 'Juliette', 'Mary', 'Jane'], 'score': [5,8,6,4,8,7,3,5] }) df.loc[df['name'].str.contains('J'), 'score'].mean()
_____no_output_____
MIT
solutions/09_extra_tips_solutions.ipynb
gabrielecalvo/pandas_tutorial
Uproot and Awkward Arrays Tutorial for Electron Ion Collider usersJim Pivarski (Princeton University) PreliminariesThis is a draft of the demo presented to the Electron Ion Collider group on April 8, 2020. The repository with the final presentation is [jpivarski/2020-04-08-eic-jlab](https://github.com/jpivarski/2020-04-08-eic-jlab). This presentation was given before the final 1.0 version was released. Some interfaces may have changed. To run this notebook, make sure you have version 0.2.10 ([GitHub](https://github.com/scikit-hep/awkward-1.0/releases/tag/0.2.10), [pip](https://pypi.org/project/awkward1/0.2.10/)) by installing```bashpip install 'awkward1==0.2.10'```This notebook also depends on `uproot<4.0`, `particle`, `boost-histogram`, `matplotlib`, `mplhep`, `numba`, `pandas`, `numexpr`, and `autograd`, as well as a data file, `"open_charm_18x275_10k.root"`. See the final presentation for a suitable environment definition and a copy of the file. Table of contents* [Uproot: getting data](uproot) - [Exploring a TFile](Exploring-a-TFile) - [Exploring a TTree](Exploring-a-TTree) - [Turning ROOT branches into NumPy arrays](Turning-ROOT-branches-into-NumPy-arrays) - [Memory management; caching and iteration](Memory-management;-caching-and-iteration) - [Jagged arrays (segue)](Jagged-arrays-(segue))* [Awkward Array: manipulating data](awkward) - [Using Uproot data in Awkward 1.0](Using-Uproot-data-in-Awkward-1.0) - [Iteration in Python vs array-at-a-time operations](Iteration-in-Python-vs-array-at-a-time-operations) - [Zipping arrays into records and projecting them back out](Zipping-arrays-into-records-and-projecting-them-back-out) - [Filtering (cutting) events and particles with advanced selections](Filtering-(cutting)-events-and-particles-with-advanced-selections) - [Flattening for plots and regularizing to NumPy for machine learning](Flattening-for-plots-and-regularizing-to-NumPy-for-machine-learning) - [Broadcasting flat arrays and jagged arrays](Broadcasting-flat-arrays-and-jagged-arrays) - [Combinatorics: cartesian and combinations](Combinatorics:-cartesian-and-combinations) - [Reducing from combinations](Reducing-from-combinations) - [Imperative, but still fast, programming in Numba](Imperative,-but-still-fast,-programming-in-Numba) - [Grafting jagged data onto Pandas](Grafting-jagged-data-onto-Pandas) - [NumExpr, Autograd, and other third-party libraries](NumExpr,-Autograd,-and-other-third-party-libraries) Uproot is a pure Python reimplementation of a significant part of ROOT I/O.You can read TTrees containing basic data types, STL vectors, strings, and some more complex data, especially if it was written with a high "splitLevel".You can also read histograms and other objects into generic containers, but the C++ methods that give those objects functionality are not available. Exploring a TFile Uproot was designed to be Pythonic, so the way we interact with ROOT files is different than it is in ROOT.
import uproot file = uproot.open("open_charm_18x275_10k.root")
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
A ROOT file may be thought of as a dict of key-value pairs, like a Python dict.
file.keys() file.values()
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
**What's the `b` before the name?** All strings retrieved from ROOT are unencoded, which Python 3 treats differently from Python 2. In the near future, Uproot will automatically interpret all strings from ROOT as UTF-8 and this cosmetic issue will be gone.**What's the `;1` at the end of the name?** It's the cycle number, something ROOT uses to track multiple versions of an object. You can usually ignore it. Nested directories are a dict of dicts.
file["events"].keys() file["events"]["tree"]
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
But there are shortcuts: * use a `/` to navigate through the levels in a single string; * use `allkeys` to recursively show all keys in all directories.
file.allkeys() file["events/tree"]
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Exploring a TTree A TTree can also be thought of as a dict of dicts, this time to navigate through TBranches.
tree = file["events/tree"] tree.keys()
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Often, the first thing I do when I look at a TTree is `show` to see how each branch is going to be interpreted.
print("branch name streamer (for complex data) interpretation in Python") print("==============================================================================") tree.show()
branch name streamer (for complex data) interpretation in Python ============================================================================== evt_id (no streamer) asdtype('>u8') evt_true_q2 (no streamer) asdtype('>f8') evt_true_x (no streamer) asdtype('>f8') evt_true_y (no streamer) asdtype('>f8') evt_true_w2 (no streamer) asdtype('>f8') evt_true_nu (no streamer) asdtype('>f8') evt_has_dis_info (no streamer) asdtype('int8') evt_prt_count (no streamer) asdtype('>u8') evt_weight (no streamer) asdtype('>f8') id (no streamer) asjagged(asdtype('>u8')) pdg (no streamer) asjagged(asdtype('>i8')) trk_id (no streamer) asjagged(asdtype('>f8')) charge (no streamer) asjagged(asdtype('>f8')) dir_x (no streamer) asjagged(asdtype('>f8')) dir_y (no streamer) asjagged(asdtype('>f8')) dir_z (no streamer) asjagged(asdtype('>f8')) p (no streamer) asjagged(asdtype('>f8')) px (no streamer) asjagged(asdtype('>f8')) py (no streamer) asjagged(asdtype('>f8')) pz (no streamer) asjagged(asdtype('>f8')) tot_e (no streamer) asjagged(asdtype('>f8')) m (no streamer) asjagged(asdtype('>f8')) time (no streamer) asjagged(asdtype('>f8')) is_beam (no streamer) asjagged(asdtype('bool')) is_stable (no streamer) asjagged(asdtype('bool')) gen_code (no streamer) asjagged(asdtype('bool')) mother_id (no streamer) asjagged(asdtype('>u8')) mother_second_id (no streamer) asjagged(asdtype('>u8')) has_pol_info (no streamer) asjagged(asdtype('>f8')) pol_x (no streamer) asjagged(asdtype('>f8')) pol_y (no streamer) asjagged(asdtype('>f8')) pol_z (no streamer) asjagged(asdtype('>f8')) has_vtx_info (no streamer) asjagged(asdtype('bool')) vtx_id (no streamer) asjagged(asdtype('>u8')) vtx_x (no streamer) asjagged(asdtype('>f8')) vtx_y (no streamer) asjagged(asdtype('>f8')) vtx_z (no streamer) asjagged(asdtype('>f8')) vtx_t (no streamer) asjagged(asdtype('>f8')) has_smear_info (no streamer) asjagged(asdtype('bool')) smear_has_e (no streamer) asjagged(asdtype('bool')) smear_has_p (no streamer) asjagged(asdtype('bool')) smear_has_pid (no streamer) asjagged(asdtype('bool')) smear_has_vtx (no streamer) asjagged(asdtype('bool')) smear_has_any_eppid (no streamer) asjagged(asdtype('bool')) smear_orig_tot_e (no streamer) asjagged(asdtype('>f8')) smear_orig_p (no streamer) asjagged(asdtype('>f8')) smear_orig_px (no streamer) asjagged(asdtype('>f8')) smear_orig_py (no streamer) asjagged(asdtype('>f8')) smear_orig_pz (no streamer) asjagged(asdtype('>f8')) smear_orig_vtx_x (no streamer) asjagged(asdtype('>f8')) smear_orig_vtx_y (no streamer) asjagged(asdtype('>f8')) smear_orig_vtx_z (no streamer) asjagged(asdtype('>f8'))
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Most of the information you'd expect to find in a TTree is there. See [uproot.readthedocs.io](https://uproot.readthedocs.io/en/latest/ttree-handling.html) for a complete list.
tree.numentries tree["evt_id"].compressedbytes(), tree["evt_id"].uncompressedbytes(), tree["evt_id"].compressionratio() tree["evt_id"].numbaskets [tree["evt_id"].basket_entrystart(i) for i in range(3)]
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Turning ROOT branches into NumPy arrays There are several methods for this; they differ only in convenience.
# TBranch → array tree["evt_id"].array() # TTree + branch name → array tree.array("evt_id") # TTree + branch names → arrays tree.arrays(["evt_id", "evt_prt_count"]) # TTree + branch name pattern(s) → arrays tree.arrays("evt_*") # TTree + branch name regex(s) → arrays tree.arrays("/evt_[A-Z_0-9]*/i")
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
**Convenience 1:** turn the bytestrings into real strings (will soon be unnecessary).
tree.arrays("evt_*", namedecode="utf-8")
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
**Convenience 2:** output a tuple instead of a dict.
tree.arrays(["evt_id", "evt_prt_count"], outputtype=tuple)
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
... to use it in assignment:
evt_id, evt_prt_count = tree.arrays(["evt_id", "evt_prt_count"], outputtype=tuple) evt_id
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Memory management; caching and iteration The `array` methods read an entire branch into memory. Sometimes, you might not have enough memory to do that.The simplest solution is to set `entrystart` (inclusive) and `entrystop` (exclusive) to read a small batch at a time.
tree.array("evt_id", entrystart=500, entrystop=600)
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Uproot is _not_ agressive about caching: if you call `arrays` many times (for many small batches), it will read from the file every time.You can avoid frequent re-reading by assigning arrays to variables, but then you'd have to manage all those variables.**Instead, use explicit caching:**
# Make a cache with an acceptable limit. gigabyte_cache = uproot.ArrayCache("1 GB") # Read the array from disk: tree.array("evt_id", cache=gigabyte_cache) # Get the array from the cache: tree.array("evt_id", cache=gigabyte_cache)
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
The advantage is that the same code can be used for first time and subsequent times. You can put this in a loop.Naturally, fetching from the cache is much faster than reading from disk (though our file isn't very big!).
%%timeit tree.arrays("*") %%timeit tree.arrays("*", cache=gigabyte_cache)
2.14 ms ± 45.2 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
The value of an explicit cache is that you get to control it.
len(gigabyte_cache) gigabyte_cache.clear() len(gigabyte_cache)
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Setting `entrystart` and `entrystop` can get annoying; we probably want to do it in a loop.There's a method, `iterate`, for that.
for arrays in tree.iterate("evt_*", entrysteps=1000): print({name: len(array) for name, array in arrays.items()})
{b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000} {b'evt_id': 1000, b'evt_true_q2': 1000, b'evt_true_x': 1000, b'evt_true_y': 1000, b'evt_true_w2': 1000, b'evt_true_nu': 1000, b'evt_has_dis_info': 1000, b'evt_prt_count': 1000, b'evt_weight': 1000}
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Keep in mind that this is a loop over _batches_, not _events_.What goes in the loop is code that applies to _arrays_.You can also set the `entrysteps` to be a size in memory.
for arrays in tree.iterate("evt_*", entrysteps="100 kB"): print({name: len(array) for name, array in arrays.items()})
{b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 544, b'evt_true_q2': 544, b'evt_true_x': 544, b'evt_true_y': 544, b'evt_true_w2': 544, b'evt_true_nu': 544, b'evt_has_dis_info': 544, b'evt_prt_count': 544, b'evt_weight': 544}
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
The same size in memory covers more events if you read fewer branches.
for arrays in tree.iterate("evt_id", entrysteps="100 kB"): print({name: len(array) for name, array in arrays.items()})
{b'evt_id': 10000}
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
This `TTree.iterate` method is similar in form to the `uproot.iterate` function, which iterates in batches over a collection of files.
for arrays in uproot.iterate(["open_charm_18x275_10k.root", "open_charm_18x275_10k.root", "open_charm_18x275_10k.root"], "events/tree", "evt_*", entrysteps="100 kB"): print({name: len(array) for name, array in arrays.items()})
{b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 544, b'evt_true_q2': 544, b'evt_true_x': 544, b'evt_true_y': 544, b'evt_true_w2': 544, b'evt_true_nu': 544, b'evt_has_dis_info': 544, b'evt_prt_count': 544, b'evt_weight': 544} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 544, b'evt_true_q2': 544, b'evt_true_x': 544, b'evt_true_y': 544, b'evt_true_w2': 544, b'evt_true_nu': 544, b'evt_has_dis_info': 544, b'evt_prt_count': 544, b'evt_weight': 544} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 1576, b'evt_true_q2': 1576, b'evt_true_x': 1576, b'evt_true_y': 1576, b'evt_true_w2': 1576, b'evt_true_nu': 1576, b'evt_has_dis_info': 1576, b'evt_prt_count': 1576, b'evt_weight': 1576} {b'evt_id': 544, b'evt_true_q2': 544, b'evt_true_x': 544, b'evt_true_y': 544, b'evt_true_w2': 544, b'evt_true_nu': 544, b'evt_has_dis_info': 544, b'evt_prt_count': 544, b'evt_weight': 544}
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Jagged arrays (segue) Most of the branches in this file have an "asjagged" interpretation, instead of "asdtype" (NumPy).
tree["evt_id"].interpretation tree["pdg"].interpretation
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
This means that they have multiple values per entry.
tree["pdg"].array()
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Jagged arrays (lists of variable-length sublists) are very common in particle physics, and surprisingly uncommon in other fields.We need them because we almost always have a variable number of particles per event.
from particle import Particle # https://github.com/scikit-hep/particle counter = 0 for event in tree["pdg"].array(): print(len(event), "particles:", " ".join(Particle.from_pdgid(x).name for x in event)) counter += 1 if counter == 30: break
51 particles: e- pi+ pi- K- pi+ pi- pi- pi+ pi+ pi+ gamma gamma K(L)0 K+ pi- K(L)0 gamma gamma gamma gamma pi+ pi- pi+ gamma gamma p pi- pi+ K+ pi- pi- K+ K- gamma gamma pi+ pi- K+ pi- pi+ K(L)0 K(L)0 gamma gamma pi+ pi- pi+ gamma gamma gamma gamma 26 particles: e- pi+ pi- n~ n gamma pi- pi+ gamma gamma pi+ gamma gamma gamma gamma gamma K(L)0 gamma gamma gamma gamma pi- pi+ pi- gamma gamma 27 particles: e- n p pi+ pi+ pi+ pi- pi- pi- pi- pi- pi+ pi- gamma gamma gamma pi+ K+ K- pi+ gamma gamma gamma gamma gamma gamma pi- 28 particles: e- pi+ pi- nu(mu) mu+ gamma gamma pi- pi+ n gamma gamma n pi- p~ pi+ gamma gamma pi+ pi- K- K(L)0 gamma gamma gamma gamma gamma gamma 30 particles: e- pi+ pi- pi+ pi- n gamma gamma K- pi+ n pi- pi+ gamma n~ p~ pi+ K(L)0 gamma gamma pi- gamma gamma pi- pi+ gamma gamma K+ pi- gamma 12 particles: e- gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma 25 particles: pi- K- K+ pi- gamma gamma pi- gamma gamma pi- K(L)0 K(L)0 gamma gamma gamma gamma K- pi+ gamma gamma gamma gamma gamma gamma gamma 4 particles: e- nu(e) e+ n 57 particles: e- pi+ n p K- K+ pi+ pi+ pi- gamma gamma K(L)0 p~ n pi- n~ pi+ pi+ pi- gamma gamma K(L)0 K+ K- K+ K- gamma gamma pi+ gamma gamma gamma gamma gamma gamma pi- gamma gamma pi- e+ e- gamma pi+ pi- gamma gamma gamma gamma gamma gamma e+ e- gamma gamma gamma gamma gamma 40 particles: e- n K- K+ gamma gamma K+ pi- gamma gamma gamma pi+ n~ pi- K- pi+ gamma gamma gamma gamma gamma gamma gamma gamma pi- K(L)0 pi- pi+ gamma gamma gamma gamma gamma gamma gamma gamma e+ e- gamma gamma 16 particles: e- pi- n pi- pi+ gamma pi+ pi- K(L)0 pi+ gamma gamma K+ K- gamma gamma 16 particles: e- K(L)0 pi- K(L)0 pi+ pi- gamma gamma nu(e)~ e- K+ K(L)0 gamma gamma gamma gamma 79 particles: e- pi+ pi- pi+ pi- K- pi+ pi- gamma gamma gamma n pi+ gamma gamma pi+ pi- K(L)0 p pi+ p~ gamma gamma gamma pi- pi+ pi+ pi- K+ gamma gamma pi+ pi- gamma gamma K+ gamma gamma pi+ pi- gamma gamma gamma pi- gamma gamma n pi+ pi- gamma gamma gamma gamma pi+ pi- gamma gamma gamma gamma K- pi+ gamma gamma pi- gamma gamma gamma gamma gamma gamma gamma gamma p~ pi+ K(L)0 gamma gamma pi+ pi- 34 particles: e- n pi- pi+ K+ pi+ pi+ pi+ pi- pi+ pi- pi- pi- K(L)0 pi+ pi+ pi- pi+ pi- gamma gamma K+ gamma gamma K(L)0 gamma gamma gamma gamma pi+ pi- pi- gamma gamma 24 particles: e- K- K+ pi- pi- pi+ gamma gamma gamma gamma gamma gamma gamma pi- K- pi+ pi+ pi- gamma gamma gamma gamma gamma gamma 32 particles: e- n pi+ pi- pi+ pi- pi+ pi- pi- gamma gamma gamma gamma gamma pi+ pi- e+ e- gamma K+ pi- K- pi+ gamma gamma gamma gamma gamma gamma gamma gamma gamma 37 particles: e- pi- pi+ pi+ pi- n n~ pi+ p pi+ pi- K+ K- gamma gamma gamma gamma pi+ pi- gamma gamma pi- pi- pi+ gamma gamma p~ gamma e+ e- gamma gamma gamma gamma gamma gamma gamma 63 particles: e- pi- n pi+ K- K+ pi+ pi- K(L)0 n pi- n~ pi+ n K(L)0 K(L)0 pi- gamma gamma gamma gamma K- pi- gamma gamma pi+ pi- gamma gamma gamma K(L)0 K- pi+ pi+ pi+ pi- pi+ pi- p pi- n~ pi+ gamma gamma K(L)0 pi+ gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma K- K+ pi- gamma gamma 37 particles: e- n p~ pi+ pi- pi+ K- pi+ gamma gamma pi+ nu(e) e+ K- gamma gamma pi- K- gamma gamma K(L)0 K+ pi- pi+ pi- pi+ pi- gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma 5 particles: e- gamma pi- gamma gamma 26 particles: e- pi- n n~ pi+ pi+ nu(mu) mu+ n pi- gamma gamma gamma gamma gamma gamma gamma K(L)0 pi- gamma gamma gamma pi+ gamma gamma K(L)0 39 particles: e- pi+ n pi- K+ pi- gamma pi+ pi- gamma gamma pi- pi- pi+ pi- pi+ pi+ pi- gamma gamma gamma gamma gamma K+ K- gamma gamma pi+ pi- gamma gamma gamma gamma gamma gamma gamma gamma pi+ pi- 58 particles: e- pi+ pi- pi+ pi- p~ pi- pi+ n~ pi- gamma pi+ pi+ pi- K(L)0 K- K+ pi- n n~ pi+ pi- pi+ pi+ pi+ pi- pi+ pi- pi+ pi- gamma gamma pi- gamma K(L)0 pi+ pi- gamma gamma gamma gamma gamma gamma pi+ pi- n gamma gamma pi+ gamma gamma gamma gamma gamma gamma n gamma gamma 27 particles: e- n pi+ pi- K- pi+ gamma gamma gamma n K- pi- pi- pi+ gamma gamma gamma gamma pi+ gamma gamma gamma gamma gamma gamma gamma gamma 23 particles: e- pi+ pi+ p pi- pi+ gamma gamma gamma pi+ pi- K(L)0 pi+ gamma gamma p~ pi- pi+ nu(e)~ e- gamma K+ pi- 20 particles: e- n pi+ pi- gamma gamma gamma K(L)0 pi- pi- e+ e- gamma gamma gamma gamma gamma gamma pi+ gamma 38 particles: e- K- pi+ pi- gamma gamma K(L)0 pi+ pi- pi+ p p~ pi- pi+ pi+ gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma nu(mu)~ mu- gamma gamma pi- pi+ pi- gamma gamma gamma gamma gamma gamma 70 particles: e- n pi- K+ n~ pi+ pi- pi- K- pi+ K(L)0 pi+ pi- p p~ pi- pi+ n pi+ pi- pi- pi+ gamma gamma n~ gamma gamma pi+ gamma gamma gamma gamma K(L)0 pi- gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma gamma n~ pi+ gamma pi+ pi+ gamma gamma n gamma gamma gamma gamma p~ pi+ pi+ pi- K- gamma gamma gamma gamma gamma gamma gamma 14 particles: e- pi- gamma pi+ pi- pi+ pi+ K(L)0 gamma gamma gamma gamma gamma gamma 29 particles: e- K- pi- K+ pi+ pi+ pi- gamma gamma pi- pi+ K(L)0 gamma gamma gamma gamma K(L)0 gamma gamma gamma pi+ pi- pi+ pi- K(L)0 K(L)0 K(L)0 gamma gamma
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Although you can iterate over jagged arrays with for loops, the idiomatic and faster way to do it is with array-at-a-time functions.
import numpy as np vtx_x, vtx_y, vtx_z = tree.arrays(["vtx_[xyz]"], outputtype=tuple) vtx_dist = np.sqrt(vtx_x**2 + vtx_y**2 + vtx_z**2) vtx_dist import matplotlib.pyplot as plt import mplhep as hep # https://github.com/scikit-hep/mplhep import boost_histogram as bh # https://github.com/scikit-hep/boost-histogram vtx_hist = bh.Histogram(bh.axis.Regular(100, 0, 0.1)) vtx_hist.fill(vtx_dist.flatten()) hep.histplot(vtx_hist) vtx_dist > 0.01 pdg = tree["pdg"].array() pdg[vtx_dist > 0.01] counter = 0 for event in pdg[vtx_dist > 0.10]: print(len(event), "particles:", " ".join(Particle.from_pdgid(x).name for x in event)) counter += 1 if counter == 30: break Particle.from_string("p~") Particle.from_string("p~").pdgid is_antiproton = (pdg == Particle.from_string("p~").pdgid) is_antiproton hep.histplot(bh.Histogram(bh.axis.Regular(100, 0, 0.1)).fill( vtx_dist[is_antiproton].flatten() ))
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
But that's a topic for the next section. Awkward Array is a library for manipulating arbitrary data structures in a NumPy-like way.The idea is that you have a large number of identically typed, nested objects in variable-length lists. Using Uproot data in Awkward 1.0Awkward Array is in transition from * version 0.x, which is in use at the LHC but has revealed some design flaws, to * version 1.x, which is well-architected and has completed development, but is not in widespread use yet.Awkward 1.0 hasn't been incorporated into Uproot yet, which is how it will get in front of most users.Since development is complete and the interface is (intentionally) different, I thought it better to show you the new version.
import awkward1 as ak
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Old-style arrays can be converted into the new framework with [ak.from_awkward0](https://awkward-array.readthedocs.io/en/latest/_auto/ak.from_awkward0.html). This won't be a necessary step for long.
?ak.from_awkward0 ?ak.to_awkward0 ak.from_awkward0(tree.array("pdg")) arrays = {name: ak.from_awkward0(array) for name, array in tree.arrays(namedecode="utf-8").items()} arrays ?ak.Array
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Iteration in Python vs array-at-a-time operationsAs before, you _can_ iterate over them in Python, but only do that for small-scale exploration.
%%timeit -n1 -r1 vtx_dist = [] for xs, xy, xz in zip(arrays["vtx_x"], arrays["vtx_y"], arrays["vtx_z"]): out = [] for x, y, z in zip(xs, xy, xz): out.append(np.sqrt(x**2 + y**2 + z**2)) vtx_dist.append(out) %%timeit -n100 -r1 vtx_dist = np.sqrt(arrays["vtx_x"]**2 + arrays["vtx_y"]**2 + arrays["vtx_z"]**2)
23.8 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 100 loops each)
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Zipping arrays into records and projecting them back outInstead of having all these arrays floating around, let's [ak.zip](https://awkward-array.readthedocs.io/en/latest/_auto/ak.zip.html) them into a structure.(This is the sort of thing that a framework developer might do for the data analysts.)
?ak.zip events = ak.zip({"id": arrays["evt_id"], "true": ak.zip({"q2": arrays["evt_true_q2"], "x": arrays["evt_true_x"], "y": arrays["evt_true_y"], "w2": arrays["evt_true_w2"], "nu": arrays["evt_true_nu"]}), "has_dis_info": arrays["evt_has_dis_info"], "prt_count": arrays["evt_prt_count"], "prt": ak.zip({"id": arrays["id"], "pdg": arrays["pdg"], "trk_id": arrays["trk_id"], "charge": arrays["charge"], "dir": ak.zip({"x": arrays["dir_x"], "y": arrays["dir_y"], "z": arrays["dir_z"]}, with_name="point3"), "p": arrays["p"], "px": arrays["px"], "py": arrays["py"], "pz": arrays["pz"], "m": arrays["m"], "time": arrays["time"], "is_beam": arrays["is_beam"], "is_stable": arrays["is_stable"], "gen_code": arrays["gen_code"], "mother": ak.zip({"id": arrays["mother_id"], "second_id": arrays["mother_second_id"]}), "pol": ak.zip({"has_info": arrays["has_pol_info"], "x": arrays["pol_x"], "y": arrays["pol_y"], "z": arrays["pol_z"]}, with_name="point3"), "vtx": ak.zip({"has_info": arrays["has_vtx_info"], "id": arrays["vtx_id"], "x": arrays["vtx_x"], "y": arrays["vtx_y"], "z": arrays["vtx_z"], "t": arrays["vtx_t"]}, with_name="point3"), "smear": ak.zip({"has_info": arrays["has_smear_info"], "has_e": arrays["smear_has_e"], "has_p": arrays["smear_has_p"], "has_pid": arrays["smear_has_pid"], "has_vtx": arrays["smear_has_vtx"], "has_any_eppid": arrays["smear_has_any_eppid"], "orig": ak.zip({"tot_e": arrays["smear_orig_tot_e"], "p": arrays["smear_orig_p"], "px": arrays["smear_orig_px"], "py": arrays["smear_orig_py"], "pz": arrays["smear_orig_pz"], "vtx": ak.zip({"x": arrays["smear_orig_vtx_x"], "y": arrays["smear_orig_vtx_y"], "z": arrays["smear_orig_vtx_z"]}, with_name="point3")})})}, with_name="particle")}, depthlimit=1) ?ak.type ak.type(events)
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
The type written with better formatting:```javascript10000 * {"id": uint64, "true": {"q2": float64, "x": float64, "y": float64, "w2": float64, "nu": float64}, "has_dis_info": int8, "prt_count": uint64, "prt": var * particle["id": uint64, "pdg": int64, "trk_id": float64, "charge": float64, "dir": point3["x": float64, "y": float64, "z": float64], "p": float64, "px": float64, "py": float64, "pz": float64, "m": float64, "time": float64, "is_beam": bool, "is_stable": bool, "gen_code": bool, "mother": {"id": uint64, "second_id": uint64}, "pol": point3["has_info": float64, "x": float64, "y": float64, "z": float64], "vtx": point3["has_info": bool, "id": uint64, "x": float64, "y": float64, "z": float64, "t": float64], "smear": {"has_info": bool, "has_e": bool, "has_p": bool, "has_pid": bool, "has_vtx": bool, "has_any_eppid": bool, "orig": {"tot_e": float64, "p": float64, "px": float64, "py": float64, "pz": float64, "vtx": point3["x": float64, "y": float64, "z": float64]}}]}``` It means that these are now nested objects.
?ak.to_list ak.to_list(events[0].prt[0]) ak.to_list(events[-1].prt[:10].smear.orig.vtx)
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
Alternatively,
ak.to_list(events[-1, "prt", :10, "smear", "orig", "vtx"])
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
"Zipping" arrays together into structures costs nothing (time does not scale with size of data), nor does "projecting" arrays out of structures.
events.prt.px events.prt.py events.prt.pz
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
This is called "projection" because the request for `"pz"` is slicing through arrays and jagged arrays.The following are equivalent:
events[999, "prt", 12, "pz"] events["prt", 999, 12, "pz"] events[999, "prt", "pz", 12] events["prt", 999, "pz", 12]
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
This "object oriented view" is a conceptual aid, not a constraint on computation. It's very fluid.Moreover, we can add behaviors to named records, like methods in object oriented programming. (See [ak.behavior](https://awkward-array.readthedocs.io/en/latest/ak.behavior.html) in the documentation.)(This is the sort of thing that a framework developer might do for the data analysts.)
def point3_absolute(data): return np.sqrt(data.x**2 + data.y**2 + data.z**2) def point3_distance(left, right): return np.sqrt((left.x - right.x)**2 + (left.y - right.y)**2 + (left.z - right.z)**2) ak.behavior[np.absolute, "point3"] = point3_absolute ak.behavior[np.subtract, "point3", "point3"] = point3_distance # Absolute value of all smear origin vertexes abs(events.prt.smear.orig.vtx) # Absolute value of the last smear origin vertex abs(events[-1].prt[-1].smear.orig.vtx) # Distance between each particle vertex and itself events.prt.vtx - events.prt.vtx # Distances between the first and last particle vertexes in the first 100 events events.prt.vtx[:100, 0] - events.prt.vtx[:100, -1]
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0
More methods can be added by declaring subclasses of arrays and records.
class ParticleRecord(ak.Record): @property def pt(self): return np.sqrt(self.px**2 + self.py**2) class ParticleArray(ak.Array): __name__ = "Array" # prevent it from writing <ParticleArray [...] type='...'> # instead of <Array [...] type='...'> @property def pt(self): return np.sqrt(self.px**2 + self.py**2) ak.behavior["particle"] = ParticleRecord ak.behavior["*", "particle"] = ParticleArray type(events[0].prt[0]) events[0].prt[0] events[0].prt[0].pt type(events.prt) events.prt events.prt.pt
_____no_output_____
BSD-3-Clause
docs-jupyter/2020-04-08-eic-jlab.ipynb
reikdas/awkward-1.0