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... | %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 = 'scali... | _____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,direct... | 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... | 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('Shearl... | 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... | _____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_sc... | _____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 con... | 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... | 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 t... | # 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 u... | 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... | 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 Regres... | 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... | 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 classe... | # 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 mode... | 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... | 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... | # 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.... | 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... | 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 th... | 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')
... | _____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 datafra... | 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.set... | 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 ratin... | # 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... | # 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 ... | 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. Ther... | 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 star... | [========================================================================] 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 ... | # 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.app... | 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 (20... | 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... | # 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 instructio... | 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['f... | _____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.- ... | 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 ... | _____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 ... | # 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 = [[ 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... | 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
C... | 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... | # 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 = [[ 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.]] ... | 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.multip... | 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 lon... | 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... | # 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 -- ... | 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]]... | 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.se... | _____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 ente... | %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 collec... | _____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... | 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[d... | 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']
... | 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 loade... | 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 o... | 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.su... | _____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', 'pri... | 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 t... | 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... | 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 cou... | 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 ... | 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 i... | # 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)
... | 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 appearin... | _____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'... | 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 appropriat... | 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 ... | !pygmentize train/model.py | [34mimport[39;49;00m [04m[36mtorch.nn[39;49;00m [34mas[39;49;00m [04m[36mnn[39;49;00m
[34mclass[39;49;00m [04m[32mLSTMClassifier[39;49;00m(nn.Module):
[33m"""[39;49;00m
[33m This is the simple RNN model we will be using to perform Sentiment Analysis.[39;49;00m
[33m """[39;49;00m
... | 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 ... | 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... | _____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... | _____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 ... | 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)... | 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',
... | 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 tra... | 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 ... | # 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 ... | _____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 diffe... | 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 se... | # 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)
#... | [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, ... | 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
#... | 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 delet... | 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, w... | !pygmentize serve/predict.py | [34mimport[39;49;00m [04m[36margparse[39;49;00m
[34mimport[39;49;00m [04m[36mjson[39;49;00m
[34mimport[39;49;00m [04m[36mos[39;49;00m
[34mimport[39;49;00m [04m[36mpickle[39;49;00m
[34mimport[39;49;00m [04m[36msys[39;49;00m
[34mimport[39;49;00m [04m[36msagemaker_containers[39;49;00m
... | 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 th... | #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, endpo... | -----------------! | 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 t... | 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... | _____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 th... | 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 wi... | 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-... | 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 numbe... | 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 ... | 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': 10... | 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': 15... | 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': 15... | 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... | 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/bo... | _____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... | 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... | 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"],
... | _____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 * parti... | ?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 t... | 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_distan... | _____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='...'>
@proper... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.