path
stringlengths 7
265
| concatenated_notebook
stringlengths 46
17M
|
---|---|
enkf_colab.ipynb | ###Markdown
Multiway Ensemble Kalman Filtering IntroductionFor illustration of the **TensorGraphicalModel Julia package**, in this notebook we present examples applying various (inverse) covariance estimation algorithms to *Ensemble Kalman filter (EnKF)*, a method used for tracking dynamical systems and estimating the true state of a system from noisy observations. Specifically, we apply several (sparse and/or multiway) methods for the state (inverse) covariance estimation step of the EnKF
###Code
%%shell
set -e
#---------------------------------------------------#
JULIA_VERSION="1.5.0" # any version ≥ 0.7.0
JULIA_PACKAGES="IJulia BenchmarkTools Plots MIRTjim https://github.com/ywa136/TensorGraphicalModels.jl"
JULIA_PACKAGES_IF_GPU="CUDA" # or CuArrays for older Julia versions
JULIA_NUM_THREADS=4
#---------------------------------------------------#
if [ -n "$COLAB_GPU" ] && [ -z `which julia` ]; then
# Install Julia
JULIA_VER=`cut -d '.' -f -2 <<< "$JULIA_VERSION"`
echo "Installing Julia $JULIA_VERSION on the current Colab Runtime..."
BASE_URL="https://julialang-s3.julialang.org/bin/linux/x64"
URL="$BASE_URL/$JULIA_VER/julia-$JULIA_VERSION-linux-x86_64.tar.gz"
wget -nv $URL -O /tmp/julia.tar.gz # -nv means "not verbose"
tar -x -f /tmp/julia.tar.gz -C /usr/local --strip-components 1
rm /tmp/julia.tar.gz
# Install Packages
if [ "$COLAB_GPU" = "1" ]; then
JULIA_PACKAGES="$JULIA_PACKAGES $JULIA_PACKAGES_IF_GPU"
fi
for PKG in `echo $JULIA_PACKAGES`; do
echo "Installing Julia package $PKG..."
julia -e 'using Pkg; pkg"add '$PKG'; precompile;"' &> /dev/null
done
# Install kernel and rename it to "julia"
echo "Installing IJulia kernel..."
julia -e 'using IJulia; IJulia.installkernel("julia", env=Dict(
"JULIA_NUM_THREADS"=>"'"$JULIA_NUM_THREADS"'"))'
KERNEL_DIR=`julia -e "using IJulia; print(IJulia.kerneldir())"`
KERNEL_NAME=`ls -d "$KERNEL_DIR"/julia*`
mv -f $KERNEL_NAME "$KERNEL_DIR"/julia
echo ''
echo "Success! Please reload this page and jump to the next section."
fi
versioninfo()
###Output
Julia Version 1.5.0
Commit 96786e22cc (2020-08-01 23:44 UTC)
Platform Info:
OS: Linux (x86_64-pc-linux-gnu)
CPU: Intel(R) Xeon(R) CPU @ 2.20GHz
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-9.0.1 (ORCJIT, broadwell)
Environment:
JULIA_NUM_THREADS = 4
###Markdown
Generate ground truth dataWe first generate simulated data from a linear Gaussian state space model. Here, two major types of dynamical structures are implemented in the package: *convection_diffusion* for states generated by solving the Convection Diffusion equation and *poisson* for states generated by solving the time-invariant Poisson equation; three types of observation sturctures are implemented: *identity*, *linear_perm*, and *linear_perm_miss*, which amounts to observations subject to: only additive random noise, random permutation of the state variale plus additive noise, and random permutation of partially observed state variable plus noise, respectively.
###Code
using TensorGraphicalModels
dynamic_type = "convection_diffusion" #specify the dynamical model: convection_diffusion, poisson, or poisson_ar
obs_type = "linear_perm_miss" #specify the observation model: identity, linear_perm, or linear_perm_miss
T = 20 #time stamps
N = 50 #number of ensembles
px = py = (32, 32) #state dimension
obs_noise = 0.01
process_noise = 0.01
add_process_noise = false
X, Y, H = TensorGraphicalModels.gen_kalmanfilter_data(dynamic_type, obs_type, T, px, py, obs_noise, process_noise, add_process_noise)
###Output
_____no_output_____
###Markdown
Visualize the true process
###Code
using Plots
using MIRTjim
# gif all time steps
anim_x = @animate for i=2:(T+1)
# plot(jim(reshape(X[:,i],px),clim=(-3.0,3.0)),
# title=string("Time step: ",i))
Plots.plot(jim(reshape(X[:,i],px)),
title=string("Time step: ",i))
end
gif(anim_x, fps=5)
###Output
┌ Info: Precompiling GR_jll [d2c73de3-f751-5644-a686-071e5b155ba9]
└ @ Base loading.jl:1278
┌ Info: Saved animation to
│ fn = /content/tmp.gif
└ @ Plots /root/.julia/packages/Plots/T6yvp/src/animation.jl:114
###Markdown
Run EnKF with tensor graphical modelsTo estimate the high-dimensional state (inverse) covariance matrix of an EnKF. Any (sparse and/or multiway) estimator could be used. Here, we compare the performance of *Glasso*, *KPCA*, *KGlasso*, *Teralasso*, and *SyGlasso*.
###Code
method_list = ["glasso", "kpca", "kglasso", "teralasso", "sg_palm"]
NRMSEs_list = []
time_list = []
Omegahat_list = []
for method in method_list
starttime = time()
## run enkf
Xhat, Xhat_bar, Omegahat = enkf(Y,
TensorGraphicalModels.method_str_to_type(method),
dynamic_type,
H,
px,
py,
N,
obs_noise,
process_noise,
add_process_noise)
## timer
stoptime = time() - starttime
push!(time_list, stoptime)
## compute NRMSEs
NRMSEs = TensorGraphicalModels.compute_nrmse(X, Xhat)
push!(NRMSEs_list, NRMSEs)
## store est. precision/cov matrix
push!(Omegahat_list, Omegahat)
end
###Output
_____no_output_____
###Markdown
Plot RMSEs for estimated ensembles
###Code
fig = Plots.plot()
xlabel!("Time step")
ylabel!("RMSE")
for method in method_list
if method == "sg_palm"
NRMSEs = NRMSEs_list[end]
elseif method == "teralasso"
NRMSEs = NRMSEs_list[4]
elseif method == "kglasso"
NRMSEs = NRMSEs_list[3]
elseif method == "glasso"
NRMSEs = NRMSEs_list[1]
elseif method == "kpca"
NRMSEs = NRMSEs_list[2]
end
## plot rmse progression for each method
TensorGraphicalModels.plot_nrmse!(NRMSEs, method)
end
display(fig)
###Output
_____no_output_____
###Markdown
Visualize the learned covariance / precision matrix
###Code
spy(Omegahat_list[end]) # SG-PALM estimated sparse precision matrix
###Output
_____no_output_____ |
analysis/misclassification/bertweet.ipynb | ###Markdown
BERTweet Misclassification Analysis Analyise validation tweets misclassified by BERTweet.
###Code
import os
import sys
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
sys.path.append(os.path.join(os.pardir, os.pardir, 'src'))
from data_processing.loading import load_train_valid_data
# Load original dataset to get correct labels.
path_to_dataset = os.path.join(os.pardir, os.pardir, 'dataset')
_, valid = load_train_valid_data(path_to_dataset)
display(valid)
# Load BERTweet predictions generated while experimenting with the model.
valid_predictions = pd.read_csv('bertweet_valid_predictions.csv', index_col='Id')
# Change column names to fit with original dataset for easy joining.
valid_predictions.index.name = 'id'
valid_predictions.columns = ['prediction']
display(valid_predictions)
# Join BERTweet classifications with original labels.
valid_joint = valid.join(valid_predictions)
# Filter correctly classified tweets.
valid_correct = valid_joint[valid_joint['label'] == valid_joint['prediction']]
# Filter misclassified tweets, i.e. where prediction is different from label.
valid_misclass = valid_joint[valid_joint['label'] != valid_joint['prediction']]
display(valid_correct)
display(valid_misclass)
# Compute confusion matrix to see if one class is more frequently
# misclassified.
labels = ['positive', 'negative']
num_valid_tweets = len(valid)
num_true_positives = len(valid_correct[valid_correct['label'] == 1])
num_false_positives = len(valid_misclass[valid_misclass['label'] == 1])
num_true_negatives = len(valid_correct[valid_correct['label'] == -1])
num_false_negatives = len(valid_misclass[valid_misclass['label'] == -1])
confusion_matrix = np.array([
[num_true_positives, num_false_positives],
[num_false_negatives, num_true_negatives]
]) / num_valid_tweets
fig, ax = plt.subplots(figsize=((6,6)))
im = ax.imshow(confusion_matrix)
# Show all ticks and label with respective list entries.
ax.set_xticks(np.arange(len(labels)))
ax.set_yticks(np.arange(len(labels)))
ax.set_xticklabels(labels)
ax.set_yticklabels(labels)
ax.set_xlabel('Predicted')
ax.set_ylabel('True')
# Loop over data dimensions and create text annotations.
for i in range(len(labels)):
for j in range(len(labels)):
text = ax.text(j, i, f'{100 * confusion_matrix[i, j]:.2f}%',
ha="center", va="center")
ax.set_title("BERTweet Confusion Matrix")
fig.tight_layout()
plt.show()
###Output
_____no_output_____
###Markdown
Misclassified Common Twitter AbbreviationsCheck to see if common Twitter abbreviations occur in the misclassifiedvalidation tweets with a frequency higher than their full text versions. If so,then this hints at BERTweet struggling with Twitter abbreviations, which wouldbe ground for dictionary normalization with the full text versions.The candidates for Twitter abbreviations and their full versions are taken from:https://www.webopedia.com/reference/twitter-dictionary-guide/
###Code
# Compute a dataframe with a summary of occurrences of different candidate
# abbreviations and their full text counter parts.
abbreviation_occur = []
with open("normalization-dict-candidates.csv", "r") as f:
for index, line in enumerate(f.readlines()):
if index == 0:
# Skip the header line.
continue
abbr, full = line.strip().split(",")
abbr_matcher = re.compile(
f"(\s+{abbr}\s+)|(^{abbr}\s+)|(\s+{abbr}$)|(^{abbr}$)"
)
full_matcher = re.compile(
f"(\s+{full}\s+)|(^{full}\s+)|(\s+{full}$)|(^{full}$)"
)
valid['abbr_occur'] = valid['tweet'].apply(
lambda tweet: len(abbr_matcher.findall(tweet))
)
valid_misclass['abbr_occur'] = valid_misclass['tweet'].apply(
lambda tweet: len(abbr_matcher.findall(tweet))
)
valid['full_occur'] = valid['tweet'].apply(
lambda tweet: len(full_matcher.findall(tweet))
)
valid_misclass['full_occur'] = valid_misclass['tweet'].apply(
lambda tweet: len(full_matcher.findall(tweet))
)
valid_abbr_occur = float(valid['abbr_occur'].sum())
misclass_abbr_occur = valid_misclass['abbr_occur'].sum()
valid_full_occur = float(valid['full_occur'].sum())
misclass_full_occur = valid_misclass['full_occur'].sum()
abbreviation_occur.append([
abbr,
misclass_abbr_occur,
valid_abbr_occur,
misclass_abbr_occur / valid_abbr_occur,
full,
misclass_full_occur,
valid_full_occur,
misclass_full_occur / valid_full_occur
])
del valid['abbr_occur']
del valid['full_occur']
del valid_misclass['abbr_occur']
del valid_misclass['full_occur']
abbreviation_occurrances = pd.DataFrame(
abbreviation_occur,
columns=[
'abbr',
'abbr_misclass_occur',
'abbr_valid_occur',
'abbr_error_rate',
'full',
'full_misclass_occur',
'full_valid_occur',
'full_error_rate'
]
)
display(abbreviation_occurrances)
# Filter out the actual dictionary normalizations we would want to do based on
# the misclassified data.
dict_normalizations = abbreviation_occurrances.copy()
# Remove abbreviations or full text versions that do not occur at all, as
# we cannot possibly do a reasonable replacement.
dict_normalizations = dict_normalizations[dict_normalizations['abbr_valid_occur'] != 0.0]
dict_normalizations = dict_normalizations[dict_normalizations['full_valid_occur'] != 0.0]
# Remove abbreviations or full text versions where both are below the
# overall error rate, as there is no ground for replacement at this stage.
misclass_error = len(valid_misclass) / float(len(valid))
dict_normalizations = dict_normalizations[
(dict_normalizations['abbr_error_rate'] >= misclass_error) |
(dict_normalizations['full_error_rate'] >= misclass_error)
]
# Remove abbreviations that occur more frequently than their full text
# counterparts. If the abbreviation occurs more frequently, then we would
# actually be obfuscating the text.
# Example: 'yolo' is in considerably higher use than 'you only live once'.
dict_normalizations = dict_normalizations[
dict_normalizations['abbr_valid_occur'] <=
dict_normalizations['full_valid_occur']
]
# Finally, keep abbreviations that have higher error rate than their full text
# counterparts so that they can be replaced.
dict_normalizations = dict_normalizations[
dict_normalizations['abbr_error_rate'] >=
dict_normalizations['full_error_rate']
]
display(dict_normalizations)
# Store normalization dictionary for later use.
normalization_dict = dict_normalizations[['abbr','full']]
normalization_dict = normalization_dict.rename(columns={'abbr': 'abbreviation', 'full': 'full_text'})
normalization_dict.to_csv('normalization-dict.csv', index=False)
display(normalization_dict)
###Output
_____no_output_____ |
Demo/.ipynb_checkpoints/Demo_NoCellOutput-checkpoint.ipynb | ###Markdown
Demo Read in data First we need to read in our data set which can be found in ______. To read the information from the file, we will need to enlist the help of pandas. Using pandas, you can read files from both local files and the internet! Pretty neat, right? Let's import that now.
###Code
# For reading data sets
import pandas
###Output
_____no_output_____
###Markdown
We want to be able to save this information in a way that is organized like the original data set. An array will suffice, with each row representing an individual student and each column representing an individual feature (like school and final grade). Numpy provides us with a way to create such an array and more functionality that will prove to be quite useful in our endeavors. Let's import that too.
###Code
# For lots of awesome things
import numpy as np
###Output
_____no_output_____
###Markdown
Now it's time to read in the data! We're going to save it in an array called "student_data." We need to tell pandas the file we want to read from, how the information is seperated, or delimited, (it's seperated by semicolons ";") and if there is a header, which there is. If you look at the file, you will see that the first row, row 0, tells us what can be found in each column
###Code
# Read in student data
student_data = np.array(pandas.read_table("./student-por.csv",
delimiter=";", header=0))
# Display student data
student_data
###Output
_____no_output_____
###Markdown
Later, we will need to know what each feature(column) represents. Let's import those descriptions now. We only need to read in one row but we need to let pandas know not to ignore the header.
###Code
# Descriptions for each feature (found in the header)
feature_descrips = np.array(pandas.read_csv("./student-por.csv",
delimiter=";", header=None, nrows=1))
# Display descriptions
print(feature_descrips)
###Output
_____no_output_____
###Markdown
Hm..those descripriptions aren't very specific. Let's store some more detailed information. These descriptions were constructed using the description of attributes in Table 1 of Cortez and Silva's report.
###Code
# More detailed descriptions
feature_descrips = np.array(["School", "Sex", "Age", "Urban or Rural Address", "Family Size",
"Parent's Cohabitation status", "Mother's Education", "Father's Education",
"Mother's Job", "Father's Job", "Reason for Choosing School",
"Student's Gaurdain", "Home to School Travel Time", "Weekly Study Time",
"Number of Past Class Failures", "Extra Educational Support",
"Family Educational Support", "Extra Paid Classes", "Extra Curricular Activities",
"Attended Nursery School", "Wants to Take Higher Education", "Internet Access at Home",
"In a Romantic Relationship", "Quality of Family Relationships",
"Free Time After School", "Time Spent Going out With Friends",
"Workday Alcohol Consumption", "Weekend Alcohol Consumption",
"Current Health Status", "Number of Student Absences", "First Period Grade",
"Second Period Grade", "Final Grade"])
###Output
_____no_output_____
###Markdown
Data Cleanup Woohoo! Now we have all the information we need. Don't get too excited, though. We can't start building and training our neural net yet. We need to tidy up the data to make it easier for our net to learn. Shuffle data The data is split by school, meaning all the students represented in the first part of this data set went to one school (GP - Gabriel Pereira ) and the rest went to another (MS - Mousinho da Silveira). This isn't ideal. We want our network to see student data from both schools and don't want it to get used to only seeing one. Let's shuffle the data. I told you numpy would come in handy again...
###Code
# Shuffle the data!
np.random.shuffle(student_data)
student_data
###Output
_____no_output_____
###Markdown
Numerically Classify Scores Now we're going to classify the grades. Currently, each student has a final frade between 0 and 19, inclusive. We're going to classify them like letter grades, with 4 representing an A and 0 represeting an F
###Code
# Array holding final scores for every student
scores = student_data[:,32]
# Iterate through list of scores, changing them from a 0-19 value
## to a 0-4 value (representing F-A)
for i in range(len(scores)):
if(scores[i] > 18):
scores[i] = 4
elif(scores[i] > 16):
scores[i] = 3
elif(scores[i] > 14):
scores[i] = 2
elif(scores[i] > 12):
scores[i] = 1
else:
scores[i] = 0
# Update the final scores in student_data to reflect these changes
for i in range(len(scores)):
student_data[i,32] = scores[i]
# Display new data. Hint: Look at the last column
student_data
###Output
_____no_output_____
###Markdown
Encoding Non-Numeric Data to Integers Let's take a look at a student sample from our data set.
###Code
# one student sample
student_data[0,:]
###Output
_____no_output_____
###Markdown
As you can see, several of our features have string values that don't mean much to our neural net. Let's encode these labels into integers using with sklearn's Label Encoder.
###Code
# Need this for LabelEncoder
from sklearn import preprocessing
# Label Encoder
le = preprocessing.LabelEncoder()
# Columns that hold non-numeric data
indices = np.array([0,1,3,4,5,8,9,10,11,15,16,17,18,19,20,21,22])
# Transform the non-numeric data in these columns to integers
for i in range(len(indices)):
column = indices[i]
le.fit(student_data[:,column])
student_data[:,column] = le.transform(student_data[:,column])
###Output
_____no_output_____
###Markdown
Let's take a look at what that student sample looks like now.
###Code
student_data[0,:]
###Output
_____no_output_____
###Markdown
Encoding 0's to -1 for Binomial Data Perfect, right? Well, not quite. When a neural net sees a feature has a value of 0, it takes it as there is no value which in turn will cause the weights (what drives our neural net) to not turn on. Let's fix that by changing the zeros in the binomial data to -1's.
###Code
# Columns that hold binomial data
indices = np.array([0,1,3,4,5,15,16,17,18,19,20,21,22])
# Change 0's to -1's
for i in range(len(indices)):
column = indices[i]
# values of current feature
feature = student_data[:,column]
# change values to -1 if equal to 0
feature = np.where(feature==0, -1, feature)
student_data[:,column] = feature
student_data[0,:]
###Output
_____no_output_____
###Markdown
Standardizing Nominal and Numerical Data We need our input to matter equally (Everyone is important!). We do this by standardizing our data (get a mean of 0 and a stardard deviation of 1).
###Code
scaler = preprocessing.StandardScaler()
temp = student_data[:,[2,6,7,8,9,10,11,12,13,14,23,24,25,26,27,28,29,30,31]]
print(student_data[0,:])
Standardized = scaler.fit_transform(temp)
print('Mean:', round(Standardized.mean()))
print('Standard deviation:', Standardized.std())
student_data[:,[2,6,7,8,9,10,11,12,13,14,23,24,25,26,27,28,29,30,31]] = Standardized
student_data[0,:]
###Output
_____no_output_____
###Markdown
One-Hot Encode Results Our results are currently floating point numbers. We want to categorize them so the net views them as seperate values (or grades). To do this, we will one-hot encode them. This means that each grade will have an array of all zeroes except for one element, which will be a 1. This is kind of like the grade's ID. So for examples, F would be 10000 and D would be 01000. There are 5 unique grades [A-F] so there are 5 digits in each "ID."
###Code
# Final grades
results = student_data[:,32]
# Take a look at first 5 final grades
print("First 5 final grades:", results[0:5])
# All unique values for final grades (0-4 representing F-A)
possible_results = np.unique(student_data[:,32]).T
print("All possible results:", possible_results)
###Output
_____no_output_____
###Markdown
Keras has an awesome built-in function that allows us to categorize the results in such a way. Keras is the library we will be using to build our network. Let's import it now so we can take advantage of its wonderful functionality.
###Code
# For building our net
import keras
# One-hot encode final grades (results) which will be used as our output
# The length of the "ID" should be as long as the total number of possible results so each results
## gets its own, personal one-hot encoding
y = keras.utils.to_categorical(results,len(possible_results))
# Take a look at the first 5 final grades now (no longer numbers but arrays)
y[0:5]
###Output
_____no_output_____
###Markdown
We set these categorized results equal to y because this is the -output- of our neural net which is intaking all features except the final grade. We shall call the set of these -inputs- x.
###Code
# Our input, all features except final grades
x = student_data[:,0:32]
###Output
_____no_output_____
###Markdown
Model Building Now let's create a function that will build a model for us. This will come in handy later on. Our model will have two hidden layers. The first hidden layer will have an input size of 800, and the second will have an input size of 400. The optimizer that we are using is adamax which is good at ignoring noise in a datset. The loss function we are using is called categorical cross entropy and which is useful for trying to classify or label something. In this case, we are trying to classify students by letter grades, so this loss function will be of great use to us.
###Code
# Function to create network given model
def create_network(model):
# Specify input/output size
input_size = x.shape[1]
output_size = y.shape[1]
# Creeate the hidden layer
model.add(keras.layers.Dense(800, input_dim = input_size, activation = 'relu'))
# Additional hidden layer
model.add(keras.layers.Dense(400,activation='relu'))
# Output layer
model.add(keras.layers.Dense(output_size,activation='softmax'))
# Compile - why using adamax?
model.compile(loss='categorical_crossentropy',
optimizer='adamax',
metrics=['accuracy'])
###Output
_____no_output_____
###Markdown
Now we can create a basic model and have that function build the network for us.
###Code
# Feed-forward model
model = keras.Sequential()
create_network(model)
model.summary()
###Output
_____no_output_____
###Markdown
Initial Test of the Network The initial model and its weights are included in the demo. We can import this model and the weights easily and skip the training. Before that we have to import some things that will be needed to load the model.
###Code
from keras.models import model_from_json
from keras.models import Sequential
from keras.layers import Dense
import os
# We have to import the model first
model_file = open('./initial_model.json','r')
model_json = model_file.read()
model_file.close()
loaded_model = model_from_json(model_json)
# After the model is imported we can import the weights
loaded_model.load_weights("initial_model_weights.h5")
loaded_model.compile(loss='binary_crossentropy',optimizer='adamax',metrics=['accuracy'])
print("Model is loaded and ready")
loaded_model.summary()
###Output
_____no_output_____
###Markdown
Now let's see what this net can do! Before we do that, though, we need to split our data into to groups: one for training (our network will see this data and "learn" it) and one for testing. The testing data is data the network hasn't seen before. Once we're done training, we'll feed it the the trained network and see how well it outputs what it is supposed to. 20% of the 649 individual student statistics (approximately 130) will be designated to the testng data group.
###Code
# Split data into training and testing data
x_train = x[0:518,:]
x_test = x[519:649,:]
y_train = y[0:518,:]
y_test = y[519:649,:]
score = loaded_model.evaluate(x_test,y_test,verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
###Output
_____no_output_____
###Markdown
To train our neural network, we're going to use the fit() member function which we can access through the model we created. There are certain things we need to specify. - First we need to tell the model that it will fed the training input and should produce the training output. -Then we need to specify the batch size. In this case, it's 32 (the default value for batch size). This means the net will go through 32 samples before it updates any of the weights that drive it. - The number of epochs describes how many times we want the net to see all samples of our data. Our net will run through all of our data 7 times. - We set verbose to 0 because we don't care too much about the accuracy and loss rates at each epoch nor how long it takes for each epoch to run. We're concerned only about the end result so we're going to opt out of this. - Finally we have the validation split which is set to 0.2 (20%). This means 20% of the training data will actually be used for validation instead of training. The model sees and learns from the initial 80% of the data and then uses the validation data to get used to seeing new things and being able to recognize them (generalization).
###Code
# Train on training data!
# We're saving this information in the variable -history- so we can take a look at it later
history = model.fit(x_train, y_train,
batch_size = 32,
epochs = 7,
verbose = 0,
validation_split = 0.2)
###Output
_____no_output_____
###Markdown
Now it's time to see how the neural net performs on our testing data (the data it has never seen before). We're going to use the -evaluate- function to do this.
###Code
# Validate using data the network hasn't seen before (testing data)
# Save this info in -score- so we can take a look at it
score = model.evaluate(x_test,y_test, verbose=0)
# Check it's effectiveness
print('Test loss:', score[0])
print('Test accuracy:', score[1])
###Output
_____no_output_____
###Markdown
It'd be nice to see a more visual representation of how our training went, don't you think? Let's make a plot to do just that. Since we're going to be doing this several times, we're going to create a function that takes in the history of model training and plots the training accuracy and loss (shown in blue) and the validation accuracy and loss (shown in orange). Too plot, we're going to need to inport matplotlib.pyplot.
###Code
import matplotlib.pyplot as plt
%matplotlib inline
# Plot the data
def plot(history):
plt.figure(1)
# Summarize history for accuracy
plt.subplot(211)
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train','test'], loc ='upper left')
# Summarize history for loss
plt.subplot(212)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train','test'], loc ='upper left')
# Display plot
plt.tight_layout()
plt.show()
###Output
_____no_output_____
###Markdown
Let's put this function to good use and plot the current training and validation info that is stored in -history-
###Code
# Plot current training and validation accuracy and loss
plot(history)
###Output
_____no_output_____
###Markdown
Training and Testing Without Individual Features A few questions now come to mind. Are all of these features important? Would removing unimportant ones improve accuracy? What features are most essential to maintaining a good accuracy? To answer these questions, we're going to try trainining the network with all featues except one. Since we're going to be doing this for 32 features, let's make a general function we can call that takes the index of the feature we want to remove and trains the network with all the features except that one.
###Code
# Analyze the effects of removing one feature on training
def remove_and_analyze(feature):
# Told you those feature descriptions would be useful
print("Without feature", feature, ":", feature_descrips[feature])
# Create feed-forward network
model = keras.Sequential()
create_network(model)
# Remove feature from columns (axis 1)
x = np.delete(student_data, feature, axis = 1)
# Split data into training and testing data
x_train = x[0:518,:]
x_test = x[519:649,:]
# Train on training data!
history = model.fit(x_train, y_train,
batch_size = 32,
epochs = 7,
verbose = 0,
validation_split = 0.2)
# Validate using data the network hasn't seen before (testing data)
score = model.evaluate(x_test,y_test, verbose=0)
# Check it's effectiveness
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Plot the data
plot(history)
student_data.shape[1]
###Output
_____no_output_____
###Markdown
Now we'll run this function 32 times (once for each feature).
###Code
# Analyze the effects of removing one feature on training
# Do this for all input features
for i in range(student_data.shape[1]-1):
remove_and_analyze(i)
print("\n \n \n")
###Output
_____no_output_____
###Markdown
Training and Testing Without Five Features We found that the removal of these five features individually produced results with better accuracy: 1) Internet access at home 2) Wants to take higher education 3) Father's job 4) Mother's job 5) Father's education. If removing them one at a time improves accuracy, what would happen if we removed them all at once? Let's try it. Imported Model The final model and its weights are included in the demo. We can import this model and the weights easily and skip the training.
###Code
# We have to import the model first
model_file = open('model.json','r')
model_json = model_file.read()
model_file.close()
loaded_model = model_from_json(model_json)
# After the model is imported we can import the weights
loaded_model.load_weights("model.h5")
loaded_model.compile(loss='binary_crossentropy',optimizer='adamax',metrics=['accuracy'])
print("Model is loaded and ready")
loaded_model.summary()
###Output
_____no_output_____
###Markdown
Now let's see how the imported model performs.
###Code
# Delete the five features that most negatively impact accuracy
x = np.delete(student_data, 21, axis = 1)
x = np.delete(x, 20, axis = 1)
x = np.delete(x, 9, axis = 1)
x = np.delete(x, 8, axis = 1)
x = np.delete(x, 7, axis = 1)
# Create test data
x_test = x[519:649,:]
y.shape
score = loaded_model.evaluate(x_test,y_test,verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
print('Test loss:', score[0])
###Output
_____no_output_____
###Markdown
Grade Distribution Analysis Wow! That's a lot better! Our accuracy increased from 80% to 97.08%. We did this by removing the five features which negatively impacted the accuracy of our net. What about the features that were most beneficial in obtaining a good accuracy? In other words, the removal of which features caused the accuracy rate to decrease? The original study by Cortez and Silva had come to the conclusion that previous grades had the most impact on predicting student performance. However, our goal is not solely to predict student performance but to better understand how non-academic features affect it. The five non-academic features that had the most beneficial effect on our neural net are: 1) Family educational support 2) Reason for choosing school 3) Frequency of going out with friends 4) Amount of free time after school 5) Access to extra paid classes How do we intend to do that? For each feature, we'll seperate student samples into groups according to the value of the featue they exhibit. For example, for the feature "family educational support," we'll divide the student samples according to whether the student has this support or not. We'll only save the final grades since grade distribution is what we'll be analyzing. Let's create a function that takes in an array of final grades (pertaining to students that exhibit a specific value of a feature) and prints a bar graph which displays what percentage of students received F's, D's, C's, B's, or A's.
###Code
# Function for analyzing the percent of students with each grade [F,D,C,B,A]
def analyze(array):
# To hold the total number of students with a certain final grade
# Index 0 - F. Index 4 - A
sums = np.array([0,0,0,0,0])
# Iterate through array. Update sums according to whether a student got a final grade of a(n)
for i in range(len(array)):
# F
if(array[i]==0):
sums[0] += 1
# D
elif(array[i]==1):
sums[1] +=1
# C
elif(array[i]==2):
sums[2] +=1
# B
elif(array[i]==3):
sums[3] +=1
# A
else:
sums[4] += 1
# Total number of students
total = sums[0] + sums[1] + sums[2] + sums[3] + sums[4]
# Hold percentage of students with grade of [F,D,C,B,A]
percentages = np.array([sums[0]/total*100,
sums[1]/total*100,
sums[2]/total*100,
sums[3]/total*100,
sums[4]/total*100])
# One bar for each of the 5 grades
x = np.array([1,2,3,4,5])
# Descriptions for each bar. None on y-axis
plt.xticks(np.arange(6), ('', 'F', 'D', 'C', 'B','A'))
# X axis - grades. Y axis - percentage of students with each grade
plt.bar(x,percentages)
plt.xlabel("Grades")
plt.ylabel("Percentage of Students")
# Display bar graph
plt.show()
# Display percentages
print(percentages)
###Output
_____no_output_____
###Markdown
Now let's analyze the distribution of grades among our top five non-academic features! Family Educational Support First, let's create the arrays we want to analyze. One with the final grades of students who do have family educational support and one with the final grades of students that don't.
###Code
# Array holding final grades of all students who have family educational support
fam_sup = []
# Array holding final grades of all students who have family educational support
no_fam_sup = []
# Iterate through all student samples
for i in range(student_data.shape[0]):
# Does the student have family educational support? (-1 no, 1 yes)
sup = student_data[i][16]
# Append student's final grade to corresponding array
if(sup==1):
fam_sup.append(student_data[i][32])
else:
no_fam_sup.append(student_data[i][32])
###Output
_____no_output_____
###Markdown
Analyze! Family Educational Support
###Code
analyze(fam_sup)
###Output
_____no_output_____
###Markdown
No Family Educational Support
###Code
analyze(no_fam_sup)
###Output
_____no_output_____
###Markdown
Surprisingly, there is not much of a difference in the distribution. Among students with family educational support, the amount of students who got an F was 2% less than among students without this support. However, this 2% seemed to float into the D-range. This does show that the support might prove helpful to some students but it is not as crucial to grade distribution overall. It's imporant to note that only 2 students in the entire date set achieved a final grade of an A. We're going to take a similar approach for the next four features. Reason for choosing school
###Code
# Each array holds the grades of students who chose to go to their school for that reason
# Close to home
reason1 = []
# School reputation
reason2 = []
# Course prefrence
reason3 = []
# Other
reason4 = []
# Values that represent these unique reasons. They are not integer numbers like in the previous
## example. They're floatig point numbers so we'll save them so we can compare them to the value
## of this feature in each sample
unique_reasons = np.unique(student_data[:,10])
# Iterate through all student samples and append final grades to corresponding arrays
for i in range(student_data.shape[0]):
reason = student_data[i][10]
if(reason==unique_reasons[0]):
reason1.append(student_data[i][32])
elif(reason==unique_reasons[1]):
reason2.append(student_data[i][32])
elif(reason==unique_reasons[2]):
reason3.append(student_data[i][32])
else:
reason4.append(student_data[i][32])
###Output
_____no_output_____
###Markdown
Reason 1: Close to Home
###Code
analyze(reason1)
###Output
_____no_output_____
###Markdown
Reason 2: School Reputation
###Code
analyze(reason2)
###Output
_____no_output_____
###Markdown
Reason 3: Course Prefrence
###Code
analyze(reason3)
###Output
_____no_output_____
###Markdown
Reason 4: Other
###Code
analyze(reason4)
###Output
_____no_output_____
###Markdown
By far, the worst distribution of grades pertains to the students who chose their school based on course prefrence. Why could this be? Perhaps these students want to go to a school with supposedly easier classes and therefore are less motivated to perform better. Or perhaps they chose easier classes because they struggle academically. Either way, this is interesting because you would think that giving students the choice to choose their school based on the courses offered would motivate them to perform better. The next worst distribution belongs to the students who chose this school because it is close to home. This could be because there was no academic motivation behind this reason or maybe the student had no means of transportation to go to another school which opens up the possibility of other factors that could affect student performance. School reputation had a much more gradual distribution but by far students who chose a reason other than the aforementioned features did by far the best. They had the lowest percentage of F's and the highest percentage of C's and B's. One student got an A. The other student that got an A based their selection of school reputation. This begs the questions, why did these students pick their school and why do they seem to do so much better? Frequency of Going Out With Friends
###Code
# Each array holds the grades of students who go out with friends for that specified amount of time
# (1 - very low, 5 - very high)
go_out1 = []
go_out2 = []
go_out3 = []
go_out4 = []
go_out5 = []
# Floating point values representing frequency
unique = np.unique(student_data[:,25])
# Iterate through all student samples and append final grades to corresponding arrays
for i in range(student_data.shape[0]):
frequency = student_data[i][25]
if(frequency==unique[0]):
go_out1.append(student_data[i][32])
elif(frequency==unique[1]):
go_out2.append(student_data[i][32])
elif(frequency==unique[2]):
go_out3.append(student_data[i][32])
elif(frequency==unique[3]):
go_out4.append(student_data[i][32])
else:
go_out5.append(student_data[i][32])
analyze(go_out1)
analyze(go_out2)
analyze(go_out3)
analyze(go_out4)
analyze(go_out5)
###Output
_____no_output_____
###Markdown
From these results, we can see that it is important for students to spend some time with friends. Those who minimally went out with friends did the worst academically. None of them got B's or A's and 95.8% of them either got an F or a D. However, students with the most amount of time spent going out had the highest percentage of F's (66.4%) By far, the students who did the best ranked the amount of time spent going out with friends at a 2 (low). Grade distributions got worse as the amount of time students spent going out with friends increased. This shows that social activity is important for student success but it should be limited. The time these students are not spending going out is probably spent preparing for school. Free Time after School
###Code
# Each array holds the grades of students who have the specified amount of free time after school
# (1 - very low, 5 - very high)
free1 = []
free2 = []
free3 = []
free4 = []
free5 = []
# Floating point values representing frequency
unique = np.unique(student_data[:,24])
# Iterate through all student samples and append final grades to corresponding arrays
for i in range(student_data.shape[0]):
frequency = student_data[i][24]
if(frequency==unique[0]):
free1.append(student_data[i][32])
elif(frequency==unique[1]):
free2.append(student_data[i][32])
elif(frequency==unique[2]):
free3.append(student_data[i][32])
elif(frequency==unique[3]):
free4.append(student_data[i][32])
else:
free5.append(student_data[i][32])
analyze(free1)
analyze(free2)
analyze(free3)
analyze(free4)
analyze(free5)
###Output
_____no_output_____
###Markdown
Interesting...our results are very similar to that of our previous example. Overall, those with the least amount of free time did the worst but those with the most had the highest percentage of students with an F (67.6...very close to the previous 66.4). Those who did the best had the second-least amount of free time and performace seems to decreaese from there. There seems to be a sort of "sweet-spot" when it comes to free time and going out with friends. Extra Paid Classes Last feature to analyze...how sad this is coming to an end.
###Code
# Array holding final grades of all students who have extra paid classes
paid_class = []
# Array holding final grades of all students who do not have extra paid classes
no_paid_class = []
# Iterate through all student samples and append final grades to corresponding arrays
for i in range(student_data.shape[0]):
paid = student_data[i][17]
if(paid==1):
paid_class.append(student_data[i][32])
else:
no_paid_class.append(student_data[i][32])
###Output
_____no_output_____
###Markdown
Extra Paid Classes
###Code
analyze(paid_class)
###Output
_____no_output_____
###Markdown
No Extra Paid Classes
###Code
analyze(no_paid_class)
###Output
_____no_output_____ |
Code_2.ipynb | ###Markdown
###Code
import gc
gc.collect()
# The new data set (Movie Dialogues)
!wget http://www.cs.cornell.edu/~cristian/data/cornell_movie_dialogs_corpus.zip
!unzip cornell_movie_dialogs_corpus.zip -d dataset
!pip install chatterbot
!pip install chatterbot-corpus
!pip install requests
!pip install chatterbot
!pip install argparse
import os
import requests
import time
import argparse
import os
import json
from requests.compat import urljoin
import gensim
from chatterbot import ChatBot
from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import re
import nltk
import sklearn
from sklearn.model_selection import train_test_split
#import train_test_splitnltk.download("stopwords")
from nltk.corpus import stopwords
from sklearn.multiclass import OneVsRestClassifier
import gensim
import pickle
import re
import nltk
from nltk.corpus import stopwords
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances_argmin
!wget -c "https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz"
!gunzip GoogleNews-vectors-negative300.bin.gz
import gensim
import pickle
import re
import nltk
from nltk.corpus import stopwords
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances_argminpi
# We will need this function to prepare text at prediction time
def text_prepare(text):
"""Performs tokenization and simple preprocessing."""
replace_by_space_re = re.compile('[/(){}\[\]\|@,;]')
bad_symbols_re = re.compile('[^0-9a-z #+_]')
stopwords_set = set(stopwords.words('english'))
text = text.lower()
text = replace_by_space_re.sub(' ', text)
text = bad_symbols_re.sub('', text)
text = ' '.join([x for x in text.split() if x and x not in stopwords_set])
return text.strip()
# need this to convert questions asked by user to vectors
def question_to_vec(question, embeddings, dim=300os):
"""
question: a string
embeddings: dict where the key is a word and a value is its' embedding
dim: size of the representation
result: vector representation for the question
"""
word_tokens = question.split(" ")
question_len = len(word_tokens)
question_mat = np.zeros((question_len,dim), dtype = np.float32)
for idx, word in enumerate(word_tokens):
if word in embeddings:
question_mat[idx,:] = embeddings[word]
# remove zero-rows which stand for OOV words
question_mat = question_mat[~np.all(question_mat == 0, axis = 1)]
# Compute the mean of each word along the sentence
if question_mat.shape[0] > 0:
vec = np.array(np.mean(question_mat, axis = 0), dtype = np.float32).reshape((1,dim))
else:
vec = np.zeros((1,dim), dtype = np.float32)
return vec
class SimpleDialogueManager_2(object):
"""
This is a simple dialogue manager to test the telegram bot.
The main part of our bot will be written here.
"""
def __init__(self):
# Instantiate all the models and TFIDF Objects.
print("Loading resources...")
# Instantiate a Chatterbot for Chitchat type questions
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
chatbot = ChatBot('MLWhizChatterbot')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')
self.chitchat_bot = chatbot
print("Loading Word2vec model...")
# Instantiate the Google's pre-trained Word2Vec model.
self.model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
print("Loading Classifier objects...")
# Load the intent classifier and tag classifier
self.intent_recognizer = pickle.load(open('resources/intent_clf.pkl', 'rb'))
self.tag_classifier = pickle.load(open('resources/tag_clf.pkl', 'rb'))
# Load the TFIDF vectorizer object
self.tfidf_vectorizer = pickle.load(open('resources/tfidf.pkl', 'rb'))
print("Finished Loading Resources")
# We created this function just above. We just need to have a function to get most similar question's *post id* in the dataset given we know the programming Language of the question. Here it is:
def get_similar_question(self,question,tag):
# get the path where all question embeddings are kept and load the post_ids and post_embeddings
embeddings_path = 'resources/embeddings_folder/' + tag + ".pkl"
post_ids, post_embeddings = pickle.load(open(embeddings_path, 'rb'))
# Get the embeddings for the question
question_vec = question_to_vec(question, self.model, 300)
# find index of most similar post
best_post_index = pairwise_distances_argmin(question_vec,
post_embeddings)
# return best post id
return post_ids[best_post_index]
def generate_answer(self, question):
prepared_question = text_prepare(question)
features = self.tfidf_vectorizer.transform([prepared_question])
# find intent
intent = self.intent_recognizer.predict(features)[0]
# Chit-chat part:
if intent == 'dialogue':
response = self.chitchat_bot.get_response(question)
# Stack Overflow Question
else:
# find programming language
tag = self.tag_classifier.predict(features)[0]
# find most similar question post id
post_id = self.get_similar_question(question,tag)[0]
# respond with
response = 'I think its about %s\nThis thread might help you: https://stackoverflow.com/questions/%s' % (tag, post_id)
return response
class BotHandler(object):
"""
BotHandler is a class which implements all back-end of the bot.
It has three main functions:
'get_updates' — checks for new messages
'send_message' – posts new message to user
'get_answer' — computes the most relevant on a user's question
"""
def __init__(self, token, dialogue_manager):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
self.dialogue_manager = dialogue_manager
def get_updates(self, offset=None, timeout=30):
params = {"timeout": timeout, "offset": offset}
raw_resp = requests.get(urljoin(self.api_url, "getUpdates"), params)
try:
resp = raw_resp.json()
except json.decoder.JSONDecodeError as e:
print("Failed to parse response {}: {}.".format(raw_resp.content, e))
return []
if "result" not in resp:
return []
return resp["result"]
def send_message(self, chat_id, text):
params = {"chat_id": chat_id, "text": text}
return requests.post(urljoin(self.api_url, "sendMessage"), params)
def get_answer(self, question):
if question == '/start':
return "Hi, I am your project bot. How can I help you today?"
return self.dialogue_manager.generate_answer(question)
def is_unicode(text):
return len(text) == len(text.encode())
# class SimpleDialogueManager(object):
# """
# This is a simple dialogue manager to test the telegram bot.
# The main part of our bot will be written here.
# """
# def generate_answer(self, question):
# if "Hi" in question:
# return "Hello, You"
# else:
# return "Don't be rude. Say Hi first."
def main():
# Put your own Telegram Access token here...
token = '828781554:AAEE4sdEf04fZwldjg_mW_8jB7hM8__nuXc'
simple_manager = SimpleDialogueManager_2()
bot = BotHandler(token, simple_manager)
###############################################################
print("Ready to talk!")
offset = 0
while True:
updates = bot.get_updates(offset=offset)
for update in updates:
print("An update received.")
if "message" in update:
chat_id = update["message"]["chat"]["id"]
if "text" in update["message"]:
text = update["message"]["text"]
if is_unicode(text):
print("Update content: {}".format(update))
bot.send_message(chat_id, bot.get_answer(update["message"]["text"]))
else:
bot.send_message(chat_id, "Hmm, you are sending some weird characters to me...")
offset = max(offset, update['update_id'] + 1)
time.sleep(1)
if __name__ == "__main__":
main()
class SimpleDialogueManager(object):
"""
This is a simple dialogue manager to test the telegram bot.
The main part of our bot will be written here.
"""
def __init__(self):
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
chatbot = ChatBot('MLWhizChatterbot')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')
self.chitchat_bot = chatbot
def generate_answer(self, question):
response = self.chitchat_bot.get_response(question)
return response
!wget https://github.com/MLWhiz/chatbot/raw/master/data.zip
!unzip data.zip -d data
#os.rmdir('data')
dialogues = pd.read_csv("data/data/dialogues.tsv",sep="\t")
posts = pd.read_csv("data/data/tagged_posts.tsv",sep="\t")
dialogues.head()
dialogues.head()
import nltk
nltk.download('stopwords')
texts = list(dialogues[:200000].text.values) + list(posts[:200000].title.values)
labels = ['dialogue']*200000 + ['stackoverflow']*200000
data = pd.DataFrame({'text':texts,'target':labels})
def text_prepare(text):
"""Performs tokenization and simple preprocessing."""
replace_by_space_re = re.compile('[/(){}\[\]\|@,;]')
bad_symbols_re = re.compile('[^0-9a-z #+_]')
stopwords_set = set(stopwords.words('english'))
text = text.lower()
text = replace_by_space_re.sub(' ', text)
text = bad_symbols_re.sub('', text)
text = ' '.join([x for x in text.split() if x and x not in stopwords_set])
return text.strip()
# Doing some data cleaning
data['text'] = data['text'].apply(lambda x : text_prepare(x))
X_train, X_test, y_train, y_test = train_test_split(data['text'],data['target'],test_size = .1 , random_state=0)
print('Train size = {}, test size = {}'.format(len(X_train), len(X_test)))
# We will keep our models and vectorizers in this folder
def tfidf_features(X_train, X_test, vectorizer_path):
"""Performs TF-IDF transformation and dumps the model."""
tfv = TfidfVectorizer(dtype=np.float32, min_df=3, max_features=None,
strip_accents='unicode', analyzer='word',token_pattern=r'\w{1,}',
ngram_range=(1, 3), use_idf=1,smooth_idf=1,sublinear_tf=1,
stop_words = 'english')
X_train = tfv.fit_transform(X_train)
X_test = tfv.transform(X_test)
pickle.dump(tfv,vectorizer_path)
return X_train, X_test
os.mkdir('resources')
X_train_tfidf, X_test_tfidf = tfidf_features(X_train, X_test, open("resources/tfidf.pkl",'wb'))
intent_recognizer = LogisticRegression(C=10,random_state=0)
intent_recognizer.fit(X_train_tfidf,y_train)
pickle.dump(intent_recognizer, open("resources/intent_clf.pkl" , 'wb'))
# Check test accuracy.
y_test_pred = intent_recognizer.predict(X_test_tfidf)
test_accuracy = accuracy_score(y_test, y_test_pred)
print('Test accuracy = {}'.format(test_accuracy))
# creating the data for Programming Language classifier
X = posts['title'].values
y = posts['tag'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
print('Train size = {}, test size = {}'.format(len(X_train), len(X_test)))
os.mkdir('resources')
vectorizer = pickle.load(open("resources/tfidf.pkl", 'rb'))
X_train_tfidf, X_test_tfidf = vectorizer.transform(X_train), vectorizer.transform(X_test)
tag_classifier = OneVsRestClassifier(LogisticRegression(C=5,random_state=0))
tag_classifier.fit(X_train_tfidf,y_train)
pickle.dump(tag_classifier, open("resources/tag_clf.pkl", 'wb'))
# Check test accuracy.
y_test_pred = tag_classifier.predict(X_test_tfidf)
test_accuracy = accuracy_score(y_test, y_test_pred)
print('Test accuracy = {}'.format(test_accuracy))
# Load Google's pre-trained Word2Vec model.
#model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
#!wget -c "https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz"
pretrained_embeddings_path = "https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz"
model = gensim.models.KeyedVectors.load_word2vec_format(pretrained_embeddings_path,binary=True)
# from gensim import models
# w = models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True)
def question_to_vec(question, embeddings, dim=300):
"""
question: a string
embeddings: dict where the key is a word and a value is its' embedding
dim: size of the representation
result: vector representation for the question
"""
word_tokens = question.split(" ")
question_len = len(word_tokens)
question_mat = np.zeros((question_len,dim), dtype = np.float32)
for idx, word in enumerate(word_tokens):
if word in embeddings:
question_mat[idx,:] = embeddings[word]
# remove zero-rows which stand for OOV words
question_mat = question_mat[~np.all(question_mat == 0, axis = 1)]
# Compute the mean of each word along the sentence
if question_mat.shape[0] > 0:
vec = np.array(np.mean(question_mat, axis = 0), dtype = np.float32).reshape((1,dim))
else:
vec = np.zeros((1,dim), dtype = np.float32)
return vec
counts_by_tag = posts.groupby(by=['tag'])["tag"].count().reset_index(name = 'count').sort_values(['count'], ascending = False)
counts_by_tag = list(zip(counts_by_tag['tag'],counts_by_tag['count']))
print(counts_by_tag)
# import os
os.mkdir('resources/embeddings_folder')
for tag, count in counts_by_tag:
tag_posts = posts[posts['tag'] == tag]
tag_posts
tag_post_ids = tag_posts['post_id'].values
tag_vectors = np.zeros((count, 300), dtype=np.float32)
for i, title in enumerate(tag_posts['title']):
tag_vectors[i, :] = question_to_vec(title, model, 300)
# Dump post ids and vectors to a file.
filename = 'resources/embeddings_folder/'+ tag + '.pkl'
pickle.dump((tag_post_ids, tag_vectors), open(filename, 'wb'))
from sklearn.metrics.pairwise import pairwise_distances_argmin
def get_similar_question(question,tag):
# get the path where all question embeddings are kept and load the post_ids and post_embeddings
embeddings_path = 'resources/embeddings_folder/' + tag + ".pkl"
post_ids, post_embeddings = pickle.load(open(embeddings_path, 'rb'))
# Get the embeddings for the question
question_vec = question_to_vec(question, model, 300)
# find index of most similar post
best_post_index = pairwise_distances_argmin(question_vec,
post_embeddings)
# return best post id
return post_ids[best_post_index]
get_similar_question("how to use list comprehension in python?",'python')
!pip install chatterbot
!pip install chatterbot-corpus
!pip install requests
!pip install chatterbot
!pip install argparse
import chatterbot
from chatterbot import ChatBot
import os
import requests
import time
import argparse
import os
import json
from requests.compat import urljoin
import gensim
from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import re
import nltk
import sklearn
from sklearn.model_selection import train_test_split
#import train_test_splitnltk.download("stopwords")
from nltk.corpus import stopwords
from sklearn.multiclass import OneVsRestClassifier
import chatterbot
from chatterbot import ChatBot
import nltk
#nltk.download('stopwords')
import gensim
import pickle
import re
import nltk
from nltk.corpus import stopwords
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances_argmin
!wget -c http://www.cs.cmu.edu/~ark/QA-data/data/Question_Answer_Dataset_v1.2.tar.gz
import pandas as pd
df = pd.read_csv('Question_Answer_Dataset_v1.2.tar.gz', compression='gzip', header=0, sep='\t', quotechar='"', error_bad_lines=False, encoding='latin-1')
#pd.read_csv('u.item', sep='|', names=m_cols , encoding='latin-1')
df = df[['Question','Answer']]
x = len(df)
###Output
_____no_output_____
###Markdown
###Code
import numpy as np
q_a_pairs= []
for i in range(x):
if ((df['Question'][i] is not np.nan) and ((df['Answer'][i]) is not np.nan)):
q_a_pairs.append(df['Question'][i])
q_a_pairs.append(df['Answer'][i])
!wget -c https://download.microsoft.com/download/E/5/F/E5FCFCEE-7005-4814-853D-DAA7C66507E0/WikiQACorpus.zip
!unzip WikiQACorpus.zip
import pandas as pd
df = pd.read_csv('WikiQACorpus/WikiQA-train.tsv', sep = '\t')
df.head()
import numpy as np
y = len(df)
q_a_pairs_2= []
for i in range(y):
if ((df['Question'][i] is not np.nan) and ((df['Sentence'][i]) is not np.nan)):
q_a_pairs_2.append(df['Question'][i])
q_a_pairs_2.append(df['Sentence'][i])
q_a_pairs_2
!wget -c http://www.cs.cornell.edu/~cristian/data/cornell_movie_dialogs_corpus.zip
!unzip cornell_movie_dialogs_corpus.zip
import pickle
with open('movie_titles_metadata.txt', 'r', encoding = "ISO-8859-1") as movies:
rom_movies = []
for movie in movies:
parsed_movie = movie.split('+++$+++')
if 'romance' in parsed_movie[-1]:
rom_movies.append(parsed_movie[0].strip())
print(rom_movies)
with open('movie_lines.txt', 'r', encoding = "ISO-8859-1") as lines:
rom_parsed_lines = []
other_parsed_lines = []
for line in lines:
parsed_line = line.split('+++$+++')
if parsed_line[2].strip() in rom_movies:
rom_parsed_lines.append(parsed_line[-1].strip())
else:
other_parsed_lines.append(parsed_line[-1].strip())
print(other_parsed_lines)
with open('rom.pickle', 'wb') as rom:
pickle.dump(rom_parsed_lines, rom)
with open('other.pickle', 'wb') as other:
pickle.dump(other_parsed_lines, other)
with open('rom.pickle', 'rb') as rom:
rom_dialogue = pickle.load(rom)[:15000]
catbot.train(rom_dialogue)
EN_WHITELIST = '0123456789abcdefghijklmnopqrstuvwxyz ' # space is included in whitelist
EN_BLACKLIST = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\''
limit = {
'maxq' : 25,
'minq' : 2,
'maxa' : 25,
'mina' : 2
}
UNK = 'unk'
VOCAB_SIZE = 8000
def get_id2line():
lines=open('cornell movie-dialogs corpus/movie_lines.txt', encoding='utf-8', errors='ignore').read().split('\n')
id2line = {}
for line in lines:
_line = line.split(' +++$+++ ')
if len(_line) == 5:
id2line[_line[0]] = _line[4]
return id2line
out = get_id2line()
out
def get_conversations():
conv_lines = open('cornell movie-dialogs corpus/movie_conversations.txt', encoding='utf-8', errors='ignore').read().split('\n')
convs = [ ]
for line in conv_lines[:-1]:
_line = line.split(' +++$+++ ')[-1][1:-1].replace("'","").replace(" ","")
convs.append(_line.split(','))
return convs
convs = get_conversations()
convs
def gather_dataset(convs, id2line):
q_a_pairs_3 = [];
for conv in convs:
if len(conv) %2 != 0:
conv = conv[:-1]
for i in range(len(conv)):
# if i%2 == 0:
q_a_pairs_3.append(id2line[conv[i]])
# else:
# answers.append(id2line[conv[i]])
return q_a_pairs_3
q_a_pairs_3 = gather_dataset(convs, out)
q_a_pairs_3
class SimpleDialogueManager(object):
"""
This is a simple dialogue manager to test the telegram bot.
The main part of our bot will be written here.
"""
def __init__(self):
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer
chatbot = ChatBot('MLWhizChatterbot')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')
# from chatbot import chatbot
trainer = ListTrainer(chatbot)
# chatbot.set_trainer(ListTrainer)
# trainer = ListTrainer(chatbot)
trainer.train(q_a_pairs)
trainer.train(q_a_pairs_2)
trainer.train(q_a_pairs_3)
# trainer.train(q_a_pairs_3)
self.chitchat_bot = chatbot
def generate_answer(self, question):
response = self.chitchat_bot.get_response(question)
return response
df[1:100]
import requests
from requests.compat import urljoin
import time
import argparse
import os
import json
class BotHandler(object):
"""
BotHandler is a class which implements all back-end of the bot.
It has three main functions:
'get_updates' — checks for new messages
'send_message' – posts new message to user
'get_answer' — computes the most relevant on a user's question
"""
def __init__(self, token, dialogue_manager):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
self.dialogue_manager = dialogue_manager
def get_updates(self, offset=None, timeout=30):
params = {"timeout": timeout, "offset": offset}
raw_resp = requests.get(urljoin(self.api_url, "getUpdates"), params)
try:
resp = raw_resp.json()
except json.decoder.JSONDecodeError as e:
print("Failed to parse response {}: {}.".format(raw_resp.content, e))
return []
if "result" not in resp:
return []
return resp["result"]
def send_message(self, chat_id, text):
params = {"chat_id": chat_id, "text": text}
return requests.post(urljoin(self.api_url, "sendMessage"), params)
def get_answer(self, question):
if question == '/start':
return "Hi, I am your project bot. How can I help you today?"
return self.dialogue_manager.generate_answer(question)
def is_unicode(text):
return len(text) == len(text.encode())
# class SimpleDialogueManager(object):
# """
# This is a simple dialogue manager to test the telegram bot.
# The main part of our bot will be written here.
# """
# def generate_answer(self, question):
# if "Hi" in question:
# return "Hello, You"
# else:
# return "Don't be rude. Say Hi first."
import nltk
nltk.download('punkt')
print("Hurraaaaaaaay It workss")
def main():
# Put your own Telegram Access token here...
token = '828781554:AAFeYtCKCs8Ztc2UJdFakDXi4i71UWzlBsU'
simple_manager = SimpleDialogueManager()
bot = BotHandler(token, simple_manager)
###############################################################
print("Ready to talk!")
offset = 0
while True:
updates = bot.get_updates(offset=offset)
for update in updates:
print("An update received.")
if "message" in update:
chat_id = update["message"]["chat"]["id"]
if "text" in update["message"]:
text = update["message"]["text"]
if is_unicode(text):
print("Update content: {}".format(update))
bot.send_message(chat_id, bot.get_answer(update["message"]["text"]))
else:
bot.send_message(chat_id, "Hmm, you are sending some weird characters to me...")
offset = max(offset, update['update_id'] + 1)
time.sleep(1)
if __name__ == "__main__":
main()
###Output
_____no_output_____ |
.ipynb_checkpoints/scrape-awesome-public-datasets-checkpoint.ipynb | ###Markdown
Data scraping awesome public datasetsThis is a companion notebook for the new [Data Science Solutions](https://strtupsci.com) book. The code is explained in the book.
###Code
%matplotlib inline
import urllib2
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
from subprocess import check_output
plt.style.use('seaborn-pastel')
# plt.style.available
awesome_list = 'https://github.com/caesar0301/awesome-public-datasets/blob/master/README.rst'
html = urllib2.urlopen(awesome_list)
scrape = BeautifulSoup(html, 'lxml')
category_name_feature = []; about_feature = []
name_feature = []; vintage_feature = []
link_feature = []; category_id_feature = []
github_feature = []; dataset_feature = []
# Populate github column
def extract_github_feature(link_text, link_url):
if link_text:
github_ref = link_url.find('github.com')
if github_ref > -1:
github_feature.append('Yes')
else:
github_feature.append('No')
else:
github_feature.append('No')
# Populate dataset column
def extract_dataset_feature(link_text, link_url):
if link_text:
dataset_ref = link_url.find('dataset')
datasource_ref = link_url.find('datasets')
if dataset_ref > -1 and datasource_ref == -1:
dataset_feature.append('Yes')
return
if dataset_ref > -1 and datasource_ref > -1:
dataset_feature.append('No')
return
if dataset_ref == -1:
dataset_feature.append('No')
return
else:
dataset_feature.append('No')
# Populate vintage column
def extract_vintage_feature(link_text):
if link_text:
twenty = link_text.find('20')
nineteen = link_text.find('19')
if twenty > -1:
if all(char.isdigit() for char in link_text[twenty:twenty+4]):
vintage_feature.append(link_text[twenty:twenty+4])
else:
vintage_feature.append('NA')
return
if nineteen > -1:
if all(char.isdigit() for char in link_text[nineteen:nineteen+4]):
vintage_feature.append(link_text[nineteen:nineteen+4])
else:
vintage_feature.append('NA')
return
vintage_feature.append('NA')
else:
vintage_feature.append('NA')
# Populate name column
def extract_name_feature(link_text):
shortname = None
if link_text:
# Prefix to hyphen is a short name
split_dash = link_text.find(' - ')
if split_dash > -1:
shortname = link_text[0:split_dash]
# Abbreviations in brackets are short names
split_brackets = link_text.find('(')
end_brackets = link_text.find(')')
if split_brackets > -1:
shortname = link_text[split_brackets + 1:end_brackets]
if shortname:
if all(char.isdigit() for char in shortname):
shortname = None
if shortname:
name_feature.append(shortname)
else:
if link_text:
# First four words are a short name
dataset_words = link_text.split()
if len(dataset_words) > 2:
name_feature.append(' '.join(dataset_words[0:2]))
else:
name_feature.append(link_text)
else:
name_feature.append(None)
headings_list = scrape.find_all('h2')
for heading in headings_list:
if heading.a:
category = heading.a.next_sibling.string
category_name_feature.append(category)
link_list = heading.next_sibling.next_sibling.find_all('li')
for link in link_list:
link_text = link.string
category_id_feature.append(category)
about_feature.append(link_text)
link_url = link.a.get('href')
link_feature.append(link_url)
extract_github_feature(link_text, link_url)
extract_dataset_feature(link_text, link_url)
extract_vintage_feature(link_text)
extract_name_feature(link_text)
df = pd.DataFrame(
{'name': name_feature, 'about': about_feature,
'link': link_feature, 'vintage': vintage_feature,
'dataset': pd.Categorical(dataset_feature),
'category_id': pd.Categorical(category_id_feature),
'github': pd.Categorical(github_feature)})
df = df.loc[:, ['name', 'about', 'link', 'category_id',
'dataset', 'github', 'vintage']]
df.head()
df_categories = pd.DataFrame({'name': category_name_feature})
df_categories.head()
df.describe()
df[df.vintage!='NA'].groupby('vintage').count().dataset.plot.bar()
sorted_by_category_count = df.groupby(
'category_id').count().sort_values(
by='dataset', ascending=False)
plt.figure(figsize = (6,6))
plt.xlabel('count of datasets or datasources')
sorted_by_category_count.dataset.plot.barh(stacked=True)
df_datasources = df[
(df.dataset=='No')
& (df.github=='No')
& (df.vintage=='NA')]
df_datasources.describe()
df_datasets = df[
(df.dataset=='Yes')
| (df.github=='Yes')
| (df.vintage!='NA')]
df_datasets.describe()
df_categories.to_csv(
'data/scraping/categories.csv',
index=False)
df_datasets.to_csv(
'data/scraping/datasets.csv',
na_rep='BLANK', index=False)
df_datasources.to_csv(
'data/scraping/datasources.csv',
na_rep='BLANK', index=False)
print(check_output(["ls", "data/scraping"]).decode("utf8"))
###Output
categories.csv
datasets.csv
datasources.csv
|
widgets_example.ipynb | ###Markdown
Widgets for fun (but no profit)A quick experiment using ipywidgets to see if interactive matplotlib graphs in notebookscould be useful, and to see if they can run in a Binder instance.This is taken from a few sources but is mostly based on http://kapernikov.com/ipywidgets-with-matplotlibfor the basic interactive plot and https://pbpython.com/interactive-dashboards.html to get in on binder.Widgets documentation is at https://ipywidgets.readthedocs.ioAlso useful: https://github.com/matplotlib/ipympl/blob/master/examples/ipympl.ipynb (you need ipympl installed)
###Code
# We need to import some modules. Nothing very exciting
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
%matplotlib widget
###Output
_____no_output_____
###Markdown
A simple Sine graphThis function (which gets called at the end) sets up a matplotlib graphand makes it interactive. It's about as simple as it gets. The `@widgets`decorator sets the controls for the plot (and the type of control is chosen from the types of the arguments, which map to the arguments of thefunction that gets called.
###Code
def interactive_sine_plot():
"""
Create an interactive sine plot using ipwidgets and matplotlib
"""
fig, ax = plt.subplots()
ax.set_ylim(-4, 4)
ax.grid(True)
x = np.linspace(0, 2.0 * np.pi, 100)
def make_sine(z, freq, amp, phase):
return amp * np.sin(freq * (x - phase))
@widgets.interact(freq=(0, 10, 0.1), amp=(0, 4, 0.1), phase=(0, 2.0*np.pi+0.01, 0.01))
def update_plot(freq=1.0, amp=1.0, phase=0.0):
[l.remove() for l in ax.lines]
ax.plot(x, make_sine(x, freq, amp, phase), 'b-')
fig.canvas.toolbar_visible = True # Set to False to remove options on LHS
fig.canvas.header_visible = False # Hide the Figure name at the top of the figure
ax.set_xlabel('$x$')
ax.set_ylabel('$A * \sin(\omega(x-\phi)$')
plt.show()
interactive_sine_plot()
###Output
_____no_output_____ |
py/lab/pitches.ipynb | ###Markdown
Objective Develop a classifier to predict pitch type suitable for returning predictions in real-time.
###Code
import itertools
import warnings
import matplotlib as mp
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn as sk
# helper methods for the notebook
import classifier as cl
warnings.filterwarnings('ignore')
plt.style.use('ggplot')
###Output
_____no_output_____
###Markdown
Understanding the data and cleaning
###Code
# load only meaningful features available at pitch time and target label
uninformative_feature_set = set([
'uid', 'game_pk', 'year', 'start_tfs', 'start_tfs_zulu', 'pitch_id'])
target_label = 'pitch_type'
features_desc = cl.get_feature_set_descriptions(
uninformative_feature_set, target_label)
###Output
_____no_output_____
###Markdown
Peeking at the feature metadata, it looks like a good first pass would be to use only features available at the time of the pitch, and ignore seemingly uninformative identifiers
###Code
train = pd.read_csv(
'../../data/pitches.csv',
usecols=features_desc.index, parse_dates=['date'])
print(train.shape)
display(train.head())
display(train.dtypes)
display(train.pitch_type.value_counts())
print(f'missing label count is {train.shape[0] - train.pitch_type.value_counts().sum()}')
###Output
(718961, 23)
###Markdown
The raw read has misinterpreted some features as numeric when they should be categories, which should be fixed. The output classes are heavily imbalanced, and I think a benchmark will perform at about 30% accuracy just predicting pitch_type='FF'
###Code
numerical_features = [
'at_bat_num', 'away_team_runs', 'b_height', 'balls', 'fouls',
'home_team_runs', 'inning', 'outs', 'pcount_at_bat',
'pcount_pitcher', 'strikes', 'top']
float_to_int_features = ['on_1b', 'on_2b', 'on_3b']
categorical_features = [
'batter_id', 'on_1b', 'on_2b', 'on_3b', 'pitcher_id',
'p_throws', 'stand', 'team_id_b', 'team_id_p']
target_label = 'pitch_type'
feature_type_map = {
'categorical': categorical_features,
'numerical': numerical_features,
'float_to_int': float_to_int_features,
'target': target_label}
cl.clean_pitches(train, feature_type_map)
display(train.head())
display(train.dtypes)
train.isnull().sum().sum()
###Output
_____no_output_____
###Markdown
The cleaned features use categorical with empty/NaN modeled as 'missing' and numerical with empty/NaN modeled as 0. There are nuances to 'missing' and 0 that are not entirely accurate but are good enough for now. Transforming the data for modeling
###Code
# split the training data for testing by the date at which 80% of pitches are thrown
X_calval, X_holdout, y_calval, y_holdout = cl.serial_calval_holdout_split(train)
###Output
_____no_output_____
###Markdown
I split the data by date to guard against data leakage for the holdout data set
###Code
display(X_calval.shape)
display(X_holdout.shape)
display(X_holdout.dtypes)
ct = cl.get_column_transformer(feature_type_map)
ct.fit(X_calval)
###Output
_____no_output_____
###Markdown
The column transformer is fitted only on "calval" to avoid data leakage. This custom transformer ensures feature names are available for this mix of numerical and categorical features.
###Code
X_trans_calval = ct.transform(X_calval)
X_trans_holdout = ct.transform(X_holdout)
trans_feature_names = cl.get_feature_names(ct, feature_type_map)
display(X_trans_calval.shape)
display(X_trans_holdout.shape)
display(trans_feature_names[-20:-1])
###Output
_____no_output_____
###Markdown
Classification model R&D
###Code
from time import time
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
sample_size = int(5e4)
random_row_indices = np.random.choice(X_trans_calval.shape[0], size=sample_size, replace=False)
X_trans_calval_sample = X_trans_calval[random_row_indices,]
y_calval_sample = y_calval[random_row_indices]
###Output
_____no_output_____
###Markdown
Some of the models I chose struggle with a data set this large on my laptop, so I took a random sample of rows of about 10% of the data set.
###Code
clf = DummyClassifier(strategy='most_frequent')
start = time()
clf.fit(X_trans_calval, y_calval)
print(f"Fit took {time() - start:.2f} seconds.")
accuracy = accuracy_score(y_calval, clf.predict(X_trans_calval))
print(f"sample calval accuracy is {accuracy:.2f}.")
accuracy = accuracy_score(y_holdout, clf.predict(X_trans_holdout))
print(f"holdout accuracy is {accuracy:.2f}.")
###Output
Fit took 0.75 seconds.
sample calval accuracy is 0.33.
holdout accuracy is 0.34.
###Markdown
As expected, a dummy classifier achieves 33% accuracy, so this is the benchmark to beat.
###Code
clf = RandomForestClassifier(n_jobs=-1)
start = time()
clf.fit(X_trans_calval_sample, y_calval_sample)
print(f"Fit took {time() - start:.2f} seconds.")
accuracy = accuracy_score(y_calval_sample, clf.predict(X_trans_calval_sample))
print(f"sample calval accuracy is {accuracy:.2f}.")
accuracy = accuracy_score(y_holdout, clf.predict(X_trans_holdout))
print(f"holdout accuracy is {accuracy:.2f}.")
print(f"most important features are:")
display(np.array(trans_feature_names)[list(clf.feature_importances_>0.01)])
###Output
Fit took 15.37 seconds.
sample calval accuracy is 0.98.
holdout accuracy is 0.38.
most important features are:
###Markdown
A basic random forest overfits to the calval data set but achieves 38% on the holdout, so about 15% lift. Not bad for out the box settings on such a small sample.
###Code
clf = LogisticRegression(solver='liblinear', multi_class='ovr')
start = time()
clf.fit(X_trans_calval_sample, y_calval_sample)
print(f"Fit took {time() - start:.2f} seconds.")
accuracy = accuracy_score(y_calval_sample, clf.predict(X_trans_calval_sample))
print(f"sample calval accuracy is {accuracy:.2f}.")
accuracy = accuracy_score(y_holdout, clf.predict(X_trans_holdout))
print(f"holdout accuracy is {accuracy:.2f}.")
###Output
Fit took 97.11 seconds.
sample calval accuracy is 0.54.
holdout accuracy is 0.44.
###Markdown
A basic logistic regression with some regularization overfits less than the random forest and get 44% accuracy, so about 33% lift. I'll investigate this model further.
###Code
clf = LogisticRegression(solver='liblinear', multi_class='ovr')
param_grid = {'C': [0.1, 1, 10]}
grid_search = GridSearchCV(clf, param_grid=param_grid, cv=2)
start = time()
grid_search.fit(X_trans_calval_sample, y_calval_sample)
n_param_sets = len(grid_search.cv_results_['params'])
print(f"GridSearchCV took {time() - start:.2f} seconds for {n_param_sets:d} candidate parameter settings.")
display(grid_search.cv_results_)
###Output
GridSearchCV took 364.97 seconds for 3 candidate parameter settings.
###Markdown
Grid search on the regularization hyperparameter and twofold cross validation show consistent results with the out of the box settings for Logistic Regression and yield accuracy of 45%, consistent with the prior experiment. The model has thousands of features and does not scale well, so I will retrain the model using only the most important features using all the calval data set.
###Code
sfm = SelectFromModel(estimator=grid_search.best_estimator_, threshold='mean', max_features=100)
start = time()
sfm.fit(X_trans_calval_sample, y_calval_sample)
print(f"Fit took {time() - start:.2f} seconds.")
X_trans_calval_subset_features = sfm.transform(X_trans_calval)
X_trans_holdout_subset_features = sfm.transform(X_trans_holdout)
print(X_trans_calval_subset_features.shape)
clf = LogisticRegression(solver='liblinear', multi_class='ovr')
start = time()
clf.fit(X_trans_calval_subset_features, y_calval)
print(f"Fit took {time() - start:.2f} seconds.")
accuracy = accuracy_score(y_calval, clf.predict(X_trans_calval_subset_features))
print(f"calval accuracy is {accuracy:.2f}.")
accuracy = accuracy_score(y_holdout, clf.predict(X_trans_holdout_subset_features))
print(f"holdout accuracy is {accuracy:.2f}.")
###Output
Fit took 102.61 seconds.
(574882, 100)
Fit took 124.76 seconds.
calval accuracy is 0.41.
holdout accuracy is 0.40.
###Markdown
Training logistic regression using only 100 of the transformed features results in holdout accuracy of 40% and lift of 20%.
###Code
sfm = SelectFromModel(estimator=grid_search.best_estimator_, threshold='mean', max_features=300)
start = time()
sfm.fit(X_trans_calval_sample, y_calval_sample)
print(f"Fit took {time() - start:.2f} seconds.")
X_trans_calval_subset_features = sfm.transform(X_trans_calval)
X_trans_holdout_subset_features = sfm.transform(X_trans_holdout)
print(X_trans_calval_subset_features.shape)
clf = LogisticRegression(solver='liblinear', multi_class='ovr')
start = time()
clf.fit(X_trans_calval_subset_features, y_calval)
print(f"Fit took {time() - start:.2f} seconds.")
accuracy = accuracy_score(y_calval, clf.predict(X_trans_calval_subset_features))
print(f"calval accuracy is {accuracy:.2f}.")
accuracy = accuracy_score(y_holdout, clf.predict(X_trans_holdout_subset_features))
print(f"holdout accuracy is {accuracy:.2f}.")
###Output
Fit took 130.91 seconds.
(574882, 300)
Fit took 407.06 seconds.
calval accuracy is 0.46.
holdout accuracy is 0.44.
###Markdown
Training logistic regression using only 300 of the transformed features results in holdout accuracy of 44% and lift of 33%. Conclusion Model selection should balance the need for model performance and computational resource requirements, along with deployability. For this reason, I propose the best model is the Logistic Regression trained using only the top 300 features and would deploy this fitted model. Balancing the trade-offs between development time, training time, and other performance metrics would require further economic data such as cost of inaccurate predictions and entry to market delays.
###Code
import pickle
# save the settings used to pickle file for use in deploy
model_metadata = {
'hyperparameters': {'C': 1},
'sample_size': int(5e4),
'max_features': 300
}
with open('model_metadata.pkl', 'wb') as fh:
pickle.dump(model_metadata, fh, protocol=pickle.HIGHEST_PROTOCOL)
###Output
_____no_output_____ |
Coding_Interview_exercises/TestDome/GitHub_MD_rendering/06_song.ipynb | ###Markdown
Instruction - A playlist is considered a repeating playlist if any of the songs contain a reference to a previous song in the playlist. Otherwise, the playlist will end with the last song which points to None. - Implement a function is_repeating_playlist that, efficiently with respect to time used, returns true if a playlist is repeating or false if it is not. Start-up code
###Code
#For example, the following code prints "True" as both songs point to each other. why?
class Song:
def __init__(self, name):
self.name = name
self.next = None
def next_song(self, song):
self.next = song
def is_repeating_playlist(self):
return None
first = Song("Hello")
second = Song("Eye of the tiger")
first.next_song(second);
second.next_song(first);
print(first.is_repeating_playlist())
###Output
None
###Markdown
Solution 1
###Code
class Song:
def __init__(self, name):
self.name = name
self.next = None
def next_song(self, song):
self.next = song
def is_repeating_playlist(self):
"""
:returns: (bool) True if the playlist is repeating, False if not.
"""
playlist = {self}
song = self.next
while song:
if song in playlist:
return True
else:
playlist.add(song)
song = song.next
return False
first = Song("Hello")
second = Song("Eye of the tiger")
first.next_song(second)
second.next_song(first)
print(first.is_repeating_playlist())
###Output
True
|
Chapter02/Recipe-04-Replacing-missing-values-by-an-arbitrary-number.ipynb | ###Markdown
Replacing missing values by an arbitrary numberIn this recipe, we will replace missing values by an arbitrary number using pandas, Scikit-learn and Feature-Engine, all open source Python libraries.
###Code
import pandas as pd
# to split the data sets
from sklearn.model_selection import train_test_split
# to impute missing data with sklearn
from sklearn.impute import SimpleImputer
# to impute missing data with feature-engine
from feature_engine.missing_data_imputers import ArbitraryNumberImputer
# load data
data = pd.read_csv('creditApprovalUCI.csv')
data.head()
# let's separate into training and testing set
X_train, X_test, y_train, y_test = train_test_split(
data.drop('A16', axis=1), data['A16'], test_size=0.3, random_state=0)
X_train.shape, X_test.shape
# find the percentage of missing data per variable
X_train.isnull().mean()
###Output
_____no_output_____
###Markdown
Arbitrary imputation with pandas
###Code
# find the maximum value per variable
X_train[['A2','A3', 'A8', 'A11']].max()
# replace NA with 99 in indicated numerical variables
for var in ['A2','A3', 'A8', 'A11']:
X_train[var].fillna(99, inplace=True)
X_test[var].fillna(99, inplace=True)
# check absence of missing values
X_train[['A2','A3', 'A8', 'A11']].isnull().sum()
###Output
_____no_output_____
###Markdown
Arbitrary imputation with Scikit-learn
###Code
# let's separate into training and testing set
X_train, X_test, y_train, y_test = train_test_split(
data[['A2', 'A3', 'A8', 'A11']],
data['A16'],
test_size=0.3,
random_state=0)
# create an instance of the simple imputer
imputer = SimpleImputer(strategy='constant', fill_value=99)
# we fit the imputer to the train set
imputer.fit(X_train)
# we can look at the constant values:
imputer.statistics_
# and now we impute the train and test set
# NOTE: the data is returned as a numpy array!!!
X_train = imputer.transform(X_train)
X_test = imputer.transform(X_test)
# check that missing values were removed
pd.DataFrame(X_train).isnull().sum()
###Output
_____no_output_____
###Markdown
Arbitrary imputation imputation with feature engine
###Code
# let's separate into training and testing set
X_train, X_test, y_train, y_test = train_test_split(
data.drop('A16', axis=1), data['A16'], test_size=0.3, random_state=0)
# let's create an arbitrary value imputer
imputer = ArbitraryNumberImputer(
arbitrary_number=99, variables=['A2','A3', 'A8', 'A11'])
imputer.fit(X_train)
# dictionary with the mappings for each variable
imputer.arbitrary_number
# transform the data
X_train = imputer.transform(X_train)
X_test = imputer.transform(X_test)
# check that null values were replaced
X_train[['A2','A3', 'A8', 'A11']].isnull().mean()
###Output
_____no_output_____
###Markdown
Arbitrary imputation imputation with Sklearn selecting features to impute
###Code
import pandas as pd
# to impute missing data with sklearn
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
# to split the data sets
from sklearn.model_selection import train_test_split
# load data
data = pd.read_csv('creditApprovalUCI.csv')
# let's separate into training and testing set
X_train, X_test, y_train, y_test = train_test_split(
data.drop('A16', axis=1),data['A16' ], test_size=0.3, random_state=0)
# first we need to make a list with the numerical vars
features_arbitrary = ['A2', 'A3', 'A8', 'A11']
features_mean = ['A15']
# then we instantiate the imputer within a pipeline
arbitrary_imputer = Pipeline(steps=[('imputer', SimpleImputer(strategy='constant', fill_value=99))])
mean_imputer = Pipeline(steps=[('imputer', SimpleImputer(strategy='mean'))])
# then we put the features list and the imputer in
# the column transformer
preprocessor = ColumnTransformer(transformers=[
('arbitrary_imputer', arbitrary_imputer, features_arbitrary),
('mean_imputer', mean_imputer, features_mean)
], remainder='passthrough')
# now we fit the preprocessor
preprocessor.fit(X_train)
# and now we impute the data
X_train = preprocessor.transform(X_train)
X_test = preprocessor.transform(X_test)
# Note that Scikit-Learn transformers return NumPy arrays!!
X_train
###Output
_____no_output_____ |
example_hyperas.ipynb | ###Markdown
###Code
!pip install --upgrade jupyter-console &> /dev/null
!pip install --upgrade hyperas &> /dev/null
from google.colab import drive
drive.mount('/gdrive')
%ls /gdrive
!ls '/gdrive/My Drive/Colab Notebooks'
import numpy as np
import os
from hyperopt import Trials, STATUS_OK, tpe
from keras.datasets import mnist
from keras.layers.core import Dense, Dropout, Activation
from keras.models import Sequential
from keras.utils import np_utils
from hyperas import optim
from hyperas.distributions import choice, uniform
def data():
"""
Data providing function:
This function is separated from create_model() so that hyperopt
won't reload data for each evaluation run.
"""
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
nb_classes = 10
y_train = np_utils.to_categorical(y_train, nb_classes)
y_test = np_utils.to_categorical(y_test, nb_classes)
return x_train, y_train, x_test, y_test
def create_model(x_train, y_train, x_test, y_test):
"""
Model providing function:
Create Keras model with double curly brackets dropped-in as needed.
Return value has to be a valid python dictionary with two customary keys:
- loss: Specify a numeric evaluation metric to be minimized
- status: Just use STATUS_OK and see hyperopt documentation if not feasible
The last one is optional, though recommended, namely:
- model: specify the model just created so that we can later use it again.
"""
model = Sequential()
model.add(Dense(512, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dropout({{uniform(0, 1)}}))
model.add(Dense({{choice([256, 512, 1024])}}))
model.add(Activation({{choice(['relu', 'sigmoid'])}}))
model.add(Dropout({{uniform(0, 1)}}))
# If we choose 'four', add an additional fourth layer
if {{choice(['three', 'four'])}} == 'four':
model.add(Dense(100))
# We can also choose between complete sets of layers
model.add({{choice([Dropout(0.5), Activation('linear')])}})
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'],
optimizer={{choice(['rmsprop', 'adam', 'sgd'])}})
result = model.fit(x_train, y_train,
batch_size={{choice([64, 128])}},
epochs=2,
verbose=2,
validation_split=0.1)
#get the highest validation accuracy of the training epochs
validation_acc = np.amax(result.history['val_acc'])
print('Best validation acc of epoch:', validation_acc)
return {'loss': -validation_acc, 'status': STATUS_OK, 'model': model}
if __name__ == '__main__':
best_run, best_model = optim.minimize(model=create_model,
data=data,
algo=tpe.suggest,
max_evals=5,
trials=Trials(),
notebook_name=os.path.join('..','gdrive','My Drive','Colab Notebooks','example_hyperas'))
X_train, Y_train, X_test, Y_test = data()
print("Evalutation of best performing model:")
print(best_model.evaluate(X_test, Y_test))
print("Best performing model chosen hyper-parameters:")
print(best_run)
###Output
>>> Imports:
#coding=utf-8
try:
from google.colab import drive
except:
pass
try:
import numpy as np
except:
pass
try:
import os
except:
pass
try:
from hyperopt import Trials, STATUS_OK, tpe
except:
pass
try:
from keras.datasets import mnist
except:
pass
try:
from keras.layers.core import Dense, Dropout, Activation
except:
pass
try:
from keras.models import Sequential
except:
pass
try:
from keras.utils import np_utils
except:
pass
try:
from hyperas import optim
except:
pass
try:
from hyperas.distributions import choice, uniform
except:
pass
>>> Hyperas search space:
def get_space():
return {
'Dropout': hp.uniform('Dropout', 0, 1),
'Dense': hp.choice('Dense', [256, 512, 1024]),
'Activation': hp.choice('Activation', ['relu', 'sigmoid']),
'Dropout_1': hp.uniform('Dropout_1', 0, 1),
'Dropout_2': hp.choice('Dropout_2', ['three', 'four']),
'add': hp.choice('add', [Dropout(0.5), Activation('linear')]),
'optimizer': hp.choice('optimizer', ['rmsprop', 'adam', 'sgd']),
'batch_size': hp.choice('batch_size', [64, 128]),
}
>>> Data
1:
2: """
3: Data providing function:
4:
5: This function is separated from create_model() so that hyperopt
6: won't reload data for each evaluation run.
7: """
8: (x_train, y_train), (x_test, y_test) = mnist.load_data()
9: x_train = x_train.reshape(60000, 784)
10: x_test = x_test.reshape(10000, 784)
11: x_train = x_train.astype('float32')
12: x_test = x_test.astype('float32')
13: x_train /= 255
14: x_test /= 255
15: nb_classes = 10
16: y_train = np_utils.to_categorical(y_train, nb_classes)
17: y_test = np_utils.to_categorical(y_test, nb_classes)
18:
19:
20:
>>> Resulting replaced keras model:
1: def keras_fmin_fnct(space):
2:
3: """
4: Model providing function:
5:
6: Create Keras model with double curly brackets dropped-in as needed.
7: Return value has to be a valid python dictionary with two customary keys:
8: - loss: Specify a numeric evaluation metric to be minimized
9: - status: Just use STATUS_OK and see hyperopt documentation if not feasible
10: The last one is optional, though recommended, namely:
11: - model: specify the model just created so that we can later use it again.
12: """
13: model = Sequential()
14: model.add(Dense(512, input_shape=(784,)))
15: model.add(Activation('relu'))
16: model.add(Dropout(space['Dropout']))
17: model.add(Dense(space['Dense']))
18: model.add(Activation(space['Activation']))
19: model.add(Dropout(space['Dropout_1']))
20:
21: # If we choose 'four', add an additional fourth layer
22: if space['Dropout_2'] == 'four':
23: model.add(Dense(100))
24:
25: # We can also choose between complete sets of layers
26:
27: model.add(space['add'])
28: model.add(Activation('relu'))
29:
30: model.add(Dense(10))
31: model.add(Activation('softmax'))
32:
33: model.compile(loss='categorical_crossentropy', metrics=['accuracy'],
34: optimizer=space['optimizer'])
35:
36: result = model.fit(x_train, y_train,
37: batch_size=space['batch_size'],
38: epochs=2,
39: verbose=2,
40: validation_split=0.1)
41: #get the highest validation accuracy of the training epochs
42: validation_acc = np.amax(result.history['val_acc'])
43: print('Best validation acc of epoch:', validation_acc)
44: return {'loss': -validation_acc, 'status': STATUS_OK, 'model': model}
45:
Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz
11493376/11490434 [==============================] - 1s 0us/step
0%| | 0/5 [00:00<?, ?it/s, best loss: ?]WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
Instructions for updating:
Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Train on 54000 samples, validate on 6000 samples
Epoch 1/2
- 10s - loss: 1.7256 - acc: 0.4249 - val_loss: 0.8002 - val_acc: 0.8493
Epoch 2/2
- 10s - loss: 0.9461 - acc: 0.6979 - val_loss: 0.4520 - val_acc: 0.8923
Best validation acc of epoch:
0.8923333334922791
Train on 54000 samples, validate on 6000 samples
Epoch 1/2
- 15s - loss: 2.2159 - acc: 0.2832 - val_loss: 0.7372 - val_acc: 0.7705
Epoch 2/2
- 15s - loss: 1.5323 - acc: 0.4610 - val_loss: 0.5590 - val_acc: 0.8627
Best validation acc of epoch:
0.8626666666666667
Train on 54000 samples, validate on 6000 samples
Epoch 1/2
- 10s - loss: 2.0434 - acc: 0.2848 - val_loss: 0.7661 - val_acc: 0.8870
Epoch 2/2
- 9s - loss: 1.3212 - acc: 0.5004 - val_loss: 0.4248 - val_acc: 0.9358
Best validation acc of epoch:
0.935833333492279
Train on 54000 samples, validate on 6000 samples
Epoch 1/2
- 7s - loss: 0.7869 - acc: 0.7459 - val_loss: 0.1812 - val_acc: 0.9448
Epoch 2/2
- 7s - loss: 0.2932 - acc: 0.9158 - val_loss: 0.1169 - val_acc: 0.9660
Best validation acc of epoch:
0.9659999995231628
Train on 54000 samples, validate on 6000 samples
Epoch 1/2
- 12s - loss: 0.5513 - acc: 0.8315 - val_loss: 0.1394 - val_acc: 0.9597
Epoch 2/2
- 11s - loss: 0.1766 - acc: 0.9511 - val_loss: 0.0934 - val_acc: 0.9727
Best validation acc of epoch:
0.9726666668256124
100%|██████████| 5/5 [01:49<00:00, 21.28s/it, best loss: -0.9726666668256124]
Evalutation of best performing model:
10000/10000 [==============================] - 1s 97us/step
[0.10379967336268164, 0.9689]
Best performing model chosen hyper-parameters:
{'Activation': 1, 'Dense': 2, 'Dropout': 0.03323327852409652, 'Dropout_1': 0.0886198698550964, 'Dropout_2': 1, 'add': 0, 'batch_size': 1, 'optimizer': 0}
|
smab/notebooks/01_Simple_Ex.ipynb | ###Markdown
MABSim and SMPyBandits First ExampleIn this notebook, we present a first example of the use of *SMPyBandits* and *MABSim* as the base library for MAB implementartion.
###Code
#link to google drive for importing .py files
from google.colab import drive
drive.mount('/content/drive')
!pip install -q SMPyBandits
from importlib.machinery import SourceFileLoader
mabalgs = SourceFileLoader('mabalgs', '/content/drive/My Drive/Colab Notebooks/MultiArmedBandits/MyMAB/mabalgs.py').load_module()
mabsim = SourceFileLoader('mabsim', '/content/drive/My Drive/Colab Notebooks/MultiArmedBandits/MyMAB/mabsim.py').load_module()
mabplot = SourceFileLoader('mabplot', '/content/drive/My Drive/Colab Notebooks/MultiArmedBandits/MyMAB/mabplot.py').load_module()
#Dependencies
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#Policies
from SMPyBandits.Policies import UCBalpha, UCB, IndexPolicy
from mabalgs import SafeEpsilonGreedy, SafeUCBalpha
#Simulation
from mabsim import mabs
from mabplot import mabplt
plt.rcParams['figure.figsize'] = (10, 5)
#MAB parameters
means = np.array([0.3, 0.4, 0.4, 0.4, 0.4, 0.4, 0.45, 0.55, 0.6])
#means = np.concatenate((np.repeat(0.1, 15), np.repeat(0.7, 5), [0.9]))
k = len(means)
#arms objects
#A = [ExtendedBernoulli(m, maxr=maxr, minr=minr) for m in means]
A = [ExtendedBernoulli(m) for m in means]
maxr = +1.0
minr = -1.0
ampl = maxr - minr
#algorithm
#g = UCBalpha(k, alpha=1.0*ampl) #alpha is related to the amplitude of rewards
g = UCB(k)
#time-horizon
tau = 3000
#repetitions
n = 1
#window average parameter
win = tau//10
M = mabs(A, g, tau, repetitions=n, window=win, save_only_means=False)
M.run(tqdm_leave=True)
P = mabplt(M)
P.plot_history()
P.plot_action_count_progression()
P.plot_action_freq_progression()
P.plot_action_window_freq_spectrum()
P.plot_precision_progression()
#P.plot_comp_arm_count()
#P.plot_comp_arm_rewards()
P.plot_comp_freq_prop()
P.plot_cumulated_reward_regret_progression()
P.plot_average_reward_regret_progression()
#P.plot_cumulated_reward_progression()
#P.plot_average_reward_progression()
#P.plot_cumulated_regret_progression()
#P.plot_average_regret_progression()
P.plot_reward_regret()
P.plot_budget_progression()
P.plot_negative_budget_progression()
P.plot_negative_budget_time_progression()
P.plot_cumulated_negative_budget_progression()
###Output
_____no_output_____ |
Temas/6.0 ARMA/ARMA.ipynb | ###Markdown
MA Model: Returns
###Code
# Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.graphics.tsaplots as sgt
import statsmodels.tsa.stattools as sts
from statsmodels.tsa.arima_model import ARMA
from scipy.stats.distributions import chi2
from math import sqrt
import seaborn as sns
sns.set
# Importing Dataset
rawCsvData = pd.read_csv("../../DataSets/Index2018.csv")
dfComp=rawCsvData.copy()
# Pre-processing data
# Date
dfComp.date = pd.to_datetime(dfComp.date, dayfirst = True)
# Fixing index
dfComp.set_index("date", inplace = True)
# Frequency
dfComp = dfComp.asfreq('b')
# df
dfComp = dfComp.fillna(method = 'ffill')
# creating a copy of ftse column
dfComp['marketValue'] = dfComp.ftse
dfComp.head()
# Deleting some columns
dfComp = dfComp.drop(['spx','dax', 'ftse', 'nikkei'], axis = 1)
dfComp
# spliting data set in trainning and testing data
size = int(len(dfComp)*0.8)
df, dfTest = dfComp.iloc[:size], dfComp.iloc[size:]
# The LLR test
def LLR_test(mod_1, mod_2, DF = 1):
L1 = mod_1.llf
L2 = mod_2.llf
LR = (2*(L2-L1))
p = chi2.sf(LR, DF).round(3)
return p
import warnings
warnings.filterwarnings("ignore")
# Creating Returns
df['returns'] = df.marketValue.pct_change(1)*100
# modelo ARMA(1,1) for Returns
model_ret_ar_ma_1 = ARMA(df.returns[1:], order = (1,1)) # En order la ordenada indica los rezagos y el error
results_ret_ar_ma_1 = model_ret_ar_ma_1.fit()
results_ret_ar_ma_1.summary()
# coeficientes: los retornos se mueven en tendencias de valores positivios o negativos. tendencia
# positiva entre valores pasados y presentes.
# coef medias móviles: sugiere que deberíamos estar alejándonos de valores del periodo pasado en lugar de
# tratar de usarlos como objetivo para la calibración
# Necesitamos comparar el modelo ARMA(1,1) con sus partes por separado
modelRetMA1 = ARMA(df.returns[1:], order = (0,1)) # MA MODEL
resultsRetMA1 = modelRetMA1.fit()
modelRetAR1 = ARMA(df.returns[1:], order = (1,0)) # AR MODEL
resultsRetAR1 = modelRetAR1.fit()
print("\nARMA VS AR", LLR_test(resultsRetAR1, results_ret_ar_ma_1))
print("\nARMA VS MA", LLR_test(resultsRetMA1, results_ret_ar_ma_1))
sgt.plot_acf(df.returns[1:], zero = False, lags = 40)
plt.title("ACF forreturns", size = 22)
plt.show()
sgt.plot_pacf(df.returns[1:], zero = False, lags = 40, method = 'ols')
plt.title("PACF of Residuals for returns", size = 22)
plt.show()
###Output
_____no_output_____
###Markdown
Aunque vemos que hasta 8 rezagos podríamos ocupar, complejizar el modelo en ARMA sería redundante. porbamos con la mitad
###Code
# Higher lag ARMA models
model_ret_ar_3_ma_3 = ARMA(df.returns[1:], order = (3,3))
results_ret_ar_3_ma_3 = model_ret_ar_3_ma_3.fit()
results_ret_ar_3_ma_3.summary()
###Output
_____no_output_____
###Markdown
Comparamos modelos ARMA(1,1) y ARMA(3,3)
###Code
LLR_test(results_ret_ar_ma_1, results_ret_ar_3_ma_3, DF = 4)
model_ret_ar_3_ma_2 = ARMA(df.returns[1:], order = (3,2))
results_ret_ar_3_ma_2 = model_ret_ar_3_ma_2.fit()
results_ret_ar_3_ma_2.summary()
model_ret_ar_3_ma_1 = ARMA(df.returns[1:], order = (3,1))
results_ret_ar_3_ma_1 = model_ret_ar_3_ma_1.fit()
results_ret_ar_3_ma_1.summary()
LLR_test(results_ret_ar_3_ma_1, results_ret_ar_3_ma_2)
model_ret_ar_2_ma_2 = ARMA(df.returns[1:], order = (2,2))
results_ret_ar_2_ma_2 = model_ret_ar_2_ma_2.fit()
results_ret_ar_2_ma_2.summary()
model_ret_ar_1_ma_3 = ARMA(df.returns[1:], order = (1,3))
results_ret_ar_1_ma_3 = model_ret_ar_1_ma_3.fit()
results_ret_ar_1_ma_3.summary()
###Output
_____no_output_____
###Markdown
Para usar un test de comparación de modelos estos deben estar anidadosARMA($p_1$,$q1$)ARMA($p_2$,$q_2$)i) $p_1 + q1 > p_2 + q_2$ii) $p_1 \ge p_2$iii) $q_1 \ge q_2$ Cuando no tenemos modelos anidados hay que mirar los log likelihood y el criterio de información. Nos interesa un **mayor log likelihood y un menor coeficiente de información**
###Code
print("\n ARMA(3,2): \tLL = ", results_ret_ar_3_ma_2.llf, "\n ARMA(3,2): \tAIC = ", results_ret_ar_3_ma_2.aic)
print("\n ARMA(1,3): \tLL = ", results_ret_ar_1_ma_3.llf, "\n ARMA(1,3): \tAIC = ", results_ret_ar_1_ma_3.aic)
# ARMA(3,2) y ARMA(5,1)
###Output
ARMA(3,2): LL = -7895.747458514493
ARMA(3,2): AIC = 15805.494917028986
ARMA(1,3): LL = -7896.837893753008
ARMA(1,3): AIC = 15805.675787506016
###Markdown
Con los criterios expuestos nos quedaríamos con el modelo ARMA(3,2)
###Code
# Residuals for returns
df['res_ret_ar_3_ma_2']=results_ret_ar_3_ma_2.resid[1:]
df.res_ret_ar_3_ma_2.plot(figsize = (20,5))
plt.title("Residuals of Returns", size = 24)
plt.show()
# ACF
sgt.plot_acf(df.res_ret_ar_3_ma_2[2:], zero = False, lags = 40)
plt.title("ACF of residuals for returns")
plt.show()
# Evaluar ARMA(5,5) -> muchos no son sognificativos
model_ret_ar_5_ma_5 = ARMA(df.returns[1:], order = (5,5))
results_ret_ar_5_ma_5 = model_ret_ar_5_ma_5.fit()
results_ret_ar_5_ma_5.summary()
# ARMA(1,5)
model_ret_ar_1_ma_5 = ARMA(df.returns[1:], order = (1,5))
results_ret_ar_1_ma_5 = model_ret_ar_1_ma_5.fit()
results_ret_ar_1_ma_5.summary()
# ARMA(5,1)
model_ret_ar_5_ma_1 = ARMA(df.returns[1:], order = (5,1))
results_ret_ar_5_ma_1 = model_ret_ar_5_ma_1.fit()
results_ret_ar_5_ma_1.summary()
# no puede hacerse la cpmparación con el test, no son modelos anidados
print("\n ARMA(1,5): \tllf =", results_ret_ar_1_ma_5.llf, "\tAIC :", results_ret_ar_1_ma_5.aic)
print("\n ARMA(5,1): \tllf =", results_ret_ar_5_ma_1.llf, "\tAIC :", results_ret_ar_5_ma_1.aic)
# el ARMA(5,1) resultaría ser el mejor de los dos
# Comparar los modelos ARMA(3,2) y ARMA(5,1) LL y AIC
print("\n ARMA(3,2): \tllf =", results_ret_ar_3_ma_2.llf, "\tAIC :", results_ret_ar_3_ma_2.aic)
print("\n ARMA(5,1): \tllf =", results_ret_ar_5_ma_1.llf, "\tAIC :", results_ret_ar_5_ma_1.aic)
# ARMA(5,1) se desempeña mejor (NUEVO GANADOR)
# EXAMINA LOS RESIDUOS
df['res_ret_ar_5_ma_1']=results_ret_ar_5_ma_1.resid[1:]
sts.adfuller(df.res_ret_ar_5_ma_1[2:])
# plot
df.res_ret_ar_5_ma_1[2:].plot(figsize = (24,8))
plt.title("Residuals for returns", size = 21)
plt.show()
sgt.plot_acf(df.res_ret_ar_5_ma_1[2:], zero = False, lags = 40)
plt.title("ACF for residuals of returns", size = 21)
plt.show()
###Output
_____no_output_____
###Markdown
Dado que los primeros 10 residuos no resultan significativos, podemos decir que el error se mueve aleatoriamente ARMA Models for prices
###Code
# Veremos cómo se comporta estos modelos con una serie no estacionaria con los datos de precio
sts.adfuller(df.marketValue)
# plot ACF
# plot PACF
#ARMA(1,1) PARA PRECIOS. Un coef no es significativo
# ACF para residuos. Hay que incluir más retrasos
# ARMA(6,6) NO JALA PORQUE NO ES ESTACIONARIA. Pero se puede
model_ar_6_ma_6 = ARMA(df.marketValue, order=(6,6))
results_ar_6_ma_6 = model_ar_6_ma_6.fit(start_ar_lags = 11) # agregamos un parámetro
results_ar_6_ma_6.summary()
# al patrecer el único que cumple es el ARMA(6,2)
# residuos + ACF
# Comparación ARMA RETORNOS Y ARMA PRECIOS: AIC Y LL
# Fíjate los resultados. El desempeño
###Output
_____no_output_____ |
house price prediction 01.ipynb | ###Markdown
Checking the Target Variable
###Code
sns.distplot(train.SalePrice)
###Output
_____no_output_____
###Markdown
data is rightly skewed hence Transforming it
###Code
sns.distplot(np.log(train.SalePrice + 1))
###Output
_____no_output_____
###Markdown
visualizing\checking null values for both train and test by combining them
###Code
data = pd.concat((train.drop(["SalePrice"], axis=1), test))
data_na = (data.isnull().sum() / len(data)) * 100
data_na = data_na.drop(data_na[data_na == 0].index).sort_values(ascending=False)
plt.figure(figsize=(12, 6))
plt.xticks(rotation="90")
sns.barplot(x=data_na.index, y=data_na)
data[data.PoolArea != 0][["PoolArea", "PoolQC"]]
###Output
_____no_output_____
###Markdown
MiscFeature can be deleted, as miscfeature has too many missing values
###Code
data[data.MiscVal > 10000][["MiscFeature", "MiscVal"]]
data[(data.GarageType.notnull()) & (data.GarageYrBlt.isnull())][["Neighborhood", "YearBuilt", "YearRemodAdd", "GarageType", "GarageYrBlt", "GarageFinish", "GarageCars", "GarageArea", "GarageQual", "GarageCond"]]
train.loc[[332, 948]][["BsmtQual", "BsmtCond", "BsmtExposure", "BsmtFinType1", "BsmtFinSF1", "BsmtFinType2", "BsmtFinSF2", "BsmtUnfSF", "BsmtFullBath", "BsmtHalfBath"]]
test.loc[[27, 580, 725, 757, 758, 888, 1064]][["BsmtQual", "BsmtCond", "BsmtExposure", "BsmtFinType1", "BsmtFinSF1", "BsmtFinType2", "BsmtFinSF2", "BsmtUnfSF", "BsmtFullBath", "BsmtHalfBath"]]
plt.scatter(train.Utilities, train.SalePrice)
###Output
_____no_output_____
###Markdown
feature engineering 1.correcting SalePrice with a simple log transformation.
###Code
y = train["SalePrice"]
y = np.log(y+1)
###Output
_____no_output_____
###Markdown
2. Missing values filling
###Code
# PoolQC
test.loc[960, "PoolQC"] = "Fa"
test.loc[1043, "PoolQC"] = "Gd"
test.loc[1139, "PoolQC"] = "Fa"
# Garage
test.loc[666, "GarageYrBlt"] = 1979
test.loc[1116, "GarageYrBlt"] = 1979
test.loc[666, "GarageFinish"] = "Unf"
test.loc[1116, "GarageFinish"] = "Unf"
test.loc[1116, "GarageCars"] = 2
test.loc[1116, "GarageArea"] = 480
test.loc[666, "GarageQual"] = "TA"
test.loc[1116, "GarageQual"] = "TA"
test.loc[666, "GarageCond"] = "TA"
test.loc[1116, "GarageCond"] = "TA"
###Output
_____no_output_____
###Markdown
3. Missing values filling
###Code
# PoolQC
train = train.fillna({"PoolQC": "None"})
test = test.fillna({"PoolQC": "None"})
# Alley
train = train.fillna({"Alley": "None"})
test = test.fillna({"Alley": "None"})
# FireplaceQu
train = train.fillna({"FireplaceQu": "None"})
test = test.fillna({"FireplaceQu": "None"})
# LotFrontage
train = train.fillna({"LotFrontage": 0})
test = test.fillna({"LotFrontage": 0})
# Garage
train = train.fillna({"GarageType": "None"})
test = test.fillna({"GarageType": "None"})
train = train.fillna({"GarageYrBlt": 0})
test = test.fillna({"GarageYrBlt": 0})
train = train.fillna({"GarageFinish": "None"})
test = test.fillna({"GarageFinish": "None"})
test = test.fillna({"GarageCars": 0})
test = test.fillna({"GarageArea": 0})
train = train.fillna({"GarageQual": "None"})
test = test.fillna({"GarageQual": "None"})
train = train.fillna({"GarageCond": "None"})
test = test.fillna({"GarageCond": "None"})
# Bsmt
train = train.fillna({"BsmtQual": "None"})
test = test.fillna({"BsmtQual": "None"})
train = train.fillna({"BsmtCond": "None"})
test = test.fillna({"BsmtCond": "None"})
train = train.fillna({"BsmtExposure": "None"})
test = test.fillna({"BsmtExposure": "None"})
train = train.fillna({"BsmtFinType1": "None"})
test = test.fillna({"BsmtFinType1": "None"})
train = train.fillna({"BsmtFinSF1": 0})
test = test.fillna({"BsmtFinSF1": 0})
train = train.fillna({"BsmtFinType2": "None"})
test = test.fillna({"BsmtFinType2": "None"})
test = test.fillna({"BsmtFinSF2": 0})
test = test.fillna({"BsmtUnfSF": 0})
test = test.fillna({"TotalBsmtSF": 0})
test = test.fillna({"BsmtFullBath": 0})
test = test.fillna({"BsmtHalfBath": 0})
# MasVnr
train = train.fillna({"MasVnrType": "None"})
test = test.fillna({"MasVnrType": "None"})
train = train.fillna({"MasVnrArea": 0})
test = test.fillna({"MasVnrArea": 0})
# MiscFeature,Fence,Utilities
train = train.drop(["Fence", "MiscFeature", "Utilities"], axis=1)
test = test.drop(["Fence", "MiscFeature", "Utilities"], axis=1)
# other
test = test.fillna({"MSZoning": "RL"})
test = test.fillna({"Exterior1st": "VinylSd"})
test = test.fillna({"Exterior2nd": "VinylSd"})
train = train.fillna({"Electrical": "SBrkr"})
test = test.fillna({"KitchenQual": "TA"})
test = test.fillna({"Functional": "Typ"})
test = test.fillna({"SaleType": "WD"})
###Output
_____no_output_____
###Markdown
4.Explore outliers and delete
###Code
from xgboost.sklearn import XGBRegressor
from sklearn.linear_model import LinearRegression, Lasso, Ridge, ElasticNet
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
train_dummies = pd.get_dummies(pd.concat((train.drop(["SalePrice", "Id"], axis=1), test.drop(["Id"], axis=1)), axis=0)).iloc[: train.shape[0]]
test_dummies = pd.get_dummies(pd.concat((train.drop(["SalePrice", "Id"], axis=1), test.drop(["Id"], axis=1)), axis=0)).iloc[train.shape[0]:]
###Output
_____no_output_____
###Markdown
Used Ridge to find outliers
###Code
rid = Ridge(alpha=10)
rid.fit(train_dummies, y)
np.sqrt(-cross_val_score(rid, train_dummies, y, cv=5, scoring="neg_mean_squared_error")).mean()
y_pred = rid.predict(train_dummies)
resid = y - y_pred
mean_resid = resid.mean()
std_resid = resid.std()
z = (resid - mean_resid) / std_resid
z = np.array(z)
outliers1 = np.where(abs(z) > abs(z).std() * 3)[0]
outliers1
plt.figure(figsize=(6, 6))
plt.scatter(y, y_pred)
plt.scatter(y.iloc[outliers1], y_pred[outliers1])
plt.plot(range(10, 15), range(10, 15), color="black")
outliers = []
for i in outliers1:
outliers.append(i)
outliers
###Output
_____no_output_____
###Markdown
Delete outliers
###Code
train.columns
train = train.drop([30, 88, 142, 277, 328, 410, 462, 495, 523, 533, 581, 588, 628, 632, 681, 688, 710, 714, 728, 774, 812, 874, 898, 916, 968, 970, 1181, 1182, 1298, 1324, 1383, 1423, 1432, 1453])
y = train["SalePrice"]
y = np.log(y+1)
###Output
_____no_output_____
###Markdown
MODEL BUILDING
###Code
train_dummies = pd.get_dummies(pd.concat((train.drop(["SalePrice", "Id"], axis=1), test.drop(["Id"], axis=1)), axis=0)).iloc[: train.shape[0]]
test_dummies = pd.get_dummies(pd.concat((train.drop(["SalePrice", "Id"], axis=1), test.drop(["Id"], axis=1)), axis=0)).iloc[train.shape[0]:]
###Output
_____no_output_____
###Markdown
Modeling Using GBDT, XGBOOST, Lasso, Ridge, and combined them later gradient
###Code
gbr = GradientBoostingRegressor(max_depth=4, n_estimators=150)
gbr.fit(train_dummies, y)
np.sqrt(-cross_val_score(gbr, train_dummies, y, cv=5, scoring="neg_mean_squared_error")).mean()
###Output
_____no_output_____
###Markdown
XGBOOST
###Code
xgbr = XGBRegressor(max_depth=5, n_estimators=400)
xgbr.fit(train_dummies, y)
np.sqrt(-cross_val_score(xgbr, train_dummies, y, cv=5, scoring="neg_mean_squared_error")).mean()
###Output
_____no_output_____
###Markdown
LASSO
###Code
lasso = Lasso(alpha=0.00047)
lasso.fit(train_dummies, y)
np.sqrt(-cross_val_score(lasso, train_dummies, y, cv=5, scoring="neg_mean_squared_error")).mean()
###Output
_____no_output_____
###Markdown
RIDGE
###Code
rid = Ridge(alpha=13)
rid.fit(train_dummies, y)
np.sqrt(-cross_val_score(rid, train_dummies, y, cv=5, scoring="neg_mean_squared_error")).mean()
###Output
_____no_output_____
###Markdown
ENSEMBLE/COMBINED MODEL
###Code
train_predict = 0.1 * gbr.predict(train_dummies) + 0.3 * xgbr.predict(train_dummies) + 0.3 * lasso.predict(train_dummies) + 0.3 * rid.predict(train_dummies)
###Output
_____no_output_____
###Markdown
Manually modify the predicted value
###Code
plt.figure(figsize=(6, 6))
plt.scatter(y, train_predict)
plt.plot(range(10, 15), range(10, 15), color="green")
q1 = pd.DataFrame(train_predict).quantile(0.0042)
pre_df = pd.DataFrame(train_predict)
pre_df["SalePrice"] = train_predict
pre_df = pre_df[["SalePrice"]]
pre_df.loc[pre_df.SalePrice <= q1[0], "SalePrice"] = pre_df.loc[pre_df.SalePrice <= q1[0], "SalePrice"] *0.99
train_predict = np.array(pre_df.SalePrice)
plt.figure(figsize=(6, 6))
plt.scatter(y, train_predict)
plt.plot(range(10, 15), range(10, 15), color="red")
###Output
_____no_output_____
###Markdown
Prediction
###Code
test_predict = 0.1 * gbr.predict(test_dummies) + 0.3 * xgbr.predict(test_dummies) + 0.3 * lasso.predict(test_dummies) + 0.3 * rid.predict(test_dummies)
q1 = pd.DataFrame(test_predict).quantile(0.0042)
pre_df = pd.DataFrame(test_predict)
pre_df["SalePrice"] = test_predict
pre_df = pre_df[["SalePrice"]]
pre_df.loc[pre_df.SalePrice <= q1[0], "SalePrice"] = pre_df.loc[pre_df.SalePrice <= q1[0], "SalePrice"] *0.96
test_predict = np.array(pre_df.SalePrice)
sample_submission["SalePrice"] = np.exp(test_predict)-1
###sample_submission.to_csv("output11.csv", index=False)
###Output
_____no_output_____ |
M4 Data Mining/W1 Data Mining/Bank_KMeans_Student_File Aug 6.ipynb | ###Markdown
Bank datasetWe have a transaction details of 515 banks which include number of DD taken, Withdrawals, Deposits, Area of the branch and Average Walk-Ins. Profile the banks into segments and come up with recommendations for each segment. Import libraries and load data
###Code
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
data_df = pd.read_csv("bank.csv")
###Output
_____no_output_____
###Markdown
Checking the data
###Code
data_df.head()
data_df.shape
data_df.info()
###Output
_____no_output_____
###Markdown
Checking Summary Statistic
###Code
data_df.describe()
###Output
_____no_output_____
###Markdown
Checking for Duplicates There are no Duplicates in the dataset Scaling the data
###Code
# importing the StandardScaler Module
# Creating an object for the StandardScaler function
scaled_df = X.fit_transform(data_df.iloc[:,1:6])
scaled_df
###Output
_____no_output_____
###Markdown
Creating Clusters using KMeans Forming 2 Clusters with K=2
###Code
# Create K Means cluster and store the result in the object k_means
# Fit K means on the scaled_df
###Output
_____no_output_____
###Markdown
Cluster Output for all the observations
###Code
# Get the labels
k_means.labels_
###Output
_____no_output_____
###Markdown
Within Cluster Sum of Squares
###Code
k_means.inertia_
###Output
_____no_output_____
###Markdown
Forming clusters with K = 1,3,4,5,6 and comparing the WSS
###Code
k_means = KMeans(n_clusters = 1,random_state=1)
k_means.fit(scaled_df)
k_means.inertia_
k_means = KMeans(n_clusters = 3,random_state=1)
k_means.fit(scaled_df)
k_means.inertia_
k_means = KMeans(n_clusters = 4,random_state=1)
k_means.fit(scaled_df)
k_means.inertia_
k_means = KMeans(n_clusters = 5,random_state=1)
k_means.fit(scaled_df)
k_means.inertia_
k_means = KMeans(n_clusters = 6,random_state=1)
k_means.fit(scaled_df)
k_means.inertia_
###Output
_____no_output_____
###Markdown
WSS reduces as K keeps increasing Calculating WSS for other values of K - Elbow Method
###Code
wss =[]
for i in range(1,11):
KM = KMeans(n_clusters=i,random_state=1)
KM.fit(scaled_df)
wss.append(KM.inertia_)
wss
plt.plot(range(1,11), wss)
###Output
_____no_output_____
###Markdown
KMeans with K=3
###Code
###Output
_____no_output_____
###Markdown
Cluster evaluation for 3 clusters: the silhouette score
###Code
from sklearn.metrics import silhouette_samples, silhouette_score
# Calculating silhouette_score
###Output
_____no_output_____
###Markdown
KMeans with K=4
###Code
k_means = KMeans(n_clusters = 4,random_state=1)
k_means.fit(scaled_df)
labels = k_means.labels_
###Output
_____no_output_____
###Markdown
Cluster evaluation for 4 clusters
###Code
#from sklearn.metrics import silhouette_samples, silhouette_score
silhouette_score(scaled_df,labels)
###Output
_____no_output_____
###Markdown
silhouette score is better for 4 clusters than for 3 clusters. So, final clusters will be 4 Appending Clusters to the original dataset
###Code
data_df["Clus_kmeans4"] = labels
data_df.head()
###Output
_____no_output_____
###Markdown
Cluster Profiling
###Code
data_df.Clus_kmeans4.value_counts().sort_index()
clust_profile=data_df.drop(['Bank'],axis=1)
clust_profile=clust_profile.groupby('Clus_kmeans4').mean()
clust_profile['freq']=data_df.Clus_kmeans4.value_counts().sort_index()
clust_profile
###Output
_____no_output_____
###Markdown
- Cluster 0: Medium size bank with less withdrawal,walkin, DD but highest Deposit- Cluster 1: Medium size bank with less walkins and deposits and high withdrawals- Cluster 2: Small size bank with less deposit but highest walkins and Withdrawals, and large DD- Cluster 3: Large size bank with more number of walkins and highest DD, but less Deposits Some Recommendations 1. The banks in Cluster 3 has high DD and Withdrawals, but less Deposit. So it needs to improve in making the customers Deposit more. Relatively large number of customers are visiting these banks. So, can promote various deposit schemes to these customers.2. Customers in Cluster 3 seems to prefer payment through DD as these banks record the highest DD rate. Banks can check if DD is being made to other banks or to the same bank, and can look to create DD schemes for their own bank, so that customers will open their account with these banks and use the DD payment scheme.3. Customers preferring DD payment can go to banks either in Cluster 3 (if they need large space which can manage large crowd probably with more infrastructure facilities), or Cluster 2 (if they want small space where probably quick transaction can happen due to less crowd holding capacity) 4. Size of the bank doesn't matter in accomodating large group of customers inside the bank, as Cluster 2 though having the least Branch Area, has the highest daily walk ins. So, banks don't need to invest more in occupying large land space. This could mean Customers are visiting throughout the day rather than a large group of customers visiting during a period.5. Cluster 0 has large area and the proportion of withdrawals and deposits is almost equal. Most of these customers could be having a savings account since the withdrawals as well as DD are less when compared to other clusters. Customers visiting these banks are also lesser than other clusters. These banks can look bringing in more customers and increase the bank deposit by introducing various deposit schemes.6. Deposit is again less, while the withdrawals are much higher for Cluster 1. These banks can also look to introducing new deposit schemes.7. Banks in cluster 1 and 2, needs to focus on their infrastructure and banking facilities, since the area is lesser than cluster 0 and 3 , whereas daily walkins is the highest. These banks can also look for opportunities to cross-sell products to the customers.
###Code
#data_df.to_csv('km.csv')
###Output
_____no_output_____ |
09_selectores_basicos.ipynb | ###Markdown
Selectores básicos. Selectores.Los selectores son expresiones que permiten identificar uno o varios elementos dentro de un documento *HTML* e incluso algunos eventos.Los selectores son un elemento clave de las reglas de estilo, pero su aplicación va más allá de este ámbito. Los selectores también son muy uitlizados para el desarrollo de aplicaciones web.Para conocer más sobre la sintaxis de selectores es posible consultar la siguiente liga:https://www.w3schools.com/cssref/css_selectors.aspA continuación se describirán y ejemplificarán algunos de los más comunes. Selectores de elementos.Los selectores de elementos permiten identificar a todos los elementos de cierto tipo en un documento HTML por el nombre de las etiquetas.Para seleccionar a todos los elementos de un documento se utiliza el selector ```*```. **Ejemplos:** * El selector para todos los elementos `````` es ```p```.* El selector para todos los elementos `````` es ```a```.* El selector para todos los elementos `````` es ```ol```.* El selector para todos los elementos `````` es ```li```.* El selector para todos los elementos `````` es ```body```. **Ejemplo:*** Las siguientes celdas modificarán el color de fondo de todos los elementos ``````de este documento.
###Code
%%html
<style>
p {
background-color: green;
}
</style>
%%html
<style>
p {
background-color: LightCyan;
}
</style>
%%html
<style>
p {
background-color: white;
}
</style>
###Output
_____no_output_____
###Markdown
Selectores por identificador.Para encontrar un elemento a partir de si atributo ```id``` se utiliza el signo de gato `````` seguido del valor asignado a ```id```:```(identificador)``` **Ejemplo:** * Para identificar a un elemento que tiene el atributo ```id="ejemplo_3-1"```, se utiliza el selector ```ejemplo_3-1```.
###Code
%%html
<div id="ejemplo_3-1">Hola.</div>
%%html
<style>
#ejemplo_3-1 {
background-color:blue;
width: 50px;
height: 50px;
color: white;
}
</style>
###Output
_____no_output_____
###Markdown
Selectores por clase.Para encontrar los elementos de una clase a partir de su atributo *class* se utiliza el punto ```.``` seguido del valor asignado al atributo ```class```:Para encontrar a todos los elementos de una clase se utiliza:```.(clase)```Para encontrar a los elementos de un tipo específico que comparten una clase se utiliza:```(selector de elemento).(clase)``` **Ejemplos:** * Para identificar a todos los elementos con el atributo ```class="clase-1"```, se utiliza el selector ```.clase_1```.* Para identificar a todos los elementos de tipo ```p``` con el atributo ```class="solitario"```, se utiliza el selector ```p.solitario```.
###Code
%%html
<h4 class="clase_1">Ejemplo de clases</h4>
<p> Este es un párrafo normal.</p>
<p class="clase_1"> Este es un párrafo de una <span class="clase_1">clase especial</span>
que puede ser segmentada.</p>
<p> Las clases aplican a <span class="clase_1">cualquier elemento.</span> de un documento.</p>
<p>Las clases son muy útiles.</p>
%%html
<style>
.clase_1{
background-color: Gold;
color: blue;
}
p.clase_1{
color: green;
}
###Output
_____no_output_____
###Markdown
Selectores por atributos.Es posible encontrar elementos que tengan un atributo específico mediante el uso de corchetes:```[(atributo)]```Para encontrar a los elementos que tengan un atributo con un valor específico se utiliza la sintaxis siguiente:```[(atributo)="(valor)"]``` **Ejemplos:*** El selector ```[peso]``` buscará a todos los elementos que contengan al atributo ```peso```.* El selector ```[peso="10"]``` buscará a todos los elementos que contengan al atributo ```peso="10"```.* El selector ```[peso="11"]``` buscará a todos los elementos que contengan al atributo ```peso="10"```.
###Code
%%html
<ul>
<li peso="5">Este es un elemento que pesa 5.</li>
<li peso="11">Este es un elemento que pesa 11.</li>
<li peso="10">Este es un elemento que pesa 10.</li>
<li>Este es un elemento que no pesa.</li>
<li peso="5">Este es un elemento que pesa 5.</li>
<li>Este es un elemento que no pesa.</li>
<li peso="10">Este es un elemento que pesa 10.</li>
<li peso="10">Este es un elemento que pesa 10.</li>
</ol>
%%html
<style>
[peso] {
background-color: gold;
}
[peso="10"] {
background-color: azure;
color: red;
}
[peso="11"] {
background-color: skyblue;
color: cyan;
}
</style>
###Output
_____no_output_____
###Markdown
Agrupamiento de varios selectores.Para identificar más de un selectores se utiliza la coma ```,```. De ese modo se puede aplicar una regla a distintos elementos. **Ejemplo:** La regla ```color:red;``` se aplicará a todos los elementos `````` y `````` dentro de un documento HTML.``` (selector 1), (selector 2), ..., (selector n){ (reglas) } ```
###Code
%%html
<style>
p, a {
color:red;
}
</style>
###Output
_____no_output_____
###Markdown
Elementos dentro de un elemento.Es posible identificar elementos contenidos en otro elemento utilizando un espacio.``` (selector contenedor) (selector contenido){ (reglas) } ``` **Ejemplo:*** La regla ```color: green;``` se aplicará a los elementos `````` que estén dentro de un elemento ``````.* La regla ```color: yellow;``` se aplicará a los elementos `````` que estén dentro de un elemento ``````.* La regla ```color: aliceblue;``` se aplicará a los elementos ``````.
###Code
%%html
<h4>Ejemplo de <b>selectores.<b/></h4>.
<ul>
<li>uno</li>
<li>dos</li>
<li><b>tres</b></li>
<li>cuatro</li>
</ul>
<p><b>Este es un ejemplo.</b></p>
%%html
<style>
li b {
color: green;
}
p b {
color: yellow;
}
b {
color: aliceblue;
}
</style>
###Output
_____no_output_____ |
PlutonAI/01_intro_PlutonAI.ipynb | ###Markdown
Using CNN for dogs vs cats To illustrate the Deep Learning pipeline, we are going to use a pretrained model to enter the [Dogs vs Cats](https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition) competition at Kaggle. There are 25,000 labelled dog and cat photos available for training, and 12,500 in the test set that we have to try to label for this competition. According to the Kaggle web-site, when this competition was launched (end of 2013): *"**State of the art**: The current literature suggests machine classifiers can score above 80% accuracy on this task"*. So if you can beat 80%, then you will be at the cutting edge as of 2013! Imports
###Code
import numpy as np
import matplotlib.pyplot as plt
import os
import torch
import torch.nn as nn
import torchvision
from torchvision import models,transforms,datasets
import time
%matplotlib inline
###Output
_____no_output_____
###Markdown
Here you see that the latest version of PyTorch is installed by default.
###Code
torch.__version__
import sys
sys.version
###Output
_____no_output_____
###Markdown
Check if GPU is available and if not change the [runtime](https://jovianlin.io/pytorch-with-gpu-in-google-colab/).
###Code
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print('Using gpu: %s ' % torch.cuda.is_available())
###Output
_____no_output_____
###Markdown
Downloading the data You can download the full dataset from Kaggle directly.Alternatively, Jeremy Howard (fast.ai) provides a direct link to the catvsdogs [dataset](http://files.fast.ai/data/dogscats.zip). He's separated the cats and dogs into separate folders and created a validation folder as well.For test purpose (or if you run on cpu), you should use the (small) sample directory.
###Code
%mkdir data
%cd /content/data/
!wget http://files.fast.ai/data/dogscats.zip
!unzip dogscats.zip
%ls
%cd dogscats/
%ls
###Output
_____no_output_____
###Markdown
The structure of the sub-folders inside the folder `dogscats` will be important for what follows:```bash.├── test1 contains 12500 images of cats and dogs├── train| └── cats contains 11500 images of cats| └── dogs contains 11500 images of dogs├── valid| └── cats contains 1000 images of cats| └── dogs contains 1000 images of dogs├── sample| └── train| └── cats contains 8 images of cats| └── dogs contains 8 images of dogs | └── valid | └── cats contains 4 images of cats| └── dogs contains 4 images of dogs ├── models empty folder```You see that the 12 500 images of the test are in the `test1` sub-folder; the dataset of 25 000 labelled images has been split into a train set and a validation set.The sub-folder `sample` is here only to make sure the code is running properly on a very small dataset. Data processing
###Code
%cd ..
###Output
_____no_output_____
###Markdown
Below, we give the path where the data is stored. If you are running this code on your computer, you should modifiy this cell.
###Code
data_dir = '/content/data/dogscats'
###Output
_____no_output_____
###Markdown
```datasets``` is a class of the ```torchvision``` package (see [torchvision.datasets](http://pytorch.org/docs/master/torchvision/datasets.html)) and deals with data loading. It integrates a multi-threaded loader that fetches images from the disk, groups them in mini-batches and serves them continously to the GPU right after each _forward_/_backward_ pass through the network.Images needs a bit of preparation before passing them throught the network. They need to have all the same size $224\times 224 \times 3$ plus some extra formatting done below by the normalize transform (explained later).
###Code
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
imagenet_format = transforms.Compose([
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])
dsets = {x: datasets.ImageFolder(os.path.join(data_dir, x), imagenet_format)
for x in ['train', 'valid']}
os.path.join(data_dir,'train')
###Output
_____no_output_____
###Markdown
Interactive help on jupyter notebook thanks to `?`
###Code
?datasets.ImageFolder
###Output
_____no_output_____
###Markdown
We see that `datasets.ImageFolder` has attributes: classes, class_to_idx, imgs.Let see what they are?
###Code
dsets['train'].classes
###Output
_____no_output_____
###Markdown
The name of the classes are directly inferred from the structure of the folder:```bash├── train| └── cats| └── dogs```
###Code
dsets['train'].class_to_idx
###Output
_____no_output_____
###Markdown
The label 0 will correspond to cats and 1 to dogs.Below, you see that the first 5 imgs are pairs (location_of_the_image, label):
###Code
dsets['train'].imgs[:5]
dset_sizes = {x: len(dsets[x]) for x in ['train', 'valid']}
dset_sizes
###Output
_____no_output_____
###Markdown
As expected we have 23 000 images in the training set and 2 000 in the validation set.Below, we store the classes in the variable `dset_classes`:
###Code
dset_classes = dsets['train'].classes
###Output
_____no_output_____
###Markdown
The ```torchvision``` packages allows complex pre-processing/transforms of the input data (_e.g._ normalization, cropping, flipping, jittering). A sequence of transforms can be grouped in a pipeline with the help of the ```torchvision.transforms.Compose``` function, see [torchvision.transforms](http://pytorch.org/docs/master/torchvision/transforms.html) The magic help `?` allows you to retrieve function you defined and forgot!
###Code
?imagenet_format
###Output
_____no_output_____
###Markdown
Where is this normalization coming from?As explained in the [PyTorch doc](https://pytorch.org/docs/stable/torchvision/models.html), you will use a pretrained model. All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using `mean = [0.485, 0.456, 0.406]` and `std = [0.229, 0.224, 0.225]`.
###Code
loader_train = torch.utils.data.DataLoader(dsets['train'], batch_size=64, shuffle=True, num_workers=6)
?torch.utils.data.DataLoader
loader_valid = torch.utils.data.DataLoader(dsets['valid'], batch_size=5, shuffle=False, num_workers=6)
###Output
_____no_output_____
###Markdown
Try to understand what the following cell is doing?
###Code
count = 1
for data in loader_valid:
print(count, end=',')
if count == 1:
inputs_try,labels_try = data
count +=1
labels_try
inputs_try.shape
###Output
_____no_output_____
###Markdown
Got it: the validation dataset contains 2 000 images, hence this is 400 batches of size 5. `labels_try` contains the labels of the first batch and `inputs_try` the images of the first batch.What is an image for your computer?
###Code
inputs_try[0]
###Output
_____no_output_____
###Markdown
A 3-channel RGB image is of shape (3 x H x W). Note that entries can be negative because of the normalization. A small function to display images:
###Code
def imshow(inp, title=None):
# Imshow for Tensor.
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = np.clip(std * inp + mean, 0,1)
plt.imshow(inp)
if title is not None:
plt.title(title)
# Make a grid from batch from the validation data
out = torchvision.utils.make_grid(inputs_try)
imshow(out, title=[dset_classes[x] for x in labels_try])
# Get a batch of training data
inputs, classes = next(iter(loader_train))
n_images = 8
# Make a grid from batch
out = torchvision.utils.make_grid(inputs[0:n_images])
imshow(out, title=[dset_classes[x] for x in classes[0:n_images]])
###Output
_____no_output_____
###Markdown
Creating VGG Model The torchvision module comes with a zoo of popular CNN architectures which are already trained on [ImageNet](http://www.image-net.org/) (1.2M training images). When called the first time, if ```pretrained=True``` the model is fetched over the internet and downloaded to ```~/.torch/models```.For next calls, the model will be directly read from there.
###Code
model_vgg = models.vgg16(pretrained=True)
###Output
_____no_output_____
###Markdown
We will first use VGG Model without any modification. In order to interpret the results, we need to import the 1000 ImageNet categories, available at: [https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json](https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json)
###Code
!wget https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json
import json
fpath = '/content/data/imagenet_class_index.json'
with open(fpath) as f:
class_dict = json.load(f)
dic_imagenet = [class_dict[str(i)][1] for i in range(len(class_dict))]
dic_imagenet[:4]
inputs_try , labels_try = inputs_try.to(device), labels_try.to(device)
model_vgg = model_vgg.to(device)
outputs_try = model_vgg(inputs_try)
outputs_try
outputs_try.shape
###Output
_____no_output_____
###Markdown
To translate the outputs of the network into 'probabilities', we pass it through a [Softmax function](https://en.wikipedia.org/wiki/Softmax_function)
###Code
m_softm = nn.Softmax(dim=1)
probs = m_softm(outputs_try)
vals_try,preds_try = torch.max(probs,dim=1)
###Output
_____no_output_____
###Markdown
Let check, that we obtain a probability!
###Code
torch.sum(probs,1)
vals_try
print([dic_imagenet[i] for i in preds_try.data])
out = torchvision.utils.make_grid(inputs_try.data.cpu())
imshow(out, title=[dset_classes[x] for x in labels_try.data.cpu()])
###Output
_____no_output_____
###Markdown
Modifying the last layer and setting the gradient false to all layers
###Code
print(model_vgg)
###Output
_____no_output_____
###Markdown
We'll learn about what these different blocks do later in the course. For now, it's enough to know that:- Convolution layers are for finding small to medium size patterns in images -- analyzing the images locally- Dense (fully connected) layers are for combining patterns across an image -- analyzing the images globally- Pooling layers downsample -- in order to reduce image size and to improve invariance of learned features  In this practical example, our goal is to use the already trained model and just change the number of output classes. To this end we replace the last ```nn.Linear``` layer trained for 1000 classes to ones with 2 classes. In order to freeze the weights of the other layers during training, we set the field ```required_grad=False```. In this manner no gradient will be computed for them during backprop and hence no update in the weights. Only the weights for the 2 class layer will be updated.
###Code
for param in model_vgg.parameters():
param.requires_grad = False
model_vgg.classifier._modules['6'] = nn.Linear(4096, 2)
model_vgg.classifier._modules['7'] = torch.nn.LogSoftmax(dim = 1)
###Output
_____no_output_____
###Markdown
PyTorch documentation for [LogSoftmax](https://pytorch.org/docs/stable/nn.htmllogsoftmax)
###Code
print(model_vgg.classifier)
###Output
_____no_output_____
###Markdown
We load the model on GPU.
###Code
model_vgg = model_vgg.to(device)
###Output
_____no_output_____
###Markdown
Training the fully connected module Creating loss function and optimizerPyTorch documentation for [NLLLoss](https://pytorch.org/docs/stable/nn.htmlnllloss) and the [torch.optim module](https://pytorch.org/docs/stable/optim.htmlmodule-torch.optim)
###Code
criterion = nn.NLLLoss()
lr = 0.001
optimizer_vgg = torch.optim.SGD(model_vgg.classifier[6].parameters(),lr = lr)
###Output
_____no_output_____
###Markdown
Training the model
###Code
def train_model(model,dataloader,size,epochs=1,optimizer=None):
model.train()
for epoch in range(epochs):
running_loss = 0.0
running_corrects = 0
for inputs,classes in dataloader:
inputs = inputs.to(device)
classes = classes.to(device)
outputs = model(inputs)
loss = criterion(outputs,classes)
optimizer.zero_grad()
loss.backward()
optimizer.step()
_,preds = torch.max(outputs.data,1)
# statistics
running_loss += loss.data.item()
running_corrects += torch.sum(preds == classes.data)
epoch_loss = running_loss / size
epoch_acc = running_corrects.data.item() / size
print('Loss: {:.4f} Acc: {:.4f}'.format(
epoch_loss, epoch_acc))
%%time
train_model(model_vgg,loader_train,size=dset_sizes['train'],epochs=2,optimizer=optimizer_vgg)
def test_model(model,dataloader,size):
model.eval()
predictions = np.zeros(size)
all_classes = np.zeros(size)
all_proba = np.zeros((size,2))
i = 0
running_loss = 0.0
running_corrects = 0
for inputs,classes in dataloader:
inputs = inputs.to(device)
classes = classes.to(device)
outputs = model(inputs)
loss = criterion(outputs,classes)
_,preds = torch.max(outputs.data,1)
# statistics
running_loss += loss.data.item()
running_corrects += torch.sum(preds == classes.data)
predictions[i:i+len(classes)] = preds.to('cpu').numpy()
all_classes[i:i+len(classes)] = classes.to('cpu').numpy()
all_proba[i:i+len(classes),:] = outputs.data.to('cpu').numpy()
i += len(classes)
epoch_loss = running_loss / size
epoch_acc = running_corrects.data.item() / size
print('Loss: {:.4f} Acc: {:.4f}'.format(
epoch_loss, epoch_acc))
return predictions, all_proba, all_classes
predictions, all_proba, all_classes = test_model(model_vgg,loader_valid,size=dset_sizes['valid'])
# Get a batch of training data
inputs, classes = next(iter(loader_valid))
out = torchvision.utils.make_grid(inputs[0:n_images])
imshow(out, title=[dset_classes[x] for x in classes[0:n_images]])
outputs = model_vgg(inputs[:n_images].to(device))
print(torch.exp(outputs))
classes[:n_images]
###Output
_____no_output_____
###Markdown
Speeding up the learning by precomputing featuresHere you are wasting a lot of time computing over and over the same quantities. Indeed, the first part of the VGG model (called `features` and made of convolutional layers) is frozen and never updated. Hence, we can precompute for each image in the dataset, the output of these convolutional layers as these outputs will always be the same during your training process.This is what is done below.
###Code
x_try = model_vgg.features(inputs_try)
x_try.shape
###Output
_____no_output_____
###Markdown
You see that the features computed for an image is of shape 512x7x7 (above we have a batch corresponding to 5 images).
###Code
def preconvfeat(dataloader):
conv_features = []
labels_list = []
for data in dataloader:
inputs,labels = data
inputs = inputs.to(device)
labels = labels.to(device)
x = model_vgg.features(inputs)
conv_features.extend(x.data.cpu().numpy())
labels_list.extend(labels.data.cpu().numpy())
conv_features = np.concatenate([[feat] for feat in conv_features])
return (conv_features,labels_list)
%%time
conv_feat_train,labels_train = preconvfeat(loader_train)
conv_feat_train.shape
%%time
conv_feat_valid,labels_valid = preconvfeat(loader_valid)
###Output
_____no_output_____
###Markdown
Creating a new data generatorWe will not load images anymore, so we need to build our own data loader. If you do not understand the cell below, it is OK! We will come back to it in Lesson 5...
###Code
dtype=torch.float
datasetfeat_train = [[torch.from_numpy(f).type(dtype),torch.tensor(l).type(torch.long)] for (f,l) in zip(conv_feat_train,labels_train)]
datasetfeat_train = [(inputs.reshape(-1), classes) for [inputs,classes] in datasetfeat_train]
loaderfeat_train = torch.utils.data.DataLoader(datasetfeat_train, batch_size=128, shuffle=True)
%%time
train_model(model_vgg.classifier,dataloader=loaderfeat_train,size=dset_sizes['train'],epochs=50,optimizer=optimizer_vgg)
datasetfeat_valid = [[torch.from_numpy(f).type(dtype),torch.tensor(l).type(torch.long)] for (f,l) in zip(conv_feat_valid,labels_valid)]
datasetfeat_valid = [(inputs.reshape(-1), classes) for [inputs,classes] in datasetfeat_valid]
loaderfeat_valid = torch.utils.data.DataLoader(datasetfeat_valid, batch_size=128, shuffle=False)
predictions, all_proba, all_classes = test_model(model_vgg.classifier,dataloader=loaderfeat_valid,size=dset_sizes['valid'])
###Output
_____no_output_____
###Markdown
4. Viewing model prediction (qualitative analysis)The most important metrics for us to look at are for the validation set, since we want to check for over-fitting.With our first model we should try to overfit before we start worrying about how to handle that - there's no point even thinking about regularization, data augmentation, etc if you're still under-fitting! (We'll be looking at these techniques after the 2 weeks break...)As well as looking at the overall metrics, it's also a good idea to look at examples of each of: 1. A few correct labels at random 2. A few incorrect labels at random 3. The most correct labels of each class (ie those with highest probability that are correct) 4. The most incorrect labels of each class (ie those with highest probability that are incorrect) 5. The most uncertain labels (ie those with probability closest to 0.5).In general, these are particularly useful for debugging problems in the model. Since our model is very simple, there may not be too much to learn at this stage...
###Code
# Number of images to view for each visualization task
n_view = 8
correct = np.where(predictions==all_classes)[0]
len(correct)/dset_sizes['valid']
from numpy.random import random, permutation
idx = permutation(correct)[:n_view]
idx
loader_correct = torch.utils.data.DataLoader([dsets['valid'][x] for x in idx],batch_size = n_view,shuffle=True)
for data in loader_correct:
inputs_cor,labels_cor = data
# Make a grid from batch
out = torchvision.utils.make_grid(inputs_cor)
imshow(out, title=[l.item() for l in labels_cor])
from IPython.display import Image, display
for x in idx:
display(Image(filename=dsets['valid'].imgs[x][0], retina=True))
incorrect = np.where(predictions!=all_classes)[0]
for x in permutation(incorrect)[:n_view]:
#print(dsets['valid'].imgs[x][1])
display(Image(filename=dsets['valid'].imgs[x][0], retina=True))
#3. The images we most confident were cats, and are actually cats
correct_cats = np.where((predictions==0) & (predictions==all_classes))[0]
most_correct_cats = np.argsort(all_proba[correct_cats,1])[:n_view]
for x in most_correct_cats:
display(Image(filename=dsets['valid'].imgs[correct_cats[x]][0], retina=True))
#3. The images we most confident were dogs, and are actually dogs
correct_dogs = np.where((predictions==1) & (predictions==all_classes))[0]
most_correct_dogs = np.argsort(all_proba[correct_dogs,0])[:n_view]
for x in most_correct_dogs:
display(Image(filename=dsets['valid'].imgs[correct_dogs[x]][0], retina=True))
###Output
_____no_output_____ |
pyAnVIL/docs/_static/0.0.2.ipynb | ###Markdown
pyAnVIL dashboard installation> Ensure latest version installed
###Code
# Install a pip package in the current Jupyter kernel
import sys
# !{sys.executable} -m pip install pyanvil --upgrade
!{sys.executable} -m pip show pyanvil
###Output
Name: pyAnVIL
Version: 0.0.2rc16
Summary: AnVIL client library. Combines gen3, terra client APIs with single signon and data harmonization use cases.
Home-page: https://github.com/anvilproject/client-apis
Author: The AnVIL project
Author-email: [email protected]
License: UNKNOWN
Location: /home/jupyter-user/notebooks/packages
Requires: google-cloud-storage, Click, firecloud, gen3, attrdict, xmltodict
Required-by:
###Markdown
validation> Note: As a workaround, the tracking spreadsheet is embedded in the python package. This spreadsheet provides a list of workspaces that should exist and associated dbGap accessions
###Code
# check installation, import should work
import os
import time
# embedded data tracking spreadsheet should exist
# see https://docs.google.com/spreadsheets/d/1UvQimGHggygeJeTIPjIi6Ze3ryxsUdVjjn8BoIFkyho/edit#gid=552844485
from anvil.dbgap.api import DEFAULT_OUTPUT_PATH
assert os.path.isfile(DEFAULT_OUTPUT_PATH), "embedded data tracking spreadsheet should exist"
###Output
_____no_output_____
###Markdown
extract> Extract all meta data, reconcile with google bucket and dbGap data
###Code
import json
import logging
from anvil.util.reconciler import aggregate, DEFAULT_NAMESPACE
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s')
# store aggregated data locally
DASHBOARD_OUTPUT_PATH = '/tmp/data_dashboard.json'
def reconcile_all(user_project, consortiums, namespace=DEFAULT_NAMESPACE, output_path=DASHBOARD_OUTPUT_PATH):
"""Reconcile and aggregate results.
e.g. bin/reconciler --user_project <your-billing-project> --consortium CMG AnVIL_CMG.* --consortium CCDG AnVIL_CCDG.* --consortium GTEx ^AnVIL_GTEx_V8_hg38$ --consortium ThousandGenomes ^1000G-high-coverage-2019$
"""
with open(output_path, 'w') as outs:
json.dump({'projects': [v for v in aggregate(namespace, user_project, consortiums)]}, outs)
logging.info("Starting aggregation for all AnVIL workspaces, this will take several minutes.")
reconcile_all(
user_project = os.environ['GOOGLE_PROJECT'],
consortiums = (
('CMG', 'AnVIL_CMG.*'),
('CCDG', 'AnVIL_CCDG.*'),
('GTEx', '^AnVIL_GTEx_V8_hg38$'),
('ThousandGenomes', '^1000G-high-coverage-2019$')
)
)
###Output
2020-09-10 19:34:04,757 INFO Starting aggregation for all AnVIL workspaces, this will take several minutes.
2020-09-10 19:35:11,890 WARNING AnVIL_CMG_Broad_Brain_Gleeson_WGS missing dbGap accession
2020-09-10 19:35:17,522 WARNING AnVIL_CMG_Broad_Brain_Engle_WGS missing dbGap accession
2020-09-10 19:35:20,968 WARNING AnVIL_CMG_Broad_Kidney_Pollak_WES missing dbGap accession
2020-09-10 19:35:24,529 WARNING AnVIL_CMG_Broad_Orphan_Scott_WES missing dbGap accession
2020-09-10 19:35:28,651 WARNING AnVIL_CMG_Broad_Blood_Fleming_WES missing dbGap accession
2020-09-10 19:35:31,041 WARNING anvil_ccdg_broad_ai_ibd_daly_niddk_cho_wes missing dbGap accession
2020-09-10 19:35:32,566 WARNING phs001155/ error: No qualified study for phs001155
2020-09-10 19:35:32,567 WARNING No study found AnVIL_CCDG_WashU_CVD_EOCAD_BioMe_WGS accession: phs001155
2020-09-10 19:35:32,938 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_chung_asd_exome missing dbGap accession
2020-09-10 19:35:33,649 WARNING Study missing sample list AnVIL_CCDG_Broad_AI_IBD_Brant_DS-IBD_WGS accession: phs001642 'NoneType' object is not subscriptable
2020-09-10 19:35:34,193 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_ac-boston_asd_exome missing dbGap accession
2020-09-10 19:35:36,194 WARNING anvil_ccdg_broad_ai_ibd_niddk_daly_silverberg_wes missing dbGap accession
2020-09-10 19:35:38,451 WARNING phs001601/ error: No qualified study for phs001601
2020-09-10 19:35:38,453 WARNING No study found AnVIL_CCDG_Broad_CVD_AFib_Penn_WGS accession: phs001601
2020-09-10 19:35:40,823 WARNING anvil_ccdg_broad_ai_ibd_daly_vermeire_wes missing dbGap accession
2020-09-10 19:35:41,080 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_lattig_asd_exome missing dbGap accession
2020-09-10 19:35:42,628 WARNING AnVIL_CCDG_WashU_CVD_EOCAD_Harvard-Costa-Rica_WGS missing dbGap accession
2020-09-10 19:35:46,350 WARNING phs001579/ error: No qualified study for phs001579
2020-09-10 19:35:46,353 WARNING No study found AnVIL_CCDG_WashU_CVD_EOCAD_METSIM_WGS accession: phs001579
2020-09-10 19:35:46,996 WARNING AnVIL_CCDG_WashU_CVD_EOCAD_Finland-CHD_WGS missing dbGap accession
2020-09-10 19:35:47,224 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_puura_asd_exome missing dbGap accession
2020-09-10 19:35:52,498 WARNING AnVIL_CCDG_NYGC_NP_Autism_ACE2_DS-MDS_WGS missing dbGap accession
2020-09-10 19:35:52,702 WARNING anvil_ccdg_broad_ai_ibd_niddk_daly_brant_wes missing dbGap accession
2020-09-10 19:35:56,608 WARNING AnVIL_CCDG_Broad_MI_BRAVE_GRU_WES missing dbGap accession
2020-09-10 19:35:59,001 WARNING Study missing sample list AnVIL_CCDG_Broad_AI_IBD_McGovern_WGS accession: phs001642 'NoneType' object is not subscriptable
2020-09-10 19:36:00,430 WARNING AnVIL_CCDG_WashU_CVD_EOCAD_BioImage_WGS missing dbGap accession
2020-09-10 19:36:01,535 WARNING anvil_ccdg_broad_ai_ibd_daly_mccauley_wes missing dbGap accession
2020-09-10 19:36:03,115 WARNING anvil_ccdg_broad_ai_ibd_daly_lewis_ccfa_wes missing dbGap accession
2020-09-10 19:36:06,084 WARNING AnVIL_CCDG_WASHU_PAGE missing dbGap accession
2020-09-10 19:36:06,711 WARNING Study missing sample list AnVIL_CCDG_Broad_AI_IBD_Cho_WGS accession: phs001642 'NoneType' object is not subscriptable
2020-09-10 19:36:07,049 WARNING AnVIL_CCDG_NYGC_NP_Autism_SAGE_WGS missing dbGap accession
2020-09-10 19:36:07,223 WARNING AnVIL_CCDG_Broad_Spalletta_HMB_NPU_MDS_WES missing dbGap accession
2020-09-10 19:36:07,368 WARNING Study missing sample list AnVIL_CCDG_Broad_AI_IBD_Newberry_WGS accession: phs001642 'NoneType' object is not subscriptable
2020-09-10 19:36:08,119 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_menashe_asd_exome missing dbGap accession
2020-09-10 19:36:08,451 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_AGRE_asd_exome missing dbGap accession
2020-09-10 19:36:09,383 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_domenici_asd_exome missing dbGap accession
2020-09-10 19:36:09,974 WARNING AnVIL_CCDG_Baylor_CVD_HemStroke_ERICH_WGS missing dbGap accession
2020-09-10 19:36:11,923 WARNING anvil_ccdg_broad_ai_ibd_daly_kupcinskas_wes missing dbGap accession
2020-09-10 19:36:16,476 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_TASC_asd_exome missing dbGap accession
2020-09-10 19:36:17,198 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_passos-bueno_asd_exome missing dbGap accession
2020-09-10 19:36:18,038 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_AGRE-FEMF_asd_exome missing dbGap accession
2020-09-10 19:36:18,304 WARNING anvil_ccdg_broad_ai_ibd_daly_bernstein_wes missing dbGap accession
2020-09-10 19:36:18,594 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_control_NIMH_asd_exome missing dbGap accession
2020-09-10 19:36:19,942 WARNING anvil_ccdg_broad_ai_ibd_daly_louis_wes missing dbGap accession
2020-09-10 19:36:21,577 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_renieri_asd_exome missing dbGap accession
2020-09-10 19:36:21,901 WARNING anvil_ccdg_broad_ai_ibd_daly_chung_gider_wes missing dbGap accession
2020-09-10 19:36:25,917 WARNING AnVIL_CCDG_Broad_NP_Autism_State-Sanders_WGS missing dbGap accession
2020-09-10 19:36:26,143 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_barbosa_asd_exome missing dbGap accession
2020-09-10 19:36:26,349 WARNING anvil_ccdg_broad_ai_ibd_niddk_daly_duerr_wes missing dbGap accession
2020-09-10 19:36:26,903 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_herman_asd_exome missing dbGap accession
2020-09-10 19:36:29,389 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_palotie_asd_exome missing dbGap accession
2020-09-10 19:36:30,394 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_kolevzon_asd_exome missing dbGap accession
2020-09-10 19:36:31,423 WARNING AnVIL_CCDG_Broad_NP_Epilepsy_USAFEB_GRU_WES missing dbGap accession
2020-09-10 19:36:32,236 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_hertz-picciotto_asd_exome missing dbGap accession
2020-09-10 19:36:33,531 WARNING AnVIL_CCDG_NYGC_NP_Autism_TASC_WGS missing dbGap accession
2020-09-10 19:36:33,807 WARNING AnVIL_CCDG_WashU_CVD_EOCAD_Emory_WGS missing dbGap accession
2020-09-10 19:36:34,623 WARNING anvil_ccdg_broad_ai_ibd_daly_xavier_share_wes missing dbGap accession
2020-09-10 19:36:35,593 WARNING AnVIL_CCDG_Broad_CVD_AFib_UCSF_WGS missing dbGap accession
2020-09-10 19:36:36,502 WARNING Study missing sample list AnVIL_CCDG_Broad_AI_IBD_McCauley_WGS accession: phs001642 'NoneType' object is not subscriptable
2020-09-10 19:36:36,677 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_pericak-vance_asd_exome_ missing dbGap accession
2020-09-10 19:36:36,821 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_weiss_asd_exome missing dbGap accession
2020-09-10 19:36:37,538 WARNING Study missing sample list AnVIL_CCDG_Broad_AI_IBD_Kugathasan_WGS accession: phs001642 'NoneType' object is not subscriptable
2020-09-10 19:36:37,811 WARNING AnVIL_CCDG_NYGC_NP_Autism_ACE2_GRU-MDS_WGS missing dbGap accession
2020-09-10 19:36:41,784 WARNING phs001569/ error: No qualified study for phs001569
2020-09-10 19:36:41,785 WARNING No study found ANVIL_CCDG_Broad_CVD_EOCAD_PROMIS_ARRAY accession: phs001569
2020-09-10 19:36:42,747 WARNING AnVIL_CCDG_Baylor_CVD_EOCAD_BioMe_WGS missing dbGap accession
2020-09-10 19:36:43,745 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_goethe_asd_exome missing dbGap accession
2020-09-10 19:36:44,358 WARNING AnVIL_CCDG_WashU_CVD-NP-AI_Controls_VCControls_WGS missing dbGap accession
2020-09-10 19:36:44,768 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_mcpartland_asd_exome missing dbGap accession
2020-09-10 19:36:45,154 WARNING AnVIL_CCDG_NYGC_NP_Autism_HMCA_WGS missing dbGap accession
2020-09-10 19:36:45,496 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_persico_asd_exome missing dbGap accession
2020-09-10 19:36:46,498 WARNING phs001569/ error: No qualified study for phs001569
2020-09-10 19:36:46,500 WARNING No study found AnVIL_CCDG_Broad_CVD_EOCAD_PROMIS_WGS accession: phs001569
2020-09-10 19:36:48,256 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_brusco_asd_exome missing dbGap accession
2020-09-10 19:36:50,565 WARNING Study missing sample list AnVIL_CCDG_Broad_AI_IBD_Brant_HMB_WGS accession: phs001642 'NoneType' object is not subscriptable
2020-09-10 19:36:51,899 WARNING AnVIL_ccdg_asc_ndd_daly_talkowski_parellada_asd_exome missing dbGap accession
###Markdown
validate
###Code
# validate output
import json
import os
DASHBOARD_OUTPUT_PATH = '/tmp/data_dashboard.json'
assert os.path.isfile(DASHBOARD_OUTPUT_PATH), "dashboard should exist"
with open(DASHBOARD_OUTPUT_PATH, 'r') as inputs:
dashboard_data = json.load(inputs)
###Output
_____no_output_____
###Markdown
transform> Flatten the results into a table
###Code
from anvil.util.reconciler import flatten
import pandas as pd
(flattened, column_names) = flatten(dashboard_data['projects'])
df = pd.DataFrame(flattened)
df.columns = column_names
# Print the data (all rows, all columns)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
df
###Output
_____no_output_____
###Markdown
summarize> problems with comma separated list of workspaces
###Code
# explore
flattened = []
problems = set([problem for project in dashboard_data['projects'] for problem in project['problems']])
for problem in problems:
projects = [project['project_id'] for project in dashboard_data['projects'] if problem in project['problems']]
flattened.append([problem, ','.join(projects)])
# Print the data (all rows, all columns)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
pd.set_option('display.colheader_justify', 'left')
df = pd.DataFrame(flattened)
df.columns = ['problem', 'affected_workspaces']
df = df.style.set_properties(**{'text-align': 'left'})
df
# print (df.to_string (justify='left', index=False))
###Output
_____no_output_____
###Markdown
"load" > Copy results to bucket
###Code
# copy json results to bucket
!gsutil cp /tmp/data_dashboard.json $WORKSPACE_BUCKET
# create a tsv from dataframe
df.to_csv("/tmp/data_dashboard.tsv", sep="\t")
# copy json results to bucket
!gsutil cp /tmp/data_dashboard.tsv $WORKSPACE_BUCKET
!gsutil ls $WORKSPACE_BUCKET
###Output
gs://fc-secure-d8ae6fb6-76be-43a4-87a5-2ab255fc8d7d/data_dashboard.json
gs://fc-secure-d8ae6fb6-76be-43a4-87a5-2ab255fc8d7d/data_dashboard.tsv
gs://fc-secure-d8ae6fb6-76be-43a4-87a5-2ab255fc8d7d/notebooks/
|
Understanding_Python_for_Data_Analysis_Part2.ipynb | ###Markdown
**Introduction**In the first notebook/class, we looked at these;* Python **data types** (str, list, tuples, numeric, boolean etc)* Python **data stuctures** (sets, list, tuples)* Methods of **data extraction** into python (Git, Web, Google drive, Kaggle etc)* Explored **Pandas librar**y in Python* Introduced **Exploratory data analytics** Recommended communities to join to learn more on Python.1. Learning on the Go2. Python Nigeria - [Slack](https://join.slack.com/t/pythonnigeria/shared_invite/zt-922f1iqc-9biL9GZLOr8vdDKjY~94MQ)3. Nicholas Renotte - Youtube, etc4. Women in AI (WAI) - [Slack](https://join.slack.com/t/waicommunity/shared_invite/zt-ntn7ebna-FbvGt9B38htJizKFIDQUCw) etc---In this notebook, we will address the following;* Data Prep & Python Syntax* Data Cleaning* Numpy Library in Python* A mini-project combining Pandas and Numpy* Anaconda Jupyter notebook environment My Data Analysis Processes:1. Data Preparation2. Get Data, Pre- Process Data (Data cleaning)3. Data Manipulation4. Visual Exporation- EDA5. Generate Predictive or Descriptive Models (where needed)5. Submit resluts and findings (analysis)6. Document
###Code
###Output
_____no_output_____
###Markdown
Python Foundations **Python syntax**
###Code
print('Hello World')
###Output
Hello World
###Markdown
**Create a python file and run it***Notebooks have extensions of .ipynb*
###Code
# python examplefile.py or # ! python examplefile.py (linux env)
###Output
_____no_output_____
###Markdown
**Python Indentation**Indentation refers to the spaces at the beginning of a code line.Where in *other programming languages the indentation in code is for readability only*, **the indentation in Python is very important**.
###Code
#example of indentations
if 10 > 5:
print("Ten is greater than five")
# Try this and see
if 10 > 5:
print("Ten is greater than five")
# it gives IndentationError:
###Output
_____no_output_____
###Markdown
**The number of spaces is up to you as a programmer, but it has to be at least one.**
###Code
if 10 > 5:
print("Ten is greater than five")
if 10 > 4:
print("Ten is greater than four")
###Output
Ten is greater than five
Ten is greater than four
###Markdown
**You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:**
###Code
if 10 > 3:
print("I am going home")
print("I am going home")
#IndentationError: unexpected indent
###Output
_____no_output_____
###Markdown
**Multi Line Comments**Majorly comments are used for: Comments can be used to explain Python code.Comments can be used to make the code more readable.Comments can be used to prevent execution when testing code.---**So what are multi line comments?** aka triple quotesPython ignores string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:
###Code
"""
This is a comment
written in python
i like this programming
you can add more comments
"""
print("Hello, world")
###Output
Hello, world
###Markdown
**Variables**---**Casting**If you want to specify the data type of a variable, this can be done with casting.
###Code
#example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(type(x))
print(type(y))
print(type(z))
###Output
<class 'str'>
<class 'int'>
<class 'float'>
###Markdown
**Single or Double Quotes?**String variables can be declared either by using single or double quotes:
###Code
x = "Ada"
# is the same as
x = 'Ada'
###Output
_____no_output_____
###Markdown
**Case-Sensitive**Variable names are case-sensitive. **Rules for variable names:**A variable name must start with a letter or the underscore characterA variable name cannot start with a numberA variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )Variable names are case-sensitive (age, Age and AGE are three different variables)
###Code
a = 10
A = "Aunty"
#A will not overwrite a
print(a)
print(A)
###Output
10
Aunty
###Markdown
Many Values to Multiple Variables
###Code
x, y, z = "Ade", "John", "Gory"
print(x)
print(y)
print(z)
###Output
Ade
John
Gory
###Markdown
One Value to Multiple Variables
###Code
x = y =z = "Ade"
print(x)
print(y)
print(z)
###Output
Ade
Ade
Ade
###Markdown
Unpack a CollectionIf you have a collection of values in a *list, tuple* etc. Python allows you to extract the values into variables. This is called unpacking.
###Code
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
###Output
apple
banana
cherry
###Markdown
Output VariablesTo combine both text and a variable, Python uses the + character:
###Code
x = "good boy"
print("Tolu is a " + x)
###Output
Tolu is a good boy
###Markdown
Global VariablesVariables that are created outside of a function.
###Code
# Create a variable outside of a function, and use it inside the function
x= 'awesome'
def mysamplefun():
print("Python is " + x)
mysamplefun()
###Output
Python is awesome
###Markdown
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
###Code
# Create a variable inside a function, with the same name as the global variable
x = 'awesome'
def mysamplefun():
x = 'beautiful'
print('Python is always ' + x)
mysamplefun()
print ('Python is always ' + x)
###Output
Python is always beautiful
Python is always awesome
###Markdown
**The global Keyword**Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.To create a global variable inside a function, you can use the global keyword
###Code
# If you use the global keyword, the variable belongs to the global scope:
def mysamplefun():
global x
x = 'beautiful'
mysamplefun()
print('Python is ' + x)
###Output
Python is beautiful
###Markdown
To be continued in next class Numpy in Python (Numerical Python)NumPy is a Python library used for working with arrays.An array is a collection of items storedArray can be handled in Python by a module named array"Modules are simply files with the “. py” extension containing Python code that can be imported inside another Python Program. In simple terms, we can consider a module to be the same as a code library or a file that contains a set of functions that you want to include in your application."
###Code
#!pip install numpy #already installed most times
#example
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
#alias: In Python alias are an alternate name for referring to the same thing.
import numpy as np
print(np.__version__) #to check version of numpy
###Output
_____no_output_____
###Markdown
Creating Arrays NumPy is used to work with arrays. The array object in NumPy is called ndarray
###Code
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
###Output
[1 2 3 4 5]
<class 'numpy.ndarray'>
###Markdown
Use a tuple to create a NumPy array:
###Code
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
###Output
[1 2 3 4 5]
###Markdown
0-D Arrays or Scalars
###Code
#Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)
###Output
42
###Markdown
1-D Arrays
###Code
#Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
###Output
[1 2 3 4 5]
###Markdown
2-D ArraysAn array that has 1-D arrays as its elements is called a 2-D array.These are often used to represent matrix or 2nd order tensors.
###Code
#Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
#Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
###Output
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
###Markdown
Check Number of Dimensions
###Code
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
###Output
0
1
2
3
###Markdown
Higher Dimensional Arrays
###Code
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
###Output
[[[[[1 2 3 4]]]]]
number of dimensions : 5
###Markdown
Numpy Array Indexing Access Array ElementsThe indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
###Code
import numpy as np
arr = np.array([1, 2, 3, 4])
#print(arr[0])
print(arr[1])
print(arr[2] + arr[3])
###Output
7
###Markdown
NumPy Array Slicing
###Code
#Slice elements from index 1 to index 5 from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
#Slice elements from index 4 to the end of the array:
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
#Slice elements from the beginning to index 4 (not included):
arr = np.array([1, 2, 3, 4, 5,6,7])
print(arr[:4])
###Output
[1 2 3 4]
###Markdown
Negative Slicing
###Code
#Slice from the index 3 from the end to index 1 from the end:
arr = np.array([1, 2, 3, 4, 5,6,7])
print(arr[-3:-1])
###Output
[5 6]
###Markdown
Data Types in Python NumPy has some extra data types, and refer to data types with one character, like i for integers, u for unsigned integers etc.Below is a list of all data types in NumPy and the characters used to represent them.i - integerb - booleanu - unsigned integerf - floatc - complex floatm - timedeltaM - datetimeO - objectS - stringU - unicode stringV - fixed chunk of memory for other type ( void ) Checking Data Type
###Code
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
import numpy as np
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype)
#dytpe is a property
###Output
<U6
###Markdown
Creating Arrays With a Defined Data Type
###Code
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
###Output
[b'1' b'2' b'3' b'4']
|S1
###Markdown
For i, u, f, S and U we can define size as wellCreate an array with data type 4 bytes integer:
###Code
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)
###Output
[1 2 3 4]
int32
###Markdown
Converting Data Type on Existing Arrays
###Code
# Change data type from float to integer by using 'i' as parameter value:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
# Change data type from float to integer by using int as parameter value:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
# Change data type from integer to boolean:
import numpy as np
arr = np.array([1, 0, 3])
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)
###Output
[ True False True]
bool
###Markdown
NumPy Array Copy vs ViewThe main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array.The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy.The view does not own the data and any changes made to the view will affect the original array, and any changes made to the original array will affect the view. COPY:
###Code
# Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42 #it wont affect the original array
print(arr)
print(x)
###Output
[42 2 3 4 5]
[1 2 3 4 5]
###Markdown
VIEW:
###Code
# Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4,5])
x=arr.view()
arr[0]=43
print(arr)
print(x)
###Output
[43 2 3 4 5]
[43 2 3 4 5]
###Markdown
Make Changes in the VIEW:
###Code
# Make a view, change the view, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31
print(arr)
print(x)
###Output
[31 2 3 4 5]
[31 2 3 4 5]
###Markdown
Check if Array Owns it's Data copies owns the data, and views does not own the data, but how can we check this?Every NumPy array has the attribute base that returns None if the array owns the data.
###Code
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
y = arr.view()
print(x.base)
print(y.base)
###Output
None
[1 2 3 4 5]
###Markdown
NumPy Array ShapeShape of an ArrayThe shape of an array is the number of elements in each dimension. Get the Shape of an Array
###Code
# Print the shape of a 2-D array:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
#The example above returns (2, 4), which means that the array has 2 dimensions,
# where the first dimension has 2 elements and the second has 4.
# Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4 and verify that last dimension has value 4:
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', arr.shape)
###Output
_____no_output_____
###Markdown
**Data Cleaning Example**Data cleaning means fixing bad data in your data set.Bad data could be:* Empty cells* Data in wrong format* Wrong data* Duplicates
###Code
import pandas as pd
import numpy as np
!wget https://www.w3schools.com/python/pandas/dirtydata.csv.txt #for example
df_exp = pd.read_csv('dirtydata.csv.txt')
df_exp
df_exp.shape
df_exp.info()
###Output
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 32 entries, 0 to 31
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Duration 32 non-null int64
1 Date 31 non-null object
2 Pulse 32 non-null int64
3 Maxpulse 32 non-null int64
4 Calories 30 non-null float64
dtypes: float64(1), int64(3), object(1)
memory usage: 1.4+ KB
###Markdown
Dealing with **Empty Cells****Solution:** Remove Rows or replace with zeros or mean etc
###Code
df_exp.isna().sum() #sum all missing values/cells in our dataset
###Output
_____no_output_____
###Markdown
**1. Return a new Data Frame with no empty cells:**One way to deal with empty cells is to **remove rows** that contain empty cells.By default, the *dropna()* method returns a new DataFrame, and will not change the original
###Code
df_expcopy = df_exp.copy(deep=True)
df_expcopy
#deep=True returns a dataframe
###Output
_____no_output_____
###Markdown
I dont want to affect the df_exp
###Code
df_exp2 = df_expcopy.dropna() #dropna removes rows that contain empty cells
df_exp2
#instead of using df_exp.dropna()
df_exp2.isna().sum()
df_exp2.shape
###Output
_____no_output_____
###Markdown
**If you want to change the original DataFrame, use the inplace = True argument:**
###Code
df_exp2 = df_expcopy.dropna(inplace = True)
###Output
_____no_output_____
###Markdown
**2. Replace Empty Values**
###Code
df_exp.shape
df_exp3= df_exp.fillna(0) #means replace any empty cell with 0
df_exp3
df_exp3.isna().sum()
###Output
_____no_output_____
###Markdown
**3. Replace Empty Cell for only specified Column**
###Code
df_exp
#df_exp["Maxpulse"].fillna(1, inplace = True)
###Output
_____no_output_____
###Markdown
**3. Replacing with Median, Mean & Mode**Mode`x = df["Calories"].mode()[0]``df["Calories"].fillna(x, inplace = True)`Mean`x = df["Calories"].mean()``df["Calories"].fillna(x, inplace = True)`Median`x = df["Calories"].median()``df["Calories"].fillna(x, inplace = True)`
###Code
###Output
_____no_output_____
###Markdown
**Class Project**dataset location- [online store UCI](https://archive.ics.uci.edu/ml/datasets/Online+Shoppers+Purchasing+Intention+Dataset)dataset [direct link](https://archive.ics.uci.edu/ml/machine-learning-databases/00468/online_shoppers_intention.csv)**Case Study:** Get Data (Data Prep)
###Code
!wget https://archive.ics.uci.edu/ml/machine-learning-databases/00468/online_shoppers_intention.csv
###Output
--2022-01-28 10:42:30-- https://archive.ics.uci.edu/ml/machine-learning-databases/00468/online_shoppers_intention.csv
Resolving archive.ics.uci.edu (archive.ics.uci.edu)... 128.195.10.252
Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1072063 (1.0M) [application/x-httpd-php]
Saving to: ‘online_shoppers_intention.csv’
online_shoppers_int 100%[===================>] 1.02M 2.27MB/s in 0.4s
2022-01-28 10:42:31 (2.27 MB/s) - ‘online_shoppers_intention.csv’ saved [1072063/1072063]
###Markdown
**Import Python Libraries & dependencies**
###Code
import pandas as pd
import numpy as np # maths
import pandas as pd # data processing,
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
#from wordcloud import WordCloud, STOPWORDS
# Inline backend
%matplotlib inline
mpl.style.use(['ggplot'])
import warnings
warnings.filterwarnings('ignore')
###Output
_____no_output_____
###Markdown
**Extract the Data from source - Dataframe**
###Code
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/00468/online_shoppers_intention.csv')
df
###Output
_____no_output_____
###Markdown
or
###Code
dftry = pd.read_csv('online_shoppers_intention.csv')
dftry
###Output
_____no_output_____
###Markdown
**Learn more about our dataset**
###Code
df.info()
df.shape
df.describe().T
df.plot(kind = 'area') #a simple description but not detailed
df.isna().sum() #sum all missing values/cells in our dataset
###Output
_____no_output_____
###Markdown
Plots
###Code
df.Administrative_Duration.value_counts()
df.columns
sns.countplot(df['Region'])
###Output
_____no_output_____
###Markdown
**Making a Copy of Your Dataframe**
###Code
# Top 10 Regions that contributed the most to Sales/Revenue/turnover
#expnanation purposes
df10 = df.copy(deep=True)
df.sort_values(['Region'], ascending=False, axis=0, inplace=True)
# get the top 10 entries
dften = df10.head(10)
# transpose the dataframe
#dften = dften[years].transpose()
#dften.head()
df10 =df.copy(deep=True)
df10.head(10)
df10.sort_values(['Region'], ascending=False, axis=0, inplace=True)
dften =df10.head(10)
dften
dfxx = df10.transpose()
dfxx #not so useful as such because there are no labels now
# Compare the trends of top 10 locations/stores that contributed the most to business.
dften.plot(kind='line', figsize=(14, 8))
plt.title('Quantity')
plt.xlabel('Region')
plt.show()
#https://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html
sns.displot(data=df, x="Region", col="Month", kde=True)
###Output
_____no_output_____
###Markdown
Printing to CSV
###Code
###Output
_____no_output_____
###Markdown
Case Study:Attendance - Storex[Data Link](https://www.kaggle.com/c/store-sales-time-series-forecasting/data)
###Code
###Output
_____no_output_____ |
Bankruptcy_prediction_ (1).ipynb | ###Markdown
**Detecting whether or not a bank goes bankrupt after 1 year** **Importing necessary libraries**
###Code
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
###Output
_____no_output_____
###Markdown
**Importing bankruptcy dataset**
###Code
from scipy.io import arff
from io import BytesIO
data = arff.loadarff('5year.arff')
df = pd.DataFrame(data[0])
X = df.iloc[:, :-1].values
Y = df.iloc[:, -1].values
y=[]
for i in range(len(Y)):
if(Y[i]==b'0'):
y.append(0)
else:
y.append(1)
###Output
_____no_output_____
###Markdown
**Processing missing values**
###Code
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(X)
X = imputer.transform(X)
###Output
_____no_output_____
###Markdown
**Splitting dataset into training and test sets**
###Code
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
###Output
_____no_output_____
###Markdown
**Logistic regression** **Training the logistic regression model**
###Code
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, Y_train)
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_logistic.py:818: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG,
###Markdown
**Predicting the target labels of testset**
###Code
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score,recall_score, f1_score
from sklearn.metrics import plot_confusion_matrix
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
plot_confusion_matrix(classifier, X_test, Y_test)
plt.show()
print("accuracy = %f" % accuracy_score(Y_test, Y_pred))
print("precision = %f" % precision_score(Y_test, Y_pred))
print("recall score = %f" % recall_score(Y_test, Y_pred))
print("f1 score = %f" % f1_score(Y_test, Y_pred))
#https://vitalflux.com/accuracy-precision-recall-f1-score-python-example/
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
warnings.warn(msg, category=FutureWarning)
###Markdown
**Eliminating attributes based on correlation**
###Code
print(len(X[0]))
l=[]
for i in range(0,len(X[0])):
xmat=X[:,i]
ymat=np.array(y)
r = np.corrcoef(xmat, ymat)
if(r[0,1]>0):
l.append(i)
X=np.delete(X, l, axis=1)
print(len(X[0]))
###Output
64
42
###Markdown
**Training the logistic regression model after reducing X**
###Code
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, Y_train)
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score,recall_score, f1_score
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
plot_confusion_matrix(classifier, X_test, Y_test)
plt.show()
print("accuracy = %f" % accuracy_score(Y_test, Y_pred))
print("precision = %f" % precision_score(Y_test, Y_pred))
print("recall score = %f" % recall_score(Y_test, Y_pred))
print("f1 score = %f" % f1_score(Y_test, Y_pred))
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
warnings.warn(msg, category=FutureWarning)
###Markdown
**Feacture extraction**
###Code
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
lda = LDA(n_components = 1)
print(len(X_train[0]))
X_train = lda.fit_transform(X_train, Y_train)
X_test = lda.transform(X_test)
print(len(X_train[0]))
###Output
64
1
###Markdown
**Training the logistic regression model after feature extraction**
###Code
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, Y_train)
###Output
_____no_output_____
###Markdown
Predicting the target lables of testset
###Code
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score,recall_score, f1_score
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
plot_confusion_matrix(classifier, X_test, Y_test)
plt.show()
print("accuracy = %f" % accuracy_score(Y_test, Y_pred))
print("precision = %f" % precision_score(Y_test, Y_pred))
print("recall score = %f" % recall_score(Y_test, Y_pred))
print("f1 score = %f" % f1_score(Y_test, Y_pred))
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
warnings.warn(msg, category=FutureWarning)
###Markdown
**Linear Support Vector Machine**
###Code
from sklearn.svm import SVC
classifier = SVC(kernel = 'linear', random_state = 0)
classifier.fit(X_train, Y_train)
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score,recall_score, f1_score
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
plot_confusion_matrix(classifier, X_test, Y_test)
plt.show()
print("accuracy = %f" % accuracy_score(Y_test, Y_pred))
print("precision = %f" % precision_score(Y_test, Y_pred))
print("recall score = %f" % recall_score(Y_test, Y_pred))
print("f1 score = %f" % f1_score(Y_test, Y_pred))
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
warnings.warn(msg, category=FutureWarning)
###Markdown
**Polynomial Support Vector Machine**
###Code
from sklearn.svm import SVC
classifier = SVC(kernel = 'poly',degree=3, random_state = 0)
classifier.fit(X_train, Y_train)
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score,recall_score, f1_score
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
plot_confusion_matrix(classifier, X_test, Y_test)
plt.show()
print("accuracy = %f" % accuracy_score(Y_test, Y_pred))
print("precision = %f" % precision_score(Y_test, Y_pred))
print("recall score = %f" % recall_score(Y_test, Y_pred))
print("f1 score = %f" % f1_score(Y_test, Y_pred))
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
warnings.warn(msg, category=FutureWarning)
###Markdown
**Radial basis function SVM**
###Code
from sklearn.svm import SVC
classifier = SVC(kernel = 'rbf', random_state = 0)
classifier.fit(X_train, Y_train)
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score,recall_score, f1_score
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
plot_confusion_matrix(classifier, X_test, Y_test)
plt.show()
print("accuracy = %f" % accuracy_score(Y_test, Y_pred))
print("precision = %f" % precision_score(Y_test, Y_pred))
print("recall score = %f" % recall_score(Y_test, Y_pred))
print("f1 score = %f" % f1_score(Y_test, Y_pred))
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
warnings.warn(msg, category=FutureWarning)
###Markdown
**K-NN model**
###Code
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)
classifier.fit(X_train, Y_train)
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score,recall_score, f1_score
Y_pred = classifier.predict(X_test)
cm = confusion_matrix(Y_test, Y_pred)
plot_confusion_matrix(classifier, X_test, Y_test)
plt.show()
print("accuracy = %f" % accuracy_score(Y_test, Y_pred))
print("precision = %f" % precision_score(Y_test, Y_pred))
print("recall score = %f" % recall_score(Y_test, Y_pred))
print("f1 score = %f" % f1_score(Y_test, Y_pred))
###Output
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.
warnings.warn(msg, category=FutureWarning)
|
data_structure/map_reduce.ipynb | ###Markdown
Map
###Code
def calculateSquare(n):
return n * n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
numbers = (1, 2, 3, 4)
result = map(lambda x: x * x, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
num1 = [4, 5, 6]
num2 = [5, 6, 7]
result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))
# iterate over multiple function (stupid)
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
###Output
[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]
###Markdown
Reduce
###Code
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product)
# using reduce to compute maximum element from list
lis = [1, 3, 5, 6, 2]
print("The maximum element of the list is : ", end="")
print(reduce(lambda a,b : a if a > b else b,lis))
###Output
The maximum element of the list is : 6
|
DL - Deep Learning - Building Deep Learning Applications/03_04_Creating_Training_Neural_Network_Model.ipynb | ###Markdown
1) Creating a Neural Network in Keras 1.1) Preprocessing Training Data
###Code
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# Load training data and test data
training_data_df = pd.read_csv('data/sales_data_training.csv')
testing_data_df = pd.read_csv('data/sales_data_test.csv')
# Scale the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_training_data = scaler.fit_transform(training_data_df)
scaled_testing_data = scaler.transform(testing_data_df)
# Print out the adjustment that the scaler applied to the total_earnings column of data
print("Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}".format(scaler.scale_[8], scaler.min_[8]))
training_data_df.columns.values
# Create new pandas DataFrame objects from the scaled data
scaled_training_df = pd.DataFrame(data=scaled_training_data, columns=training_data_df.columns.values)
scaled_testing_df = pd.DataFrame(data=scaled_testing_data, columns=testing_data_df.columns.values)
# Save scaled data dataframes to new CSV files
scaled_training_df.to_csv('data/sales_data_training_scaled.csv', index=False)
scaled_testing_df.to_csv('data/sales_data_test_scaled.csv', index=False)
###Output
_____no_output_____
###Markdown
------- 1.2) Define Keras Model using Sequential API- we want to predict `Total Earnings` for the games
###Code
import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
training_data_df = pd.read_csv('data/sales_data_training_scaled.csv')
training_data_df.head()
X = training_data_df.drop('total_earnings', axis=1).values
y = training_data_df[['total_earnings']].values
X.shape, y.shape
y[:5]
# Define the model
model = Sequential()
model.add(Dense(50, input_dim=9, activation='relu')) # as our number of features is 9
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='linear')) # linear is default too. we are predicting single value
model.compile(
loss='mse',
optimizer='adam'
)
model.summary()
###Output
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_4 (Dense) (None, 50) 500
_________________________________________________________________
dense_5 (Dense) (None, 100) 5100
_________________________________________________________________
dense_6 (Dense) (None, 50) 5050
_________________________________________________________________
dense_7 (Dense) (None, 1) 51
=================================================================
Total params: 10,701
Trainable params: 10,701
Non-trainable params: 0
_________________________________________________________________
###Markdown
------- 2) Training Models 2.1) Training and Evaluation of Model
###Code
# Train the model
model.fit(
X,
y,
epochs=50,
shuffle = True, #shuffle is true by default though
verbose=2
)
###Output
Epoch 1/50
32/32 - 2s - loss: 0.0207
Epoch 2/50
32/32 - 0s - loss: 0.0028
Epoch 3/50
32/32 - 0s - loss: 0.0011
Epoch 4/50
32/32 - 0s - loss: 4.5699e-04
Epoch 5/50
32/32 - 0s - loss: 3.1295e-04
Epoch 6/50
32/32 - 0s - loss: 1.9573e-04
Epoch 7/50
32/32 - 0s - loss: 1.4639e-04
Epoch 8/50
32/32 - 0s - loss: 1.0866e-04
Epoch 9/50
32/32 - 0s - loss: 9.4893e-05
Epoch 10/50
32/32 - 0s - loss: 9.5402e-05
Epoch 11/50
32/32 - 0s - loss: 7.9593e-05
Epoch 12/50
32/32 - 0s - loss: 6.1124e-05
Epoch 13/50
32/32 - 0s - loss: 5.8854e-05
Epoch 14/50
32/32 - 0s - loss: 4.7164e-05
Epoch 15/50
32/32 - 0s - loss: 5.2579e-05
Epoch 16/50
32/32 - 0s - loss: 4.5479e-05
Epoch 17/50
32/32 - 0s - loss: 3.3523e-05
Epoch 18/50
32/32 - 0s - loss: 3.8041e-05
Epoch 19/50
32/32 - 0s - loss: 3.2778e-05
Epoch 20/50
32/32 - 0s - loss: 2.9138e-05
Epoch 21/50
32/32 - 0s - loss: 3.6182e-05
Epoch 22/50
32/32 - 0s - loss: 2.6849e-05
Epoch 23/50
32/32 - 0s - loss: 3.3815e-05
Epoch 24/50
32/32 - 0s - loss: 3.0148e-05
Epoch 25/50
32/32 - 0s - loss: 2.4762e-05
Epoch 26/50
32/32 - 0s - loss: 3.0279e-05
Epoch 27/50
32/32 - 0s - loss: 3.8937e-05
Epoch 28/50
32/32 - 0s - loss: 4.4956e-05
Epoch 29/50
32/32 - 0s - loss: 4.3861e-05
Epoch 30/50
32/32 - 0s - loss: 3.4013e-05
Epoch 31/50
32/32 - 0s - loss: 2.1935e-05
Epoch 32/50
32/32 - 0s - loss: 2.9877e-05
Epoch 33/50
32/32 - 0s - loss: 2.3932e-05
Epoch 34/50
32/32 - 0s - loss: 2.5597e-05
Epoch 35/50
32/32 - 0s - loss: 2.2657e-05
Epoch 36/50
32/32 - 0s - loss: 2.0294e-05
Epoch 37/50
32/32 - 0s - loss: 2.0241e-05
Epoch 38/50
32/32 - 0s - loss: 2.0779e-05
Epoch 39/50
32/32 - 0s - loss: 2.3561e-05
Epoch 40/50
32/32 - 0s - loss: 3.9225e-05
Epoch 41/50
32/32 - 0s - loss: 4.6857e-05
Epoch 42/50
32/32 - 0s - loss: 2.9387e-05
Epoch 43/50
32/32 - 0s - loss: 2.0429e-05
Epoch 44/50
32/32 - 0s - loss: 2.1320e-05
Epoch 45/50
32/32 - 0s - loss: 2.8111e-05
Epoch 46/50
32/32 - 0s - loss: 3.8358e-05
Epoch 47/50
32/32 - 0s - loss: 3.6742e-05
Epoch 48/50
32/32 - 0s - loss: 3.0768e-05
Epoch 49/50
32/32 - 0s - loss: 4.1079e-05
Epoch 50/50
32/32 - 0s - loss: 2.4699e-05
###Markdown
Testing and Evaluation
###Code
# load separte test data
test_data_df = pd.read_csv('data/sales_data_test_scaled.csv')
X_test = test_data_df.drop('total_earnings', axis=1).values
y_test = test_data_df[['total_earnings']].values
test_error_rate = model.evaluate(X_test, y_test)
print('The mean squared error MSE for the test data set is {}'.format(test_error_rate))
###Output
The mean squared error MSE for the test data set is 8.224092744057998e-05
###Markdown
2.2) Making Predictions- future of sale of new video game
###Code
# Load the data that we want to use to predict
# the values are already pre-scaled, so we will skip scaling
new_product_X = pd.read_csv('data/proposed_new_product.csv').values
new_product_X
# Make predictions with the neural network
prediction = model.predict(new_product_X)
prediction
# Grab just the first element of the first prediction (since that's the only have one)
prediction = prediction[0][0]
# Re-scale the data from the 0-to-1 range back to dollars
# These constants are from when the data was originally scaled down to the 0-to-1 range
prediction = prediction + 0.1159
prediction = prediction / 0.0000036968
print("Earnings Prediction for Proposed Product - ${}".format(prediction))
###Output
Earnings Prediction for Proposed Product - $262883.3664054351
###Markdown
2.3) Saving and Loading Models Save Model
###Code
model.save('models/trained_model.h5')
print('model saved to disk!')
###Output
model saved to disk!
###Markdown
Load Model and make prediction
###Code
from tensorflow.keras.models import load_model
loaded_model = load_model('models/trained_model.h5')
prediction = loaded_model.predict(new_product_X)
prediction = prediction[0][0]
prediction = prediction + 0.1159
prediction = prediction / 0.0000036968
print("Earnings Prediction for Proposed Product - ${}".format(prediction))
###Output
Earnings Prediction for Proposed Product - $262883.3664054351
|
DesafioRS_Jupyter.ipynb | ###Markdown
Função entre_AmigosA função entre_Amigos, verifica se duas pessoas são amigas entre si, amizade recíproca. A função é importante para saber se o amigo é considerado amigo de verdade do outro, assim a rede social percebe a afinidade nos laços de amizade e registra nos dados, os com mais precisão relacionamentos. Características da função* Parâmetro: Recebe nome de duas pessoas;* Retorna: O nome das pessoas e mensagens de confirmação de amizade.
###Code
def entre_Amigos(nomePessoaA, nomePessoaB):
pessoas= ["Alice", "Bob", "Carol", "Danielle"]
tam = len(pessoas)
amizades = [[0,0,0,1],[1,0,1,1],[0,0,0,1],[1,1,0,0]]
tamMat = len(amizades)
for i in range(tam):
for j in range(tam):
if pessoas[i] in nomePessoaA and pessoas[j] in nomePessoaB:
for linha in range(tamMat):
for coluna in range(len(amizades)):
if amizades[i][coluna] == 1 and amizades [j][i] == 1:
return print("São amigos entre si: " + nomePessoaA + " e " + nomePessoaB)
else:
return print("Não são amigos entre si.")
else:
print("Nome Inválido.")
test = entre_Amigos( nomePessoaA= "Alice", nomePessoaB= "Danielle")
###Output
São amigos entre si: Alice e Danielle
|
mrett.ipynb | ###Markdown
MRETT ResultsComplete spreadsheet: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=1384530880 MRETT21: 1gE2gzncRuiwzY4xgKEbVDjSBUde8LGc7u9pIMQ0C6bQ https://rgtdb.com/events/94944 Importing Google Spreadsheet into Pandashttps://stackoverflow.com/questions/19611729/getting-google-spreadsheet-csv-into-a-pandas-dataframe```pythonpd.read_csv('https://docs.google.com/spreadsheets/d/' + '0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc' + '/export?gid=0&format=csv', Set first column as rownames in data frame index_col=0, Parse column values to datetime parse_dates=['Quradate'] )``` APIshttps://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/values/MRETT22https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/editgid=171816323&range=C17GC: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=138453088021: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=022: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=60170817823: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=17181632324: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=176980185625: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=195356958126: https://docs.google.com/spreadsheets/d/11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU/edit?fbclid=IwAR2KA8_pks7JY4Q_P7XLrNSawnmysBJo2FnAFvjUe5r7XiAlAi134Z-PXNwgid=1178762166
###Code
import pandas as pd
df_MRETT_GC = pd.read_csv('https://docs.google.com/spreadsheets/d/' +
'11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU' +
'/export?gid=' + '1384530880' + '&format=csv',
# Set first column as rownames in data frame
index_col=0,
# Parse column values to datetime
#parse_dates=['Quradate']
)
#df_MRETT22 = pd.read_csv('https://docs.google.com/spreadsheets/d/' + '1gIz_Gs6uxUrMUJKk7SrflaAiKeOKScQfvNqnX4bADV0' + '/export?gid=' + '1667031214' + '&format=csv', index_col=0)
df_MRETT_GC
###Output
_____no_output_____
###Markdown
Wait for Spreadsheet to InitializeSince the spreadsheet reads data from other sheets, it may take several seconds for it to properly fetch and calculate all values.
###Code
import time
for i in range(1):
time.sleep(5)
pd.read_csv('https://docs.google.com/spreadsheets/d/' +
'11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU' +
'/export?' + '' + '&format=csv',
index_col=1,
)
###Output
_____no_output_____
###Markdown
Get all Sheet Tabs, Including GC
###Code
mrett_gids = {
'GC' : '1384530880',
'21' : '0',
'22' : '601708178',
'23' : '171816323',
'24' : '1769801856',
'25' : '1953569581',
'26' : '1178762166'
}
mrett_finished = {
'GC' : False,
'21' : True,
'22' : True,
'23' : True,
'24' : True,
'25' : True,
'26' : False
}
df_mretts = {}
for mrett in mrett_gids.keys():
print(mrett, mrett_gids[mrett])
gid = mrett_gids[mrett]
if mrett_finished[mrett] != True:
print('Updating from spreadsheet')
df_mretts[mrett] = pd.read_csv('https://docs.google.com/spreadsheets/d/' + '11uk0WpQzjVBOWs99cev9buajG1PalFdC5mtdynhqejU' + '/export?gid=' + gid + '&format=csv', index_col=1, na_values=['', ' '])
else:
print('Using stored values')
filename = mrett + '.pickle'
df_mretts[mrett] = pd.read_pickle(filename)
df_mretts['GC']
###Output
GC 1384530880
Updating from spreadsheet
21 0
Using stored values
22 601708178
Using stored values
23 171816323
Using stored values
24 1769801856
Using stored values
25 1953569581
Using stored values
26 1178762166
Updating from spreadsheet
###Markdown
Workaound for broken MRETT22 - Results saved before MRETT22 stopped working Total MRETT21 MRETT22 MRETT23 MRETT24 MRETT25 MRETT26Team eCKD 1 1 1000 200.0 200.0 200.0 200.0 200.0 NaNRasio Racing 2 920 190.0 180.0 180.0 180.0 190.0 NaNThe Pedalers 2 920 170.0 190.0 190.0 190.0 180.0 NaNPocomotion 4 850 175.0 165.0 170.0 165.0 175.0 NaNOTR Black 5 835 165.0 160.0 175.0 175.0 160.0 NaNKISS Racing Team 1 6 815 150.0 175.0 155.0 170.0 165.0 NaNMoon Riders 7 791 160.0 141.0 160.0 160.0 170.0 NaNOTR Blue 8 765 155.0 170.0 145.0 145.0 150.0 NaNOTR Green 9 748 141.0 137.0 165.0 150.0 155.0 NaNTeam Lou Racing Squad 10 732 137.0 145.0 150.0 155.0 145.0 NaNeCKD 2 11 693 145.0 133.0 137.0 137.0 141.0 NaNWesterley CC Purple 12 669 129.0 129.0 133.0 141.0 137.0 NaNWKG Renegades 13 520 125.0 125.0 141.0 129.0 NaN NaNWesterlies 14 504 NaN 121.0 129.0 125.0 129.0 NaNRGT France 1 15 335 180.0 155.0 NaN NaN NaN NaNTeam Lou Too 16 266 NaN NaN NaN 133.0 133.0 NaNLes Watts 17 150 NaN 150.0 NaN NaN NaN NaNTricky Allsorts 18 133 133.0 NaN NaN NaN NaN NaN
###Code
""" if pd.isna(df_mretts['GC']['MRETT21'].iloc[0]):
df_mretts['GC'].at['eCKD 1', 'MRETT21'] = 200
df_mretts['GC'].at['Rasio Racing', 'MRETT21'] = 190
df_mretts['GC'].at['The Pedalers', 'MRETT21'] = 170
df_mretts['GC'].at['Pocomotion', 'MRETT21'] = 175
df_mretts['GC'].at['OTR Black', 'MRETT21'] = 165
df_mretts['GC'].at['KISS Racing Team 1', 'MRETT21'] = 150
df_mretts['GC'].at['Moon Riders', 'MRETT21'] = 160
df_mretts['GC'].at['OTR Blue', 'MRETT21'] = 155
df_mretts['GC'].at['OTR Green', 'MRETT21'] = 141
df_mretts['GC'].at['Team Lou Racing Squad', 'MRETT21'] = 137
df_mretts['GC'].at['eCKD 2', 'MRETT21'] = 145
df_mretts['GC'].at['Westerley CC Purple', 'MRETT21'] = 129
df_mretts['GC'].at['WKG Renegades', 'MRETT21'] = 125
df_mretts['GC'].at['Westerlies', 'MRETT21'] = 0
df_mretts['GC'].at['RGT France 1', 'MRETT21'] = 189
df_mretts['GC'].at['Team Lou Too', 'MRETT21'] = 0
df_mretts['GC'].at['Les Watts', 'MRETT21'] = 0
df_mretts['GC'].at['Tricky Allsorts', 'MRETT21'] = 133
df_mretts['GC']['Total'] = df_mretts['GC']['Total'] + df_mretts['GC']['MRETT21']
df_mretts['GC'] """
###Output
_____no_output_____
###Markdown
Create Graphs
###Code
import pandas_bokeh
import bokeh
from bokeh.themes import built_in_themes
from bokeh.io import curdoc
pandas_bokeh.output_notebook()
df_mretts['GC'][::-1].loc[:,'MRETT21':'MRETT26'].fillna(0).plot_bokeh.barh(
ylabel="Team",
xlabel="Points",
title="MRETT Series 2 GC",
stacked=True,
alpha=0.6,
figsize=(1600, 600),
legend = "bottom_right",
sizing_mode="scale_width"
)
###Output
_____no_output_____
###Markdown
Convert Time column to timedelta
###Code
for mrett in mrett_gids.keys():
if mrett != 'GC':
df_mretts[mrett]['timedelta'] = pd.to_timedelta(df_mretts[mrett].Time)
df_mretts[mrett]['Time in Seconds'] = df_mretts[mrett]['timedelta'].dt.total_seconds()
df_mretts[mrett]['Time in Minutes'] = df_mretts[mrett]['Time in Seconds']/60
df_mretts[mrett]['Time in Minutes Truncated'] = divmod(df_mretts[mrett]['Time in Seconds'], 60)[0]
df_mretts[mrett]['Time Remainder in Seconds'] = divmod(df_mretts[mrett]['Time in Seconds'], 60)[1]
df_mretts[mrett]['Team Name'] = df_mretts[mrett].index
df_mretts[mrett]
df_mretts['21']
df_mretts['21'][::-1].plot_bokeh.barh(
title = 'MRETT' + '21',
xlabel = 'Time (Minutes)',
y='Time in Minutes',
alpha=0.6,
figsize=(1600, 300),
legend = "top_right",
#hovertool_columns='Time',,
hovertool_string="""<h2> #@{#}
@{Team Name} </h2>
<h3> Time: @{Time} </h3>""",
sizing_mode="scale_width")
for mrett in mrett_gids.keys():
if mrett != 'GC':
df_mretts[mrett][::-1].plot_bokeh.barh(
title = 'MRETT' + mrett,
xlabel = 'Time (Minutes)',
y='Time in Minutes',
alpha=0.6,
figsize=(1600, 300),
legend = "top_right",
hovertool_string="""<h2> #@{#}
@{Team Name} </h2>
<h3> Time: @{Time} </h3>""",
sizing_mode="scale_width")
###Output
_____no_output_____
###Markdown
Save Data in Pickle FormatUse this to skip reloading/rereading
###Code
for mrett in mrett_gids.keys():
if mrett_finished[mrett] != True:
file_name = mrett + '.pickle'
df_mretts[mrett].to_pickle(file_name)
###Output
_____no_output_____ |
Course4_CNN/week2/.ipynb_checkpoints/Residual_Networks_v2a-checkpoint.ipynb | ###Markdown
Residual NetworksWelcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](https://arxiv.org/pdf/1512.03385.pdf), allow you to train much deeper networks than were previously practically feasible.**In this assignment, you will:**- Implement the basic building blocks of ResNets. - Put together these building blocks to implement and train a state-of-the-art neural network for image classification. Updates If you were working on the notebook before this update...* The current notebook is version "2a".* You can find your original work saved in the notebook with the previous version name ("v2") * To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory. List of updates* For testing on an image, replaced `preprocess_input(x)` with `x=x/255.0` to normalize the input image in the same way that the model's training data was normalized.* Refers to "shallower" layers as those layers closer to the input, and "deeper" layers as those closer to the output (Using "shallower" layers instead of "lower" or "earlier").* Added/updated instructions. This assignment will be done in Keras. Before jumping into the problem, let's run the cell below to load the required packages.
###Code
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.preprocessing import image
from tensorflow.python.keras.utils import layer_utils
from tensorflow.python.keras.utils.data_utils import get_file
from tensorflow.keras.applications.imagenet_utils import preprocess_input
import pydot
from IPython.display import SVG
from tensorflow.python.keras.utils.vis_utils import model_to_dot
from tensorflow.keras.utils import plot_model
from resnets_utils import *
from tensorflow.keras.initializers import glorot_uniform
import scipy.misc
from matplotlib.pyplot import imshow
%matplotlib inline
import tensorflow.keras.backend as K
K.set_image_data_format('channels_last')
K.set_learning_phase(1)
###Output
_____no_output_____
###Markdown
1 - The problem of very deep neural networksLast week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers.* The main benefit of a very deep network is that it can represent very complex functions. It can also learn features at many different levels of abstraction, from edges (at the shallower layers, closer to the input) to very complex features (at the deeper layers, closer to the output). * However, using a deeper network doesn't always help. A huge barrier to training them is vanishing gradients: very deep networks often have a gradient signal that goes to zero quickly, thus making gradient descent prohibitively slow. * More specifically, during gradient descent, as you backprop from the final layer back to the first layer, you are multiplying by the weight matrix on each step, and thus the gradient can decrease exponentially quickly to zero (or, in rare cases, grow exponentially quickly and "explode" to take very large values). * During training, you might therefore see the magnitude (or norm) of the gradient for the shallower layers decrease to zero very rapidly as training proceeds: **Figure 1** : **Vanishing gradient** The speed of learning decreases very rapidly for the shallower layers as the network trains You are now going to solve this problem by building a Residual Network! 2 - Building a Residual NetworkIn ResNets, a "shortcut" or a "skip connection" allows the model to skip layers: **Figure 2** : A ResNet block showing a **skip-connection** The image on the left shows the "main path" through the network. The image on the right adds a shortcut to the main path. By stacking these ResNet blocks on top of each other, you can form a very deep network. We also saw in lecture that having ResNet blocks with the shortcut also makes it very easy for one of the blocks to learn an identity function. This means that you can stack on additional ResNet blocks with little risk of harming training set performance. (There is also some evidence that the ease of learning an identity function accounts for ResNets' remarkable performance even more so than skip connections helping with vanishing gradients).Two main types of blocks are used in a ResNet, depending mainly on whether the input/output dimensions are same or different. You are going to implement both of them: the "identity block" and the "convolutional block." 2.1 - The identity blockThe identity block is the standard block used in ResNets, and corresponds to the case where the input activation (say $a^{[l]}$) has the same dimension as the output activation (say $a^{[l+2]}$). To flesh out the different steps of what happens in a ResNet's identity block, here is an alternative diagram showing the individual steps: **Figure 3** : **Identity block.** Skip connection "skips over" 2 layers. The upper path is the "shortcut path." The lower path is the "main path." In this diagram, we have also made explicit the CONV2D and ReLU steps in each layer. To speed up training we have also added a BatchNorm step. Don't worry about this being complicated to implement--you'll see that BatchNorm is just one line of code in Keras! In this exercise, you'll actually implement a slightly more powerful version of this identity block, in which the skip connection "skips over" 3 hidden layers rather than 2 layers. It looks like this: **Figure 4** : **Identity block.** Skip connection "skips over" 3 layers. Here are the individual steps.First component of main path: - The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and its name should be `conv_name_base + '2a'`. Use 0 as the seed for the random initialization. - The first BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2a'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Second component of main path:- The second CONV2D has $F_2$ filters of shape $(f,f)$ and a stride of (1,1). Its padding is "same" and its name should be `conv_name_base + '2b'`. Use 0 as the seed for the random initialization. - The second BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2b'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Third component of main path:- The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and its name should be `conv_name_base + '2c'`. Use 0 as the seed for the random initialization. - The third BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2c'`. - Note that there is **no** ReLU activation function in this component. Final step: - The `X_shortcut` and the output from the 3rd layer `X` are added together.- **Hint**: The syntax will look something like `Add()([var1,var2])`- Then apply the ReLU activation function. This has no name and no hyperparameters. **Exercise**: Implement the ResNet identity block. We have implemented the first component of the main path. Please read this carefully to make sure you understand what it is doing. You should implement the rest. - To implement the Conv2D step: [Conv2D](https://keras.io/layers/convolutional/conv2d)- To implement BatchNorm: [BatchNormalization](https://faroit.github.io/keras-docs/1.2.2/layers/normalization/) (axis: Integer, the axis that should be normalized (typically the 'channels' axis))- For the activation, use: `Activation('relu')(X)`- To add the value passed forward by the shortcut: [Add](https://keras.io/layers/merge/add)
###Code
# GRADED FUNCTION: identity_block
def identity_block(X, f, filters, stage, block):
"""
Implementation of the identity block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
stage -- integer, used to name the layers, depending on their position in the network
block -- string/character, used to name the layers, depending on their position in the network
Returns:
X -- output of the identity block, tensor of shape (n_H, n_W, n_C)
"""
# defining name basis
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
# Retrieve Filters
F1, F2, F3 = filters
# Save the input value. You'll need this later to add back to the main path.
X_shortcut = X
# First component of main path
X = Conv2D(filters = F1, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X)
X = Activation('relu')(X)
### START CODE HERE ###
# Second component of main path (≈3 lines)
X = None
X = None
X = None
# Third component of main path (≈2 lines)
X = None
X = None
# Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)
X = None
X = None
### END CODE HERE ###
return X
tf.reset_default_graph()
with tf.Session() as test:
np.random.seed(1)
A_prev = tf.placeholder("float", [3, 4, 4, 6])
X = np.random.randn(3, 4, 4, 6)
A = identity_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
test.run(tf.global_variables_initializer())
out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
print("out = " + str(out[0][1][1][0]))
###Output
_____no_output_____
###Markdown
**Expected Output**: **out** [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003] 2.2 - The convolutional blockThe ResNet "convolutional block" is the second block type. You can use this type of block when the input and output dimensions don't match up. The difference with the identity block is that there is a CONV2D layer in the shortcut path: **Figure 4** : **Convolutional block** * The CONV2D layer in the shortcut path is used to resize the input $x$ to a different dimension, so that the dimensions match up in the final addition needed to add the shortcut value back to the main path. (This plays a similar role as the matrix $W_s$ discussed in lecture.) * For example, to reduce the activation dimensions's height and width by a factor of 2, you can use a 1x1 convolution with a stride of 2. * The CONV2D layer on the shortcut path does not use any non-linear activation function. Its main role is to just apply a (learned) linear function that reduces the dimension of the input, so that the dimensions match up for the later addition step. The details of the convolutional block are as follows. First component of main path:- The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (s,s). Its padding is "valid" and its name should be `conv_name_base + '2a'`. Use 0 as the `glorot_uniform` seed.- The first BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2a'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Second component of main path:- The second CONV2D has $F_2$ filters of shape (f,f) and a stride of (1,1). Its padding is "same" and it's name should be `conv_name_base + '2b'`. Use 0 as the `glorot_uniform` seed.- The second BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2b'`.- Then apply the ReLU activation function. This has no name and no hyperparameters. Third component of main path:- The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and it's name should be `conv_name_base + '2c'`. Use 0 as the `glorot_uniform` seed.- The third BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. Shortcut path:- The CONV2D has $F_3$ filters of shape (1,1) and a stride of (s,s). Its padding is "valid" and its name should be `conv_name_base + '1'`. Use 0 as the `glorot_uniform` seed.- The BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '1'`. Final step: - The shortcut and the main path values are added together.- Then apply the ReLU activation function. This has no name and no hyperparameters. **Exercise**: Implement the convolutional block. We have implemented the first component of the main path; you should implement the rest. As before, always use 0 as the seed for the random initialization, to ensure consistency with our grader.- [Conv2D](https://keras.io/layers/convolutional/conv2d)- [BatchNormalization](https://keras.io/layers/normalization/batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))- For the activation, use: `Activation('relu')(X)`- [Add](https://keras.io/layers/merge/add)
###Code
# GRADED FUNCTION: convolutional_block
def convolutional_block(X, f, filters, stage, block, s = 2):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
stage -- integer, used to name the layers, depending on their position in the network
block -- string/character, used to name the layers, depending on their position in the network
s -- Integer, specifying the stride to be used
Returns:
X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)
"""
# defining name basis
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
# Retrieve Filters
F1, F2, F3 = filters
# Save the input value
X_shortcut = X
##### MAIN PATH #####
# First component of main path
X = Conv2D(F1, (1, 1), strides = (s,s), name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X)
X = Activation('relu')(X)
### START CODE HERE ###
# Second component of main path (≈3 lines)
X = None
X = None
X = None
# Third component of main path (≈2 lines)
X = None
X = None
##### SHORTCUT PATH #### (≈2 lines)
X_shortcut = None
X_shortcut = None
# Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)
X = None
X = None
### END CODE HERE ###
return X
tf.reset_default_graph()
with tf.Session() as test:
np.random.seed(1)
A_prev = tf.placeholder("float", [3, 4, 4, 6])
X = np.random.randn(3, 4, 4, 6)
A = convolutional_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
test.run(tf.global_variables_initializer())
out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
print("out = " + str(out[0][1][1][0]))
###Output
_____no_output_____
###Markdown
**Expected Output**: **out** [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603] 3 - Building your first ResNet model (50 layers)You now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the architecture of this neural network. "ID BLOCK" in the diagram stands for "Identity block," and "ID BLOCK x3" means you should stack 3 identity blocks together. **Figure 5** : **ResNet-50 model** The details of this ResNet-50 model are:- Zero-padding pads the input with a pad of (3,3)- Stage 1: - The 2D Convolution has 64 filters of shape (7,7) and uses a stride of (2,2). Its name is "conv1". - BatchNorm is applied to the 'channels' axis of the input. - MaxPooling uses a (3,3) window and a (2,2) stride.- Stage 2: - The convolutional block uses three sets of filters of size [64,64,256], "f" is 3, "s" is 1 and the block is "a". - The 2 identity blocks use three sets of filters of size [64,64,256], "f" is 3 and the blocks are "b" and "c".- Stage 3: - The convolutional block uses three sets of filters of size [128,128,512], "f" is 3, "s" is 2 and the block is "a". - The 3 identity blocks use three sets of filters of size [128,128,512], "f" is 3 and the blocks are "b", "c" and "d".- Stage 4: - The convolutional block uses three sets of filters of size [256, 256, 1024], "f" is 3, "s" is 2 and the block is "a". - The 5 identity blocks use three sets of filters of size [256, 256, 1024], "f" is 3 and the blocks are "b", "c", "d", "e" and "f".- Stage 5: - The convolutional block uses three sets of filters of size [512, 512, 2048], "f" is 3, "s" is 2 and the block is "a". - The 2 identity blocks use three sets of filters of size [512, 512, 2048], "f" is 3 and the blocks are "b" and "c".- The 2D Average Pooling uses a window of shape (2,2) and its name is "avg_pool".- The 'flatten' layer doesn't have any hyperparameters or name.- The Fully Connected (Dense) layer reduces its input to the number of classes using a softmax activation. Its name should be `'fc' + str(classes)`.**Exercise**: Implement the ResNet with 50 layers described in the figure above. We have implemented Stages 1 and 2. Please implement the rest. (The syntax for implementing Stages 3-5 should be quite similar to that of Stage 2.) Make sure you follow the naming convention in the text above. You'll need to use this function: - Average pooling [see reference](https://keras.io/layers/pooling/averagepooling2d)Here are some other functions we used in the code below:- Conv2D: [See reference](https://keras.io/layers/convolutional/conv2d)- BatchNorm: [See reference](https://keras.io/layers/normalization/batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis))- Zero padding: [See reference](https://keras.io/layers/convolutional/zeropadding2d)- Max pooling: [See reference](https://keras.io/layers/pooling/maxpooling2d)- Fully connected layer: [See reference](https://keras.io/layers/core/dense)- Addition: [See reference](https://keras.io/layers/merge/add)
###Code
# GRADED FUNCTION: ResNet50
def ResNet50(input_shape = (64, 64, 3), classes = 6):
"""
Implementation of the popular ResNet50 the following architecture:
CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3
-> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER
Arguments:
input_shape -- shape of the images of the dataset
classes -- integer, number of classes
Returns:
model -- a Model() instance in Keras
"""
# Define the input as a tensor with shape input_shape
X_input = Input(input_shape)
# Zero-Padding
X = ZeroPadding2D((3, 3))(X_input)
# Stage 1
X = Conv2D(64, (7, 7), strides = (2, 2), name = 'conv1', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(axis = 3, name = 'bn_conv1')(X)
X = Activation('relu')(X)
X = MaxPooling2D((3, 3), strides=(2, 2))(X)
# Stage 2
X = convolutional_block(X, f = 3, filters = [64, 64, 256], stage = 2, block='a', s = 1)
X = identity_block(X, 3, [64, 64, 256], stage=2, block='b')
X = identity_block(X, 3, [64, 64, 256], stage=2, block='c')
### START CODE HERE ###
# Stage 3 (≈4 lines)
X = None
X = None
X = None
X = None
# Stage 4 (≈6 lines)
X = None
X = None
X = None
X = None
X = None
X = None
# Stage 5 (≈3 lines)
X = None
X = None
X = None
# AVGPOOL (≈1 line). Use "X = AveragePooling2D(...)(X)"
X = None
### END CODE HERE ###
# output layer
X = Flatten()(X)
X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer = glorot_uniform(seed=0))(X)
# Create model
model = Model(inputs = X_input, outputs = X, name='ResNet50')
return model
###Output
_____no_output_____
###Markdown
Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below.
###Code
model = ResNet50(input_shape = (64, 64, 3), classes = 6)
###Output
_____no_output_____
###Markdown
As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model.
###Code
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
###Output
_____no_output_____
###Markdown
The model is now ready to be trained. The only thing you need is a dataset. Let's load the SIGNS Dataset. **Figure 6** : **SIGNS dataset**
###Code
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
# Normalize image vectors
X_train = X_train_orig/255.
X_test = X_test_orig/255.
# Convert training and test labels to one hot matrices
Y_train = convert_to_one_hot(Y_train_orig, 6).T
Y_test = convert_to_one_hot(Y_test_orig, 6).T
print ("number of training examples = " + str(X_train.shape[0]))
print ("number of test examples = " + str(X_test.shape[0]))
print ("X_train shape: " + str(X_train.shape))
print ("Y_train shape: " + str(Y_train.shape))
print ("X_test shape: " + str(X_test.shape))
print ("Y_test shape: " + str(Y_test.shape))
###Output
_____no_output_____
###Markdown
Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch.
###Code
model.fit(X_train, Y_train, epochs = 2, batch_size = 32)
###Output
_____no_output_____
###Markdown
**Expected Output**: ** Epoch 1/2** loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours. ** Epoch 2/2** loss: between 1 and 5, acc: between 0.2 and 0.5, you should see your loss decreasing and the accuracy increasing. Let's see how this model (trained on only two epochs) performs on the test set.
###Code
preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1]))
###Output
_____no_output_____
###Markdown
**Expected Output**: **Test Accuracy** between 0.16 and 0.25 For the purpose of this assignment, we've asked you to train the model for just two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check correctness, the online grader will run your code only for a small number of epochs as well. After you have finished this official (graded) part of this assignment, you can also optionally train the ResNet for more iterations, if you want. We get a lot better performance when we train for ~20 epochs, but this will take more than an hour when training on a CPU. Using a GPU, we've trained our own ResNet50 model's weights on the SIGNS dataset. You can load and run our trained model on the test set in the cells below. It may take ≈1min to load the model.
###Code
model = load_model('ResNet50.h5')
preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1]))
###Output
_____no_output_____
###Markdown
ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy.Congratulations on finishing this assignment! You've now implemented a state-of-the-art image classification system! 4 - Test on your own image (Optional/Ungraded) If you wish, you can also take a picture of your own hand and see the output of the model. To do this: 1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub. 2. Add your image to this Jupyter Notebook's directory, in the "images" folder 3. Write your image's name in the following code 4. Run the code and check if the algorithm is right!
###Code
img_path = 'images/my_image.jpg'
img = image.load_img(img_path, target_size=(64, 64))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = x/255.0
print('Input image shape:', x.shape)
my_image = scipy.misc.imread(img_path)
imshow(my_image)
print("class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = ")
print(model.predict(x))
###Output
_____no_output_____
###Markdown
You can also print a summary of your model by running the following code.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to "File -> Open...-> model.png".
###Code
plot_model(model, to_file='model.png')
SVG(model_to_dot(model).create(prog='dot', format='svg'))
###Output
_____no_output_____ |
03_neural_networks_tutorial.ipynb | ###Markdown
Neural Networks===============Neural networks can be constructed using the ``torch.nn`` package.Now that you had a glimpse of ``autograd``, ``nn`` depends on``autograd`` to define models and differentiate them.An ``nn.Module`` contains layers, and a method ``forward(input)``\ thatreturns the ``output``.For example, look at this network that classifies digit images:.. figure:: /_static/img/mnist.png :alt: convnet convnetIt is a simple feed-forward network. It takes the input, feeds itthrough several layers one after the other, and then finally gives theoutput.A typical training procedure for a neural network is as follows:- Define the neural network that has some learnable parameters (or weights)- Iterate over a dataset of inputs- Process input through the network- Compute the loss (how far is the output from being correct)- Propagate gradients back into the network’s parameters- Update the weights of the network, typically using a simple update rule: ``weight = weight - learning_rate * gradient``Define the network------------------Let’s define this network:
###Code
import torch
import torch.nn as nn
import torch.nn.functional as F
print("GPU available: ", torch.cuda.device_count())
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
# If want to change input image size, then here the input size of FC1 should be changed accordingly
# Notice, the 5 * 5 on above line is not directly the kernel size (which is, by coincidence), but the output size after a sequence of
# stacked layers defined in forward pass.
# Say, we are to change the input size and left as many layers intact as possible, then modify dimension of fc1 is applausible.
# self.fc1 = nn.Linear(16 * 7 * 7, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
print(type(net))
###Output
GPU available: 2
Net(
(conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
<class '__main__.Net'>
###Markdown
You just have to define the ``forward`` function, and the ``backward``function (where gradients are computed) is automatically defined for youusing ``autograd``.You can use any of the Tensor operations in the ``forward`` function.The learnable parameters of a model are returned by ``net.parameters()``
###Code
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
###Output
10
torch.Size([6, 1, 5, 5])
###Markdown
Let try a random 32x32 inputNote: Expected input size to this net(LeNet) is 32x32. To use this net onMNIST dataset, please resize the images from the dataset to 32x32.
###Code
# input = torch.randn(1, 1, 40, 40) # <- should be change to 40 x 40 if fc1 changed to 16 * 7 * 7 (vice versa)
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
###Output
tensor([[-0.0410, 0.0804, -0.0568, -0.0291, 0.0097, 0.1180, 0.0369, -0.1056,
0.0914, -0.1102]], grad_fn=<ThAddmmBackward>)
###Markdown
Zero the gradient buffers of all parameters and backprops with randomgradients:
###Code
net.zero_grad() # set all gradients to 0
out.backward(torch.randn(1, 10)) # backprop with random initial gradients
###Output
_____no_output_____
###Markdown
Note ``torch.nn`` only supports mini-batches. The entire ``torch.nn`` package only supports inputs that are a mini-batch of samples, and not a single sample. For example, ``nn.Conv2d`` will take in a 4D Tensor of ``nSamples x nChannels x Height x Width``. If you have a single sample, just use ``input.unsqueeze(0)`` to add a fake batch dimension. Before proceeding further, let's recap all the classes you’ve seen so far. **Recap:** - ``torch.Tensor`` - A *multi-dimensional array* with support for autograd operations like ``backward()``. Also *holds the gradient* w.r.t. the tensor. - ``nn.Module`` - Neural network module. *Convenient way of encapsulating parameters*, with helpers for moving them to GPU, exporting, loading, etc. - ``nn.Parameter`` - A kind of Tensor, that is *automatically registered as a parameter when assigned as an attribute to a* ``Module``. - ``autograd.Function`` - Implements *forward and backward definitions of an autograd operation*. Every ``Tensor`` operation, creates at least a single ``Function`` node, that connects to functions that created a ``Tensor`` and *encodes its history*.**At this point, we covered:** - Defining a neural network - Processing inputs and calling backward**Still Left:** - Computing the loss - Updating the weights of the networkLoss Function-------------A loss function takes the (output, target) pair of inputs, and computes avalue that estimates how far away the output is from the target.There are several different`loss functions `_ under thenn package .A simple loss is: ``nn.MSELoss`` which computes the mean-squared errorbetween the input and the target.For example:
###Code
output = net(input)
target = torch.randn(10) # a dummy target, for example
target = target.view(1, -1) # make it the same shape as output
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
###Output
tensor(1.6893, grad_fn=<MseLossBackward>)
###Markdown
Now, if you follow ``loss`` in the backward direction, using its``.grad_fn`` attribute, you will see a graph of computations that lookslike this::: input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> view -> linear -> relu -> linear -> relu -> linear -> MSELoss -> lossSo, when we call ``loss.backward()``, the whole graph is differentiatedw.r.t. the loss, and all Tensors in the graph that has ``requires_grad=True``will have their ``.grad`` Tensor accumulated with the gradient.For illustration, let us follow a few steps backward:
###Code
print(loss.grad_fn) # MSELoss
print(loss.grad_fn.next_functions[0][0]) # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
###Output
<MseLossBackward object at 0x000001D44F8B9F98>
<ThAddmmBackward object at 0x000001D44E145A58>
<ExpandBackward object at 0x000001D44F8B9F98>
###Markdown
Backprop--------To backpropagate the error all we have to do is to ``loss.backward()``.You need to clear the existing gradients though, else gradients will beaccumulated to existing gradients.Now we shall call ``loss.backward()``, and have a look at conv1's biasgradients before and after the backward.
###Code
net.zero_grad() # zeroes the gradient buffers of all parameters
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
loss.backward()
print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)
###Output
conv1.bias.grad before backward
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([-0.0092, -0.0081, -0.0127, 0.0025, -0.0033, 0.0077])
###Markdown
Now, we have seen how to use loss functions.**Read Later:** The neural network package contains various modules and loss functions that form the building blocks of deep neural networks. A full list with documentation is `here `_.**The only thing left to learn is:** - Updating the weights of the networkUpdate the weights------------------The simplest update rule used in practice is the Stochastic GradientDescent (SGD): ``weight = weight - learning_rate * gradient``We can implement this using simple python code:.. code:: python learning_rate = 0.01 for f in net.parameters(): f.data.sub_(f.grad.data * learning_rate)However, as you use neural networks, you want to use various differentupdate rules such as **SGD, Nesterov-SGD, Adam, RMSProp**, etc.To enable this, we built a small package: ``torch.optim`` thatimplements all these methods. Using it is very simple:
###Code
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)
# in your training loop:
optimizer.zero_grad() # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # Does the update
###Output
_____no_output_____ |
notebooks/Sim_mb_image.ipynb | ###Markdown
1. Generate a mass modelSimple SPEMD profile, using GLEE parameter conventions
###Code
num_pix = 100
x_grid, y_grid = coordinates.square_grid(num_pix)
print(x_grid, y_grid)
#extra_num_pix = 3000
#x_grid_large, y_grid_large = coordinates.square_grid(num_pix + extra_num_pix)
source_to_image_ratio = 1
num_pix_src = num_pix * source_to_image_ratio
kwargs_spemd = {
'x0': 50.5, # pixels (origin : lower left pixel)
'y0': 50.5, # pixels (origin : lower left pixel)
'gamma': 0.3,
'theta_E': 25., # pixels
'q': 0.8,
'phi': 0.3,
'r_core': 0.01, # pixels
}
# WARNING : no Dds/Ds (physical to scaled conversion) scaling
mass_model = SPEMD_glee(kwargs_spemd, Dds_Ds=None)
kappa = mass_model.convergence(x_grid, y_grid)
alpha1, alpha2 = mass_model.deflection(x_grid, y_grid)
#kwargs_spemd_large = copy.deepcopy(kwargs_spemd)
#kwargs_spemd_large['x0'] = kwargs_spemd['x0'] + extra_num_pix/2
#kwargs_spemd_large['y0'] = kwargs_spemd['y0'] + extra_num_pix/2
#kappa_large = mass_model_large.convergence(x_grid_large, y_grid_large)
#mass_model_large = SPEMD_glee(kwargs_spemd_large, Dds_Ds=None)
ax = plt.subplot2grid((1, 2), (0, 0), fig=plt.figure(figsize=(10, 4)))
im = ax.imshow(np.log10(kappa), origin='lower')
ax.set_title("$\kappa$")
nice_colorbar(im)
ax = plt.subplot2grid((1, 2), (0, 1))
im = ax.imshow(np.sqrt(alpha1**2+alpha2**2), origin='lower')
ax.set_title(r"$|\ \alpha\,|$")
nice_colorbar(im)
plt.show()
lensing_operator = planes.build_lensing_operator(None, num_pix, source_to_image_ratio,
alpha_x_in=alpha1, alpha_y_in=alpha2)
print(type(lensing_operator), len(lensing_operator))
#lensing_operator_kappa = planes.build_lensing_operator(kappa_large, num_pix, source_to_image_ratio)
image_ones = np.ones((num_pix, num_pix))
source_ones = planes.image_to_source(image_ones, lensing_operator, num_pix_src)
#source_ones_kappa = planes.image_to_source(image_ones, lensing_operator_kappa, num_pix_src)
plt.imshow(source_ones, origin='lower')
plt.show()
###Output
Deflection angles have been provided
<class 'list'> 10000
###Markdown
2. Simulate a single-band image
###Code
kwargs_gaussian_ell = {'x0': 51, 'y0': 52, 'sigma': 2, 'phi': 0.3, 'q': 0.6, 'amp': 1}
gaussian_source = GaussianElliptical(kwargs_gaussian_ell).function(x_grid, y_grid)
kwargs_gaussian = {'x0': 50, 'y0': 50, 'sigma_x': 8, 'sigma_y': 8, 'amp': 7}
gaussian_lens = Gaussian(kwargs_gaussian).function(x_grid, y_grid)
ax = plt.subplot2grid((1, 2), (0, 0), fig=plt.figure(figsize=(10, 4)))
im= ax.imshow(gaussian_lens, origin='lower')
nice_colorbar(im)
ax = plt.subplot2grid((1, 2), (0, 1))
im= ax.imshow(gaussian_source, origin='lower')
nice_colorbar(im)
plt.show()
#data_dir = '/Users/aymericg/Documents/EPFL/PhD_LASTRO/Code/Lens_modelling/gravlensgen/Data/various_images'
#galaxy_source = pyfits.open(os.path.join(data_dir, 'M81_HST_prepared_n100.fits'))[0].data
#print(galaxy_source.shape)
#
#plt.imshow(galaxy_source, origin='lower')
#plt.colorbar()
#plt.show()
# normalization
galaxy_source = gaussian_source/gaussian_source.max()
galaxy_lens = gaussian_lens/gaussian_lens.max()
galaxy_lensed = planes.source_to_image(galaxy_source, lensing_operator, num_pix)
print(galaxy_lensed.max())
galaxy_unlensed = planes.image_to_source(galaxy_lensed, lensing_operator, num_pix_src)
print(galaxy_unlensed.max())
ax = plt.subplot2grid((1, 3), (0, 0), fig=plt.figure(figsize=(20, 6)))
im = ax.imshow(galaxy_lensed, origin='lower')
nice_colorbar(im)
ax = plt.subplot2grid((1, 3), (0, 1))
im = ax.imshow(galaxy_unlensed, origin='lower')
nice_colorbar(im)
ax = plt.subplot2grid((1, 3), (0, 2))
im = ax.imshow(galaxy_source-galaxy_unlensed, origin='lower', cmap='bwr_r', vmin=-0.01, vmax=0.01)
nice_colorbar(im)
plt.show()
sim_lens_base = galaxy_lensed + galaxy_lens
###Output
_____no_output_____
###Markdown
3. Generate a multi(3)-band image
###Code
def bands2image(band_list):
return np.stack(band_list, axis=2)
def plot_rgb_bands(color_image_np):
band_r = color_image_np[:,:,0]
band_g = color_image_np[:,:,1]
band_b = color_image_np[:,:,2]
vmax = max((band_r.max(), band_g.max(), band_b.max()))
fig, axes = plt.subplots(1, 4, figsize=(16, 5))
ax = axes[0]
im = ax.imshow(band_r, origin='lower', cmap='Reds_r', vmax=vmax)
#fig.colorbar(im, ax=ax)
ax = axes[1]
ax.imshow(band_g, origin='lower', cmap='Greens_r', vmax=vmax)
ax = axes[2]
ax.imshow(band_b, origin='lower', cmap='Blues_r', vmax=vmax)
ax = axes[3]
ax.imshow(lin(color_image_np), origin='lower')
plt.show()
###Output
_____no_output_____
###Markdown
Define spectral energy distributions
###Code
lens_SEDs = (1.0, 0.7, 0.4) # not normalized
source_SEDs = (0.6, 0.7, 0.8) # not normalized
lens_multiband = [galaxy_lens * sed for sed in lens_SEDs]
lens_multiband = bands2image(lens_multiband)
lensed_multiband = [planes.source_to_image(galaxy_source*sed, lensing_operator, num_pix) for sed in source_SEDs]
lensed_multiband = bands2image(lensed_multiband)
sim_lens_multiband_no_noise = lens_multiband + lensed_multiband
###Output
_____no_output_____
###Markdown
Add noise_Only gaussian for simplicity_
###Code
noise1 = np.random.randn(num_pix, num_pix) * 0.05 # arbitrary units for now
noise2 = np.random.randn(num_pix, num_pix) * 0.05
noise3 = np.random.randn(num_pix, num_pix) * 0.05
noise_multiband = bands2image([noise1, noise2, noise3])
sim_lens_multiband = sim_lens_multiband_no_noise + noise_multiband
plot_rgb_bands(sim_lens_multiband)
###Output
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
|
Assignment_28_Jan_2022(movie_dataset).ipynb | ###Markdown
1.Profit = (Revenue - Budget)/Budget2.Do the movies that have high vote_avergae make lot of profits ?3.What genres make the most money?4.Which producers generally do well?5.Is there a bias with producers in terms of genres that they do - Do specific producer only produce specific genre movies?6.Will a longer run time bring higher profits?7.Does the presence of a homepage indicate higher profits8.Which languages rakes in high profit9.Over a period of time, how have the profitability changed - Over the period of time, which genre of movies have grossed well ?10.If the movie speaks multiple languages, is the profit % higher?
###Code
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import plotly.express as px
df = pd.read_csv('/content/drive/MyDrive/datasets/finalCleanedData.csv')
df.head(5)
###Output
_____no_output_____
###Markdown
**1.Profit = (Revenue - Budget)/Budget**
###Code
plotdata = pd.DataFrame({
"Budget":df["budget"][:10],
"Profit":df["revenue"][:10]},
index=df["original_title"][:10])
plotdata.plot(kind="bar",figsize=(15, 8))
plt.title("Profit and Budget chart")
plt.xlabel("Movies title")
plt.ylabel("Amount")
###Output
_____no_output_____
###Markdown
**2. Do the movies that have high vote_average make lot of profits?**
###Code
df2 = df.sort_values(by=['vote_average'])
plt.plot(df2["vote_average"], df2["profit"])
plt.show()
###Output
_____no_output_____
###Markdown
**Remarks for above question:** As we can see most of the profit spikes are available on the movies which has greater than 6 vote average. So yes higher vote average movies has higher profits. **3**. What genres make the most money?
###Code
df["genre1"].isna().sum()
df3 = df[df['genre1'].notna()]
# df3["genre1"].unique()
var = df3.groupby('genre1').profit.sum()
var
fig, ax1 = plt.subplots()
ax1.set_xlabel('Genre')
ax1.set_ylabel('Sum of Profit')
ax1.set_title("Profit genre wise")
var.plot(kind='bar',figsize=(20, 8))
###Output
_____no_output_____
###Markdown
**Remarks for above question:** As per the graph Drama, comedy, horor types of movies genres make the most money. **4. Which producers generally do well?**
###Code
df["Producer1"].isna().sum()
df4 = df[df['Producer1'].notna()]
df4["Producer1"].unique()
b = df4["Producer1"].unique()
len(b)
df4_1 = df4.groupby("Producer1").profit.sum().to_frame("Profit").reset_index()
df4_1
df4_1 = df4_1.sort_values('Profit', ascending=False)
df4_1[:20].plot(
x = "Producer1",
y = "Profit",
kind='bar',
xlabel ='Producers',
ylabel = 'Sum of Profit',
title ='Successful producers on the basis of their profits',
figsize=(20, 8))
###Output
_____no_output_____
###Markdown
**Remarks for above question:** As per the above graph Paramount Pictures and universal pictures are most successful **5.Is there a bias with producers in terms of genres that they do - Do specific producer only produce specific genre movies?**
###Code
###Output
_____no_output_____
###Markdown
**Remarks for above question:** **6. Will a longer run time bring higher profits?**
###Code
df6 = df[["runtime", "profit"]].copy()
df6.isna().sum()
df6 = df6[df6['runtime'].notna()]
df6 = df6.sort_values('runtime', ascending=False)
df6
df6.plot(
x = "runtime",
y = "profit",
kind='line',
xlabel ='Runtime',
ylabel = 'Sum of Profit',
title ='Profits on the basis of runtime',
figsize=(30, 10))
###Output
_____no_output_____
###Markdown
**Remarks for above question:** As per the latest graph movies which has runtime between 70 to 150 earns most profit. **7. Does the presence of a homepage indicate higher profits**
###Code
df["homePagePresent"].isna().sum()
df7 = df.groupby("homePagePresent").profit.sum().to_frame("Profit")
df7
df7.plot.pie(y="Profit", figsize=(5, 5))
###Output
_____no_output_____
###Markdown
**Remarks for above question:** As per the above graph, the movies which doesnt have home page present earns most. **8. Which languages takes in high profit**
###Code
df["original_language"].isna().sum()
len(df["original_language"].unique())
#Draw bar chart with profit on y axis and original_language in x axis
df8 = df.groupby("original_language").profit.sum().to_frame("Profit").reset_index()
df8
df8 = df8.sort_values('Profit', ascending=False)
df8[:15].plot(
x = "original_language",
y = "Profit",
kind='bar',
xlabel ='original_language',
ylabel = 'Sum of Profit',
title =' Original language graph on the basis of their profits',
figsize=(20, 8))
###Output
_____no_output_____
###Markdown
**Remarks for above question: ** english movies earns most **9. Over a period of time, how have the profitability changed - Over the period of time, which genre of movies have grossed well ?**
###Code
df9 = df[["release_date", "profit", "genre1"]].copy()
df9 = df9[df9['genre1'].notna()]
df9["release_date"] = pd.to_datetime(df9['release_date'])
df9['year'] = df9['release_date'].dt.year
df9 = df9.sort_values('year')
df9
###Output
_____no_output_____
###Markdown
**10. If the movie speaks multiple languages, is the profit % higher?**
###Code
df["TotalLanguages"].isna().sum()
len(df["TotalLanguages"].unique())
#Draw bar chart with profit on y axis and totallanguages in x axis
df10 = df.groupby("TotalLanguages").profit.sum().to_frame("Profit").reset_index()
df10
df10 = df10.sort_values('Profit', ascending=False)
df10.plot(
x = "TotalLanguages",
y = "Profit",
kind='bar',
xlabel ='Total Languages',
ylabel = 'Sum of Profit',
title =' Total Languages graph on the basis of their profits',
figsize=(20, 8))
###Output
_____no_output_____ |
04-dshboards-html.ipynb | ###Markdown
Dashboards usando HTML===**Juan David Velásquez Henao** [email protected] Universidad Nacional de Colombia, Sede Medellín Facultad de Minas Medellín, Colombia---Haga click [aquí](https://github.com/jdvelasq/Python-for-data-products/tree/master/) para acceder al repositorio online.Haga click [aquí](http://nbviewer.jupyter.org/github/jdvelasq/Python-for-data-products/tree/master/) para explorar el repositorio usando `nbviewer`. --- Estos ejemplos son adaptados de [w3schools](https://www.w3schools.com/howto/default.asp). --- **Preparación.--** El siguiente código genera las gráficas usadas en los demás ejemplos.
###Code
!rm -R examples-04-dashboards
!mkdir examples-04-dashboards
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*3.1416, 50, endpoint=True)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, color ='blue');
plt.xlabel('x');
plt.ylabel('Sin(x)');
plt.savefig('examples-04-dashboards/sin.png')
plt.savefig('examples-04-dashboards/sin.pdf')
plt.clf();
plt.plot(x, y2, color = 'red');
plt.xlabel('x');
plt.ylabel('Cos(x)');
plt.savefig('examples-04-dashboards/cos.png');
plt.close()
###Output
_____no_output_____
###Markdown
**Ejemplo 1.--** Página web mínima para visualizar las gráficas.
###Code
%%writefile examples-04-dashboards/dashboard1.html
<!DOCTYPE html>
<html>
<head>
<title>Mi primer dashboard</title>
</head>
<body>
<h1>Este es mi primer dashboard en html</h1>
<p>Este es un parrafo.</p>
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Sin(x)">
</body>
</html>
###Output
Writing examples-04-dashboards/dashboard1.html
###Markdown
**Ejemplo 2.--** Texto dinámico.
###Code
from jinja2 import Template
texto = """
<!DOCTYPE html>
<html>
<head>
<title>Mi primer dashboard</title>
</head>
<body>
<h1>Este es mi primer dashboard en html</h1>
<p>Este es un parrafo.</p>
<p>Este es el valor de la variable myvar = {{ myvar }}</p>
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Sin(x)">
</body>
</html>
"""
template = Template(texto)
file = open("examples-04-dashboards/dashboard2.html","w")
file.write( template.render(myvar = 123456789))
file.close()
###Output
_____no_output_____
###Markdown
**Ejemplo 3.--** Formato de secciones tipo acordeón.
###Code
%%writefile examples-04-dashboards/dashboard3.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
}
</style>
</head>
<body>
<center>
<h1>Titulo del Dashboard</h1>
</center>
<button class="accordion">Grafica 1</button>
<div class="panel">
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
</div>
<button class="accordion">Grafica 2</button>
<div class="panel">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Sin(x)">
</div>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
</script>
</body>
</html>
###Output
Writing examples-04-dashboards/dashboard3.html
###Markdown
**Ejemplo 4.--** Tabs horizontales.
###Code
%%writefile examples-04-dashboards/dashboard4.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial;}
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
</head>
<body>
<p>Haga clic en una de las pestanas:</p>
<div class="tab">
<button class="tablinks" onclick="openTab(event, 'Grafica1')">Grafica 1</button>
<button class="tablinks" onclick="openTab(event, 'Grafica2')">Grafica 2</button>
</div>
<div id="Grafica1" class="tabcontent">
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
</div>
<div id="Grafica2" class="tabcontent">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Cos(x)">
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
</body>
</html>
###Output
Writing examples-04-dashboards/dashboard4.html
###Markdown
**Ejemplo 5.--** Tabs verticales.
###Code
%%writefile examples-04-dashboards/dashboard5.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box}
body {font-family: "Lato", sans-serif;}
/* Style the tab */
.tab {
float: left;
border: 1px solid #ccc;
background-color: #f1f1f1;
width: 30%;
height: 300px;
}
/* Style the buttons inside the tab */
.tab button {
display: block;
background-color: inherit;
color: black;
padding: 22px 16px;
width: 100%;
border: none;
outline: none;
text-align: left;
cursor: pointer;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current "tab button" class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
float: left;
padding: 0px 12px;
border: 1px solid #ccc;
width: 70%;
border-left: none;
height: 300px;
}
</style>
</head>
<body>
<p>Haga click en el menu de abajo:</p>
<div class="tab">
<button class="tablinks" onclick="openTab(event, 'Grafica1')" id="defaultOpen">Grafica 1</button>
<button class="tablinks" onclick="openTab(event, 'Grafica2')">Grafica 2</button>
</div>
<div id="Grafica1" class="tabcontent">
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
</div>
<div id="Grafica2" class="tabcontent">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Cos(x)">
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
</body>
</html>
###Output
Writing examples-04-dashboards/dashboard5.html
###Markdown
**Ejemplo 6.--** Tabs encabezamiento.
###Code
%%writefile examples-04-dashboards/dashboard6.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: "Lato", sans-serif;}
.tablink {
background-color: #555;
color: white;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
font-size: 17px;
width: 25%;
}
.tablink:hover {
background-color: #777;
}
/* Style the tab content */
.tabcontent {
color: white;
display: none;
padding: 90px;
text-align: left;
}
</style>
</head>
<body>
<p>Haga click en el menu:</p>
<div id="Grafica1" class="tabcontent">
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
</div>
<div id="Grafica2" class="tabcontent">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Cos(x)">
</div>
<button class="tablink" onclick="openTab('Grafica1', this, 'red')" id="defaultOpen">Grafica 1</button>
<button class="tablink" onclick="openTab('Grafica2', this, 'green')">Grafica 2</button>
<script>
function openTab(tabName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(tabName).style.display = "block";
elmnt.style.backgroundColor = color;
}
document.getElementById("defaultOpen").click();
</script>
</body>
</html>
###Output
Writing examples-04-dashboards/dashboard6.html
###Markdown
**Ejemplo 7.--** Malla de imagenes.
###Code
%%writefile examples-04-dashboards/dashboard7.html
<!DOCTYPE html>
<html>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial;
}
.header {
text-align: center;
padding: 32px;
}
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 50%;
padding: 10px;
}
.column img {
margin-top: 12px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
</style>
<body>
<!-- Header -->
<div class="header">
<h1>Malla</h1>
</div>
<!-- Photo Grid -->
<div class="row">
<div class="column">
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
</div>
<div class="column">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Cos(x)">
</div>
</div>
</body>
</html>
###Output
Writing examples-04-dashboards/dashboard7.html
###Markdown
**Ejemplo 8.--** Ejemplo elaborado.
###Code
%%writefile examples-04-dashboards/dashboard8.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box}
body {font-family: "Lato", sans-serif;}
<!----------------------------- 3 columnas superiores ----------------------->
.column {
width: 25%;
float: left;
padding: 10px;
height: 200px; /* Should be removed. Only for demonstration */
}
.row:after {
content: "";
display: table;
clear: both;
}
/* Style the tab */
.tab {
float: left;
border: 1px solid #eee;
background-color: #eee;
width: 10%;
height: 500px;
}
/* Style the buttons inside the tab */
.tab button {
display: block;
background-color: inherit;
color: black;
padding: 10px 16px; /* ancho y largo del boton*/
width: 100%;
border: none;
outline: none;
text-align: right;
cursor: pointer;
transition: 0.3s;
font-size: 14px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current "tab button" class */
.tab button.active {
color: white;
background-color: #2E9AFE;
}
/* Style the tab content */
.tabcontent {
float: left;
padding: 0px 12px;
border: 1px solid #ccc;
width: 70%;
border-left: none;
height: 200px;
}
.avatar {
vertical-align: middle;
width: 50px;
height: 50px;
border-radius: 50%;
}
.container {
width: 100%;
background-color: #ddd;
}
.skills {
text-align: right;
padding-right: 20px;
line-height: 40px;
color: white;
}
.html {width: 90%; background-color: #4CAF50;}
.css {width: 80%; background-color: #2196F3;}
.js {width: 65%; background-color: #f44336;}
.php {width: 60%; background-color: #808080;}
.danger {
background-color: #ffdddd;
border-left: 6px solid #f44336;
}
.success {
background-color: #ddffdd;
border-left: 6px solid #4CAF50;
}
.info {
background-color: #e7f3fe;
border-left: 6px solid #2196F3;
}
.warning {
background-color: #ffffcc;
border-left: 6px solid #ffeb3b;
}
</style>
</head>
<body>
<h1><font color=#FF8000>Dashboard</font></h1>
<div class="row">
<div class="column" style="background-color:#aaa;">
<h2>Column 1</h2>
<img src="img_avatar1.png" alt="Avatar" class="avatar">
</div>
<div class="column" style="background-color:#bbb;">
<h2>Column 2</h2>
<img src="img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="column" style="background-color:#ccc;">
<h2>Column 3</h2>
<img src="img_avatar3.png" alt="Avatar" class="avatar">
</div>
</div>
<div class="tab">
<button class="tablinks" onclick="openTab(event, 'Dashboard1')" id="defaultOpen">
<img src="img_avatar1.png" alt="Avatar" class="avatar">
Dashboard 1
</button>
<button class="tablinks" onclick="openTab(event, 'Dashboard2')">Dashboard 2</button>
<button class="tablinks" onclick="openTab(event, 'Dashboard3')">Dashboard 3</button>
<button class="tablinks" onclick="openTab(event, 'Dashboard4')">Dashboard 4</button>
</div>
<div id="Dashboard1" class="tabcontent">
<p>Grafica de Sin(x).</p>
<img src="sin.png" alt="Sin(x)">
</div>
<div id="Dashboard2" class="tabcontent">
<p>Grafica de Cos(x).</p>
<img src="cos.png" alt="Cos(x)">
</div>
<div id="Dashboard3" class="tabcontent">
<p>HTML</p> <div class="container"> <div class="skills html">90%</div> </div>
<p>CSS</p> <div class="container"> <div class="skills css">80%</div> </div>
<p>JavaScript</p> <div class="container"> <div class="skills js">65%</div> </div>
<p>PHP</p> <div class="container">
<div class="skills php">60%</div>
</div>
</div>
<div id="Dashboard4" class="tabcontent">
<div class="danger"> <p><strong>Danger!</strong> Some text... </p> </div>
<div class="success"> <p><strong>Success!</strong> Some text...</p> </div>
<div class="info"> <p><strong>Info!</strong> Some text... </p> </div>
<div class="warning"> <p><strong>Warning!</strong> Some text...</p> </div>
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
</body>
</html>
###Output
Overwriting examples-04-dashboards/dashboard8.html
|
pandas-data-analysis-jovian.ipynb | ###Markdown
Assignment 3 - Pandas Data Analysis Practice*This assignment is a part of the course ["Data Analysis with Python: Zero to Pandas"](https://jovian.ml/learn/data-analysis-with-python-zero-to-pandas)*In this assignment, you'll get to practice some of the concepts and skills covered this tutorial: https://jovian.ml/aakashns/python-pandas-data-analysisAs you go through this notebook, you will find a **???** in certain places. To complete this assignment, you must replace all the **???** with appropriate values, expressions or statements to ensure that the notebook runs properly end-to-end. Some things to keep in mind:* Make sure to run all the code cells, otherwise you may get errors like `NameError` for undefined variables.* Do not change variable names, delete cells or disturb other existing code. It may cause problems during evaluation.* In some cases, you may need to add some code cells or new statements before or after the line of code containing the **???**. * Since you'll be using a temporary online service for code execution, save your work by running `jovian.commit` at regular intervals.* Questions marked **(Optional)** will not be considered for evaluation, and can be skipped. They are for your learning.You can make submissions on this page: https://jovian.ml/learn/data-analysis-with-python-zero-to-pandas/assignment/assignment-3-pandas-practiceIf you are stuck, you can ask for help on the community forum: https://jovian.ml/forum/t/assignment-3-pandas-practice/11225/3 . You can get help with errors or ask for hints, describe your approach in simple words, link to documentation, but **please don't ask for or share the full working answer code** on the forum. How to run the code and save your workThe recommended way to run this notebook is to click the "Run" button at the top of this page, and select "Run on Binder". This will run the notebook on [mybinder.org](https://mybinder.org), a free online service for running Jupyter notebooks. Before staring the assignment, let's save a snapshot of the assignment to your Jovian.ml profile, so that you can access it later, and continue your work.
###Code
!pip install jovian --upgrade
import jovian
jovian.commit(project='pandas-practice-assignment', environment=None)
# Run the next line to install Pandas
!pip install pandas --upgrade
import pandas as pd
###Output
_____no_output_____
###Markdown
In this assignment, we're going to analyze an operate on data from a CSV file. Let's begin by downloading the CSV file.
###Code
from urllib.request import urlretrieve
urlretrieve('https://hub.jovian.ml/wp-content/uploads/2020/09/countries.csv',
'countries.csv')
###Output
_____no_output_____
###Markdown
Let's load the data from the CSV file into a Pandas data frame.
###Code
countries_df = pd.read_csv('countries.csv')
countries_df
###Output
_____no_output_____
###Markdown
**Q: How many countries does the dataframe contain?**Hint: Use the `.shape` method.
###Code
num_countries = countries_df.shape[0]
print('There are {} countries in the dataset'.format(num_countries))
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Retrieve a list of continents from the dataframe?***Hint: Use the `.unique` method of a series.*
###Code
continents = countries_df.continent.unique()
continents
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: What is the total population of all the countries listed in this dataset?**
###Code
total_population = countries_df.population.sum()
print('The total population is {}.'.format(int(total_population)))
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: (Optional) What is the overall life expectancy across in the world?***Hint: You'll need to take a weighted average of life expectancy using populations as weights.*
###Code
overall_life_expectancy = round(((countries_df.population * countries_df.life_expectancy).sum()/countries_df.population.sum()),2)
print('The average life expectancy is {} years.'.format(overall_life_expectancy))
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Create a dataframe containing 10 countries with the highest population.***Hint: Chain the `sort_values` and `head` methods.*
###Code
most_populous_df = countries_df.sort_values(by=['population'], ascending=False).head(10)
most_populous_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Add a new column in `countries_df` to record the overall GDP per country (product of population & per capita GDP).**
###Code
countries_df['gdp'] = countries_df['gdp_per_capita'] * countries_df['population']
countries_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: (Optional) Create a dataframe containing 10 countries with the lowest GDP per capita, among the counties with population greater than 100 million.**
###Code
lowest_gdp_per_capita_df = countries_df[countries_df['population']> 10**8].sort_values(by = ['gdp_per_capita']).head(10)
lowest_gdp_per_capita_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Create a data frame that counts the number countries in each continent?***Hint: Use `groupby`, select the `location` column and aggregate using `count`.*
###Code
country_counts_df = countries_df.groupby(['continent']).count().location
country_counts_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Create a data frame showing the total population of each continent.***Hint: Use `groupby`, select the population column and aggregate using `sum`.*
###Code
continent_populations_df = countries_df.groupby(['continent']).sum().population
continent_populations_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
Let's download another CSV file containing overall Covid-19 stats for various countires, and read the data into another Pandas data frame.
###Code
urlretrieve('https://hub.jovian.ml/wp-content/uploads/2020/09/covid-countries-data.csv',
'covid-countries-data.csv')
covid_data_df = pd.read_csv('covid-countries-data.csv')
covid_data_df
###Output
_____no_output_____
###Markdown
**Q: Count the number of countries for which the `total_tests` data is missing.***Hint: Use the `.isna` method.*
###Code
total_tests_missing = covid_data_df.total_tests.isna().sum()
print("The data for total tests is missing for {} countries.".format(int(total_tests_missing)))
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
Let's merge the two data frames, and compute some more metrics.**Q: Merge `countries_df` with `covid_data_df` on the `location` column.***Hint: Use the `.merge` method on `countries_df`.
###Code
combined_df = countries_df.merge(covid_data_df, on = 'location')
combined_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Add columns `tests_per_million`, `cases_per_million` and `deaths_per_million` into `combined_df`.**
###Code
combined_df['tests_per_million'] = combined_df['total_tests'] * 1e6 / combined_df['population']
combined_df['cases_per_million'] = combined_df['total_cases']* 1e6 / combined_df['population']
combined_df['deaths_per_million'] = combined_df['total_deaths']* 1e6 / combined_df['population']
combined_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Create a dataframe with 10 countires that have highest number of tests per million people.**
###Code
highest_tests_df = combined_df.sort_values(by = ['tests_per_million'], ascending = False).head(10)
highest_tests_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Create a dataframe with 10 countires that have highest number of positive cases per million people.**
###Code
highest_cases_df = combined_df.sort_values(by = ['cases_per_million'], ascending = False).head(10)
highest_cases_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**Q: Create a dataframe with 10 countires that have highest number of deaths cases per million people?**
###Code
highest_deaths_df = combined_df.sort_values(by = ['total_deaths'], ascending = False).head(10)
highest_deaths_df
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**(Optional) Q: Count number of countries that feature in both the lists of "highest number of tests per million" and "highest number of cases per million".**
###Code
merged_df_cases_tests_highest = highest_tests_df.merge(highest_cases_df, on = 'location')
count = merged_df_cases_tests_highest.location.count()
print("There are {} countries that feature in both the lists of 'highest number of tests per million' and 'highest number of cases per million'".format(int(count)))
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____
###Markdown
**(Optional) Q: Count number of countries that feature in both the lists "20 countries with lowest GDP per capita" and "20 countries with the lowest number of hospital beds per thousand population". Only consider countries with a population higher than 10 million while creating the list.**
###Code
lowest_gdp_per_capita_20_df = countries_df[countries_df['population']> 10**7].sort_values(by = ['gdp_per_capita']).head(20)
lowest_gdp_per_capita_20_df
lowest_beds_20_df = countries_df[countries_df['population']> 10**7].sort_values(by = ['hospital_beds_per_thousand']).head(20)
lowest_beds_20_df
merged_df_gdp_per_capita_beds_20 = lowest_gdp_per_capita_20_df.merge(lowest_beds_20_df, on ='location')
count = merged_df_gdp_per_capita_beds_20.location.count()
print("There are {} countries that feature in both the lists 20 countries with lowest GDP per capita and 20 countries with the lowest number of hospital beds per thousand population. ".format(int(count)))
jovian.commit(project='pandas-practice-assignment', environment=None)
###Output
_____no_output_____ |
notebooks/stock_prediction_notebook.ipynb | ###Markdown
Project Description Investment firms, hedge funds and even individuals have been using financial models to better understand market behavior and make profitable investments and trades. A wealth of information is available in the form of historical stock prices and company performance data, suitable for machine learning algorithms to process.For this project, the task is to build a stock price predictor that takes daily trading data over a certain date range as input, and outputs projected estimates for given query dates.The inputs will contain multiple metrics, such as opening price (Open), highest price the stock traded at (High), how many stocks were traded (Volume) and closing price adjusted for stock splits and dividends (Adjusted Close); we are only predicting the Adjusted Close price.The project will use a simple script.1. Training Script: Does the Model training and saves the model, it also returns the error rate for the predicted days 2. Prediction script: Takes the saved model and forecast the price of the stocks provided NB:For you to forecast a given stock, need to have trained a model for that specific stock
###Code
#from urllib.parse import urlencode
#from pandas_datareader import data
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from datetime import date
from datetime import datetime
from datetime import timedelta
from tsfresh import extract_features
from tsfresh import select_features
from tsfresh.utilities.dataframe_functions import impute
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
from tsfresh.transformers import RelevantFeatureAugmenter
import plotly.io as pio
from dateutil.relativedelta import relativedelta, MO
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from prophet import Prophet
from pandas_datareader import data
import statsmodels.api as sm
###Output
_____no_output_____
###Markdown
Load DataStart by loading data using an API from the yahoo site.We are only taking a sample of the stock for the puopose of model training and tuning
###Code
def load_data(symbols, start_date, end_date):
"""
INPUT:
tickers : list containing the tickers of the stocks whose prices will be predicted
start_date : initial date to gather data
end_data : final date to gather data
OUTPUT:
prices_base : dataframe containing the adjusted closing price for the stocks
on the desired time frame
"""
df = data.DataReader(
symbols,
'yahoo',
start_date,
end_date)
df = pd.DataFrame(df)
df_base = df['Adj Close']
try:
df_prices = df_base.stack()
df_prices = pd.DataFrame(df_prices)
df_prices.columns = ['y']
except:
df = pd.DataFrame(df_base)
df['Symbols'] = symbols
df.rename(columns= {'Adj Close':'y'},inplace = True)
df_prices = df
#print(df_prices)
df_prices.reset_index(inplace=True)
df_prices = df_prices.sort_values(by = ['Symbols','Date'])
df_prices.rename(columns = {'Date':'ds'},inplace = True)
return df_prices
df = load_data(['GOOGL','AAPL'],'2019-05-01','2022-01-01')
###Output
_____no_output_____
###Markdown
FeaturesCreate time features that will be used as inputs to the model.Time features are good in timeseries because.1. You can generate the features even for the future dates.2. Most of the time series are seasonal and therefore time features are able to capture such aspects of the response variableNB: Will create as many as we can and keep only thoes that will be siggnificant for the model
###Code
def create_time_features(df):
df['dayofweek'] = df['ds'].dt.dayofweek
df['quarter'] = df['ds'].dt.quarter
df['month'] = df['ds'].dt.month
df['year'] = df['ds'].dt.year
df['dayofyear'] = df['ds'].dt.dayofyear
df['sin_day'] = np.sin(df['dayofyear'])
df['cos_day'] = np.cos(df['dayofyear'])
df['dayofmonth'] = df['ds'].dt.day
df['weekofyear'] = df['ds'].dt.weekofyear
df=df.sort_values('ds')
return df
df = create_time_features(df)
###Output
/Users/dgitahi/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:11: FutureWarning:
Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.
###Markdown
Exploratory Data Analysis
###Code
df.head()
df_viz
df_viz = df.set_index('ds')
df_viz= df_viz[['Symbols','y']]
for symbol in df.Symbols.unique():
df_ = df_viz[df_viz.Symbols==symbol]
print(symbol)
df_.plot(kind = 'line',figsize=(15, 6))
plt.show()
# df_ = df[df.Symbols==symbol]
# df_.sort_values(by = 'ds',inplace=True)
# fig = go.Figure(layout={'width' :1000,'height':500})
# fig.add_trace(go.Scatter(x=df_.ds,y=df_.y,
# mode='lines+markers',
# name='Price'))
# # fig.add_trace(go.Scatter(x=df.ds,y=df.yhat_lower,
# # mode='lines+markers',
# # name='lower_boundary'))
# # fig.add_trace(go.Scatter(x=df.ds,y=df.yhat_upper,
# # mode='lines+markers',
# # name='upper_boundary'))
# fig.update_layout(title = symbol,
# yaxis_title = "Price")
# fig.show()
#fig.update_yaxes(range=[10000, 800000])
###Output
AAPL
###Markdown
From the above tread there is a change i trend from the Year 2020.Will therefor confine the trainig data from year 2020 going forward.
###Code
df_
###Output
_____no_output_____
###Markdown
Seasonality
###Code
df_= pd.DataFrame(df_)
decomposition = sm.tsa.seasonal_decompose(df_, model='additive',freq =20)
from pylab import rcParams
rcParams['figure.figsize'] = 11, 9
for symbol in df.Symbols.unique():
print(symbol)
df_ = df_viz[df_viz.Symbols==symbol]
df_ = df_[['y']]
decomposition = sm.tsa.seasonal_decompose(df_, model='additive',freq=10)
fig = decomposition.plot()
plt.show()
###Output
AAPL
###Markdown
There is a strong seasonal componentThe stocks also show a increasing trend, therefore the series is not stationary. If we are to use parametric method we need to detrend the series, so that we can fit the stationary model Model TrainingWe tested 2 Models:1. Facebook Prophet: The model was good especially capturing the seasonality part of the series, though it was not able to adjust to quick changes on the trend therefore leading to high errors in such instances 2. Randomforest Regressor. It was able to capture the pattern especially when we added the time features. The out of box model with just a sligt increase of the number of trees from 100 to 120, was able to meet the set target of about 5% errror rate.NB We therefore use the RandomForest regressor as the final model.
###Code
### Fit a prophet model
df_train = df[df.Symbols=='BAC']
def model_build():
model= Prophet(seasonality_mode='additive')
return model
model = model_build()
def split_data(test_size, df):
"""
Split data into training and testing sets
INPUT:
test_size - size of testing data in ratio (default = 0.2)
df - cleaned and processed dataframe
OUTPUT:
train - training data set
test - testing data set
"""
# test_size = test_size
# training_size = 1 - test_size
# test_num = int(test_size * len(df))
# train_num = int(training_size * len(df))
train_size = len(df)-test_size
train = df[:train_size].drop(columns= ['Symbols'])
test = df[train_size:].drop(columns= ['Symbols'])
return train, test
train, test =split_data(30,df_train)
#
model.fit(train)
df_pred = model.predict(test)
def evalute_model(test):
df_pred = model.predict(test)
df_pred =pd.merge(df_pred,test,on='ds',how = 'inner')
df_pred = df_pred[['ds','yhat','y']]
mape = abs(df_pred['yhat']-df_pred['y'])/df_pred['y']*100
df_pred['mean_absolute_error'] = mape
avg_mape = round(df_pred.mean_absolute_error.mean())
#print('mean error for the period {}%'.format(avg_mape))
return df_pred,avg_mape
#df_pred,avg_mape = evalute_model(test)
df = load_data(['GOOGL','AAPL','BAC','ORCL','MSFT'],'2019-05-01','2022-01-01')
df = create_time_features(df)
error = []
symbols = df.Symbols.unique()
for symbol in symbols:
df_train = df[df.Symbols==symbol]
model = model_build()
train, test =split_data(7,df_train)
model.fit(train)
df_pred = model.predict(test)
df_pred,avg_mape = evalute_model(test)
error.append(avg_mape)
pd.DataFrame({'Symbol':symbols,'Error':error})
###Output
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
###Markdown
ADDING TIME FEATURES TO THE MODEL
###Code
def model_build():
model = Prophet(seasonality_mode='additive')
model.add_regressor('dayofweek')
#model.add_regressor('quarter')
#model.add_regressor('month')
model.add_regressor('year')
#model.add_regressor('dayofyear')
model.add_regressor('sin_day')
model.add_regressor('cos_day')
model.add_regressor('weekofyear')
return model
error = []
symbols = df.Symbols.unique()
for symbol in symbols:
df_train = df[df.Symbols==symbol]
model = model_build()
train, test =split_data(7,df_train)
model.fit(train)
df_pred = model.predict(test)
df_pred,avg_mape = evalute_model(test)
error.append(avg_mape)
pd.DataFrame({'Symbol':symbols,'Error':error})
df
###Output
_____no_output_____
###Markdown
iterating on the Change point Prior and and Seasonality Prior
###Code
cutoffs = pd.to_datetime(['2021-08-01', '2021-10-01','2021-11-01'])
symbol ='ORCL'
df_train = df[df.Symbols==symbol]
df_train = df.drop(columns='Symbols')
import itertools
from prophet.diagnostics import performance_metrics
from prophet.diagnostics import cross_validation
param_grid = {
'changepoint_prior_scale': [0.001, 0.01,0.05],
'seasonality_prior_scale':[0.01,0.1,0.5,1,5 ,10],
'seasonality_mode':['additive', 'multiplicative']
}
# Generate all combinations of parameters
all_params = [dict(zip(param_grid.keys(), v)) for v in itertools.product(*param_grid.values())]
mapes = [] # Store the RMSEs for each params here
# Use cross validation to evaluate all parameters
for params in all_params:
m = Prophet(**params)
#m.add_seasonality(name='weekly',period= 7,fourier_order= 5,prior_scale = 0.5)
m.fit(df_train) # Fit model with given params
df_cv = cross_validation(m, cutoffs=cutoffs, horizon='30 days', parallel="processes")
df_p = performance_metrics(df_cv, rolling_window=1)
mapes.append(df_p['mape'].values[0])
# Find the best parameters
tuning_results = pd.DataFrame(all_params)
tuning_results['mapes'] = mapes
print(tuning_results)
best_params = all_params[np.argmin(mapes)]
print(best_params)
def model_build():
model = Prophet(seasonality_mode='additive',changepoint_prior_scale=0.001, seasonality_prior_scale= 0.01)
model.add_regressor('dayofweek')
model.add_regressor('quarter')
model.add_regressor('month')
model.add_regressor('year')
model.add_regressor('dayofyear')
model.add_regressor('sin_day')
model.add_regressor('cos_day')
#model.add_regressor('weekofyear')
return model
error = []
symbols = df.Symbols.unique()
for symbol in symbols:
df_train = df[df.Symbols==symbol]
model = model_build()
train, test =split_data(30,df_train)
model.fit(train)
df_pred = model.predict(test)
df_pred,avg_mape = evalute_model(test)
error.append(avg_mape)
pd.DataFrame({'Symbol':symbols,'Error':error})
###Output
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
INFO:prophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
###Markdown
Model 2
###Code
def load_data(start_date,end_date,symbols):
"""the functions read data from the yahoo website.
and returns a dataframe
Input: start date: date format
end date : date format
ticker: name of the stock: string
Output: df_prices: datafame that has the prices"""
df = data.DataReader(symbols,'yahoo',start_date,end_date)
df = pd.DataFrame(df)
df_base = df['Adj Close']
df_base = df_base.stack()
df_prices = pd.DataFrame(df_base)
df_prices.columns = ['y']
#print(df_prices)
df_prices.reset_index(inplace=True)
df_prices = df_prices.sort_values(by = ['Symbols','Date'])
df_prices.rename(columns = {'Date':'ds'},inplace = True)
return df_prices
###load data
df = load_data('2019-05-01','2022-01-01',['GOOGL'])
df.head()
df.index.isocalendar().week
###time features
df = create_time_features(df)
df_train = df[df.Symbols=='GOOGL']
def split_data(test_size, df):
"""
Split data into training and testing sets
INPUT:
test_size - size of testing data in ratio (default = 0.2)
df - cleaned and processed dataframe
OUTPUT:
train - training data set
test - testing data set
"""
# test_size = test_size
# training_size = 1 - test_size
# test_num = int(test_size * len(df))
# train_num = int(training_size * len(df))
df =df.set_index('ds')
#df.drop(columns = ['year','month','quarter'],inplace = True)
train_size = len(df)-test_size
train = df[:train_size].drop(columns= ['Symbols'])
test = df[train_size:].drop(columns= ['Symbols'])
X_train=train.drop(columns='y')
X_test =test.drop(columns='y')
y_train = train['y']
y_test = test['y']
return X_train,y_train,X_test,y_test
X_train,y_train,X_test,y_test =split_data_mdl2(7,df_train)
from sklearn.ensemble import RandomForestRegressor
def build_model():
pipeline = Pipeline([
('clf', RandomForestRegressor(n_estimators=120))
])
return pipeline
model = build_model()
import pickle
# def save_model():
# filename = '/Users/dgitahi/Documents/nano degree/final_project/models/model.pkl'
# pickle.dump(model, open(filename, 'wb'))
def save_model(model, model_filepath):
with open(model_filepath, 'wb') as file:
pickle.dump(model, file)
X_train
#fit model
model.fit(X_train,y_train)
def evaluate_model(model,X_test,Y_test):
Y_pred = model.predict(X_test)
predicted = pd.DataFrame(Y_test)
predicted['y_Forecasted'] = Y_pred
mape = abs(predicted['y']-predicted['y_Forecasted'])/predicted['y']*100
predicted['mape'] = mape
mean_mape = predicted.mape.mean()
mse= mean_squared_error(Y_test,Y_pred)
return predicted,mean_mape
#return mse,mape,predicted
evaluate_model(model,X_test,y_test)
model
modeltrn = {}
df.head()
symbols
for symbol in symbols:
print(symbol)
symbols = df.Symbols.unique()
trained_model = {}
error = []
predicted_df = []
for symbol in symbols:
print(symbol)
df_train = df[df.Symbols==symbol]
#print(df_train)
model = build_model()
trained_model[symbol] = model
X_train,y_train,X_test,y_test = split_data(7, df_train)
#print(X_train)
model.fit(X_train,y_train)
print('done')
predicted,mean_mape = evaluate_model(model,X_test,y_test)
predicted['Symbol'] = symbol
error.append(mean_mape)
predicted_df.append(predicted)
error_df = pd.DataFrame({'Symbol':symbols,'Error':error})
predicted_df = pd.concat(predicted_df)
print(error_df)
print(predicted_df)
print('saving the model')
save_model(trained_model,"/Users/dgitahi/Documents/nano degree/final_project/models/final_model.pkl")
print('Trained model saved!')
symbols
#load model
def load_model():
filename = "/Users/dgitahi/Documents/nano degree/final_project/models/final_model.pkl"
loaded_model = pickle.load(open(filename, 'rb'))
return loaded_model
models = load_model()
models['BAC']
def predict (symbol_list,models,start_date,end_date):
forecasted_df = []
for symbol in symbol_list:
df = pd.DataFrame(pd.date_range(start_date,end_date,freq='d'))
#print(df)
df.columns = ['ds']
df = create_time_features(df)
features = df.drop(columns= 'ds')
model = models[symbol]
forecasted = model.predict(features)
df['forecasted_price'] = forecasted
df['Symbol']= symbol
df = df[['ds','Symbol','forecasted_price']]
forecasted_df.append(df)
forecasted_df = pd.concat(forecasted_df)
return forecasted_df
predict(['AAPL',],models,'2022-02-27','2022-03-10')
###Output
/Users/dgitahi/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:11: FutureWarning:
Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.
###Markdown
###Code
error = []
predicted_df = []
symbols = df.Symbols.unique()
for symbol in symbols:
df_train = df[df.Symbols==symbol]
model = build_model()
X_train,y_train,X_test,y_test = split_data_mdl2(7, df_train)
model.fit(X_train,y_train)
predicted,mean_mape = evaluate_model(model,X_test,y_test)
error.append(mean_mape)
predicted_df.append(predicted)
predicted['Symbol'] = symbol
error_df = pd.DataFrame({'Symbol':symbols,'Error':error})
predicted_df = pd.concat(predicted_df)
error_df
#predicted_df
###Output
_____no_output_____ |
SVMClassification.ipynb | ###Markdown
Using Support Vector Machines (SVMs) to Classify ImagesA very common problem in machine learning is recognizing hand-written digits. The image of the numerals is commonly used by data scientists and machine learning experts to train supervised learning algorithms that specialize in decoding human handwriting. This is a classic problem that is often used in exercises and documentation, as well as by algorithm developers to benchmark their new algorithms alongside existing ones. In this exercise, you will use a Support Vector Machine to classify hand-written digits. Step 1.The sklearn package provides data and documentation for analyzing this type of problem.The `sklearn` package includes some built-in datasets that can be imported. One of these is a collection of low-resolution images (8 x 8 pixels) representing hand-written digits. Let's import the dataset. The code cell below:* Imports the `datasets` submodule from the sklearn package (```from sklearn import datasets```)* Next calls the ```load_digits()``` function in the `datasets` module, and assigns the result to the variable ```digits```.* Using the built-in function type, it prints the type of the ```digits``` variable.
###Code
from sklearn import datasets
digits = datasets.load_digits()
print(type(digits))
###Output
<class 'sklearn.utils.Bunch'>
###Markdown
Step 2.You should see that ```digits``` is an object of type 'sklearn.utils.Bunch', which is not something we have seen before, but it is basically a new type of container that is something like a Python dictionary. (One of the ways it differs from a dictionary is that elements contained in the Bunch can be accessed using the dot operator ```.``` rather than the square-bracket indexing supported by dictionaries. We'll see this feature below.)Because a Bunch is similar to a dictionary, it can be queried to list its keys. The code cell below prints out the result of ```digits.keys()```. Execute the code cell below and examine the output.
###Code
print(digits.keys())
###Output
dict_keys(['data', 'target', 'target_names', 'images', 'DESCR'])
###Markdown
Step 3.You should notice that ```digits``` contains multiple elements, one of which is ```images```, which we can access via the expression ```digits.images```, that is, using the dot operator to get the images out of the digits Bunch. The code cell below prints the types of the items ```images``` and ```target``` contained in ```digits```.
###Code
print(type(digits.images))
print(type(digits.target))
###Output
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
###Markdown
Step 4.You should see that both ```images``` and ```target``` are numpy.ndarrays (which we usually just call "numpy arrays"). Since they are arrays, we can query their shape. In the code cell below, print out the shape of both the ```images``` and ```target``` arrays.
###Code
print(digits.images.shape)
print(digits.target.shape)
###Output
(1797, 8, 8)
(1797,)
###Markdown
Step 5.You should notice that ```images``` is a three-dimensional array of shape (1797, 8, 8) and that ```target``` is a one-dimensional array of shape (1797,). Each array contains 1797 elements in it, since these are 1797 examples of hand-written digits in this dataset. Let's have a look at the data in more detail.In the code cell below:* print the value of the first image in the array (```digits.images[0]```)* print the value of the first target
###Code
print(digits.images[0])
print(digits.target[0])
###Output
[[ 0. 0. 5. 13. 9. 1. 0. 0.]
[ 0. 0. 13. 15. 10. 15. 5. 0.]
[ 0. 3. 15. 2. 0. 11. 8. 0.]
[ 0. 4. 12. 0. 0. 8. 8. 0.]
[ 0. 5. 8. 0. 0. 9. 8. 0.]
[ 0. 4. 11. 0. 1. 12. 7. 0.]
[ 0. 2. 14. 5. 10. 12. 0. 0.]
[ 0. 0. 6. 13. 10. 0. 0. 0.]]
0
###Markdown
Step 6.Because the images array has shape (1797, 8, 8), the first entry in that array (```digits.images[0]```) is an 8 x 8 subarray. This array encodes the grayscale value of the first hand-written image in the dataset, i.e., each entry in the 8 x 8 array encodes the intensity (darkness) of the corresponding pixel. From the output above, the value of ```digits.target[0]``` is reported to be ```0```. This means that the first image in the dataset is an example of the digit 0. It's a bit difficult to see that by staring at the numbers in the 8 x 8 image array, but maybe things will make more sense if we try to visualize the image.Execute the code cell below, which uses the seaborn heatmap function to display the image. Hopefully that looks something like a zero to you.
###Code
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.heatmap(digits.images[0], cmap=plt.cm.Greys)
###Output
_____no_output_____
###Markdown
Step 7.The ```images``` and ```target``` entries are in registry with each other, e.g., ```target[0]``` indicates the true value of the data encoded in ```images[0]```, ```target[1]``` indicates the true value of the data encoded in ```images[1]```, etc. There are 10 possible digits (0-9), but there are 1797 images of handwritten digits, so there are many different examples of each digit in the dataset. The purpose of the classifier that we are going to build is to learn from these many examples, so that it can reliably identify a new handwritten digit that it has not been trained on.In the code cell below, try out a few calls of your own using the ```sns.heatmap``` function to display some other images in the dataset.* print the value of target number 314* plot a heatmap of image number 314If you want to peek at a few more, feel free to examine other digits in the dataset by selecting different image indexes.
###Code
print(digits.target[314])
sns.heatmap(digits.images[314], cmap=plt.cm.Greys)
###Output
6
###Markdown
Step 8.The ```digits``` Bunch also contains an item called ```data```, which is also a numpy array. In the code cell below, print out the shape of the data item.
###Code
print(digits.data.shape)
import matplotlib.pyplot as plt
###Output
(1797, 64)
###Markdown
Step 9.You should see that ```digits.data``` has shape (1797, 64). This reflects the fact that for each of the 1797 hand-written images in the dataset, the 8 x 8 image array has been "flattened" into a one-dimensional data array of length 64, by concatenating each of the 8 rows one after the other. (Within numpy, an n-dimensional array can be flattened into a one-dimensional array using the function np.ravel.) A flattening like this is convenient to be able to feed data into a machine learning algorithm, since we can use the same algorithm for datasets of different dimensions. No information is lost by this flattening procedure, except for the fact that if we were to plot out the flattened array, we probably would not be able to recognize what digit is encoded. In the code cell below, make a simple line plot using ```plt.plot``` of the one-dimensional data in array digits.data[0] to see what the flattened version of the data looks like.
###Code
plt.plot(digits.data[0])
###Output
_____no_output_____
###Markdown
Step 10.We've gone through multiple steps of interrogating the digits dataset, since this is typical in the process of developing a machine learning analysis, where one needs to understand the structure of the data and how the different data items relate to each other. We're going to carry out a supervised learning classification of the data.In this classification process, we are going to train a classifier on labeled examples, where the labels are the known values in the target array. For example, the classifier will be instructed that the data in ```digits.data[0]``` corresponds to the digit 0, the data in ```digits.data[314]``` corresponds to the digit 6, etc.The material in the sklearn tutorial on [Learning and predicting](https://scikit-learn.org/stable/tutorial/basic/tutorial.htmllearning-and-predicting) describes this next phase of the process, which we will incorporate into the code cell below.For now, just execute the code cell below and examine each step:* the first line imports the `svm` classifier from `sklearn`* the second line creates an object of type SVC (Support Vector Classifier) and assigns it to the variable ```svm_model```. Gamma and C are hyperparameters that can be specified by the user before training. They define the classification boundary between classified and missclassified data points. We have selected some sample values for this exercise but in practice there are heuristics and cross-validation procedures to identify good values.* Rather than splitting the data set into training and test sets using the `train_test_split` function, we are going to do something simple and remove the last image from the data set to use as a test image. You will see this in the third line. It fits (trains) the data in all of the images and targets except for the last (```digits.data[:-1]```, which stops one item short of the last entry)
###Code
from sklearn import svm
svm_model = svm.SVC(gamma=0.001, C=100.)
svm_model.fit(digits.data[:-1], digits.target[:-1])
###Output
_____no_output_____
###Markdown
Step 11.Having fit the classifier on all but the last image, we can now try to predict the digit associated with the last image, by calling the ```predict``` method on our classifier ```svm_model```. Execute the code cell below and examine the output.
###Code
svm_model.predict(digits.data[-1:])
###Output
_____no_output_____
###Markdown
Step 12.This tells us that our classifier has predicted the last digit to be 8, based on everything it learned in training on the previous 1796 images.The code cell below makes a heatmap plot of the last image in the dataset. Does it look like the number 8? The sklearn tutorial notes: "As you can see, it is a challenging task: after all, the images are of poor resolution. Do you agree with the classifier?"
###Code
sns.heatmap(digits.images[-1], cmap=plt.cm.Greys)
###Output
_____no_output_____
###Markdown
Step 13.The last digit in the dataset was *predicted* to be 8, based on the trained classifier. In the code cell below, write an expression that assigns to the variable true_last_digit the true value of the last digit in the dataset, by extracting the relevant value out of the digits object.
###Code
true_last_digit = digits.target[-1]
###Output
_____no_output_____
###Markdown
Self-CheckRun the cell below to test the correctness of your code above.
###Code
# Run this self-test cell to check your code; do not add code or delete code in this cell
from jn import testDigit
try:
print(testDigit(true_last_digit))
except Exception as e:
print("Error!\n" + str(e))
###Output
Correct!
###Markdown
Step 14.In the example above, we trained the classifier using all but one example, and then tried to predict the digit for that last remaining example. That is just one of many possible workflows, using a particular split of training and testing data. For example, we could instead train on all but the last 100 examples, and then predict the last 100 examples using that model. In the code cell below, copy the ```fit``` and ```predict``` functions found in Step 10 and Step 11 above, and modify them in order to fit the ```svm_model``` classifier on all but the last 100 examples, and then predict the digits for the last 100 examples. Save your result to the variable `predict_last_100`, and print out the value of that variable so that you can observe the set of predictions made for this test dataset.
###Code
svm_model.fit(digits.data[:-100], digits.target[:-100])
svm_model.predict(digits.data[-100:])
###Output
_____no_output_____
###Markdown
Self-CheckRun the cell below to test the correctness of your code above.
###Code
# Run this self-test cell to check your code; do not add code or delete code in this cell
from jn import testPredict100
try:
print(testPredict100(digits, predict_last_100))
except Exception as e:
print("Error!\n" + str(e))
###Output
Error!
name 'predict_last_100' is not defined
|
RL Book Exercises/Exercise_2_11.ipynb | ###Markdown
Exercise 2.11Make a figure analogous to Figure 2.6 for the nonstationarycase outlined in Exercise 2.5. Include the constant-step-size epsilon-greedy algorithm withalpha= 0.1. Use runs of 200,000 steps and, as a performance measure for each algorithm andparameter setting, use the average reward over the last 100,000 steps. SummaryMake a graph with these bandits:- Sample average ε-greedy;- Constant step size ε-greedy with alpha = 0.1;- Upper Bound Confidence (UBC);- Gradient bandit;- ε-greedy with optimistic initialization (e.g. q*(a) = 5 for all a) with alpha = 0.1; ImplementationI used NumPy arrays for the bandits, so each bandit has it's own Q(a), I did this because then I would only need one object and calculating stuff with arrays is quite faster than having to loop over all the Bandit objects and change their values seperatly.
###Code
# Imports and initialization
import numpy as np
import matplotlib.pyplot as plt
k = 10 # Number of arms (actions)
m = 200 # Number of bandits (agents)
steps = 20000 # The number of steps for the simulation
true_R = np.zeros(k) # The q* (the actual values of the rewars)
parameters = [2**i for i in range(-7, 3)] # The parameters to try
# Print out the variables
print("k:", k)
print("m:", m)
print("steps:", steps)
print("true_R:", true_R)
print("parameters:", parameters)
class Bandit(object):
"""
The base bandit class
"""
def __init__(self, m, k, epsilon=0.1, alpha=None, init_Q=None):
# Initialize all the variables
assert isinstance(alpha, (int, float)) or callable(alpha) or alpha is None, f"{alpha} is not an int, float, function or None"
assert isinstance(epsilon, (int, float)), f"{epsilon} is not an int or float"
self.epsilon = epsilon
if epsilon > 1:
self.epsilon = 1
elif epsilon < 0:
self.epsilon = 0
self.k = k # Num actions
self.m = m # Num bandits
self.N = np.zeros((self.m, self.k)) # How many times a certain action was chosen
self.Q = np.zeros((self.m, self.k)) # What we think is the current value of each action
if init_Q is not None:
for row in range(m):
self.Q[row, :] = init_Q
if isinstance(alpha, (int, float)):
self.alpha = lambda i, a: alpha
elif callable(alpha):
self.alpha = alpha
elif alpha is None:
self.alpha = lambda i, a: 1 / self.N[i, a]
def _choose_action(self):
pass
def step(self):
pass
class EpsilonBandit(Bandit):
"""
The bandit for ε-greedy algorithms
"""
def __init__(self, m, k, epsilon=0.1, alpha=None, init_Q=None):
# Initialize
super().__init__(m, k, epsilon=epsilon, alpha=alpha, init_Q=init_Q)
def _choose_action(self) -> int:
"""
Choose an action
if some random number < epsilon --> choose a random action
else --> choose the 'best' action (according to our Q(a))
"""
A = [np.argmax(row) if np.random.binomial(1, self.epsilon) == 0
else np.random.randint(self.k) for row in self.Q[:, ]]
return A
def step(self, t) -> int:
# Choose the actions and return the reward
A = self._choose_action()
R = np.zeros((self.m))
for i, a in enumerate(A):
R[i] += true_R[a]
self.N[i, a] += 1
self.Q[i, a] += self.alpha(i, a) * (true_R[a] - self.Q[i, a])
return R
class UBCBandit(Bandit):
"""
The bandit for Upper Bound Confidence algorithms
"""
def __init__(self, m, k, c=0.1, epsilon=0.1, alpha=None, init_Q=None):
# Initialize
assert isinstance(c, (int, float)), f"{c} is not an int or float"
self.c = c
super().__init__(m, k, epsilon=epsilon, alpha=alpha, init_Q=init_Q)
def _choose_action(self, t) -> int:
"""
Choose an action according to
argmax( Q(a) + c * sqrt(ln(t) / N(a)) )
"""
A = [np.argmax(row + self.c * np.sqrt(np.log(t + 1) / (n + 1)))
if np.random.binomial(1, self.epsilon) == 0
else np.random.randint(self.k) for row, n in zip(self.Q[:, ], self.N[:, ])]
return A
def step(self, t) -> int:
# Choose the actions and return the reward
A = self._choose_action(t)
R = np.zeros((self.m))
for i, a in enumerate(A):
R[i] += true_R[a]
self.N[i, a] += 1
self.Q[i, a] += self.alpha(i, a) * (true_R[a] - self.Q[i, a])
return R
class GradientBandit(object):
def __init__(self, m, k, alpha=None):
# Initialize
assert isinstance(alpha, (int, float)) or callable(alpha) or alpha is None, f"{alpha} is not an int, float, function or None"
self.m = m
self.k = k
self.H = np.zeros((m, k))
if isinstance(alpha, (int, float)):
self.alpha = lambda i, a: alpha
elif callable(alpha):
self.alpha = alpha
elif alpha is None:
self.alpha = lambda i, a: 1 / self.N[i, a]
def _choose_action(self) -> int:
"""
Choose an action according to
Calculate for all action a in A:
e^a / sum(e^A)
Choose a random action with those probabilities
"""
A_prob = [np.exp(row) / np.sum(np.exp(row)) for row in self.H[:, ]]
A = [np.random.choice(np.arange(self.k), p=p) for p in A_prob]
return A, A_prob
def step(self, t) -> int:
# Choose the actions and return the reward
A, A_prob = self._choose_action()
R = [true_R[a] for a in A]
for i, a in enumerate(A):
self.H[i, :] += self.alpha(i, a) * R[i] * (GradientBandit.one_hot(a, self.k) - A_prob[i])
return R
@staticmethod
def one_hot(position, length):
"""
Returns a length array where position is 1 and the rest is 0
"""
oh = np.zeros(length)
oh[position] = 1
return oh
eps_mean_r = []
ubc_mean_r = []
grad_mean_r = []
# Run for all parameters
for param in parameters:
# Create a list of Epsilon Bandit, UBC Bandit and Gradient Bandit
bandits = [
EpsilonBandit(m, k, epsilon=param, alpha=0.1), # ε = param
UBCBandit(m, k, c=param, epsilon=0.1, alpha=0.1), # c = param
GradientBandit(m, k, alpha=param) # α = param
]
# Generate a few lists
x = [i for i in range(steps)]
r = [np.zeros(steps) for _ in range(len(bandits))]
# Run the simulation with the current param
for t in range(steps):
for i, bandit in enumerate(bandits):
R = bandit.step(t)
r[i][t] = np.mean(R)
# Add a normal distribution
true_R += np.random.normal(0, 0.01, k)
print(f"Param {parameters.index(param) + 1}/{len(parameters)} Step {t + 1}/{steps}")
eps_mean_r.append(np.mean(r[0][: steps // 2]))
ubc_mean_r.append(np.mean(r[1][: steps // 2]))
grad_mean_r.append(np.mean(r[2][: steps // 2]))
# Plot the results
plt.plot(parameters, eps_mean_r, label="Epsilon")
plt.plot(parameters, ubc_mean_r, label="UBC")
plt.plot(parameters, grad_mean_r, label="Gradient")
plt.xscale('log', basex=2)
plt.title(f"RL algorithms with {m} bandits, {steps} steps")
plt.xlabel("Parameter")
plt.ylabel("Mean Reward")
plt.legend()
# Save the plot
plt.savefig("drive/MyDrive/Colab Notebooks/RL book exercises/2_11.png", dpi=300)
plt.show()
###Output
[1;30;43mStreaminguitvoer ingekort tot de laatste 5000 regels.[0m
Param 10/10 Step 15001/20000
Param 10/10 Step 15002/20000
Param 10/10 Step 15003/20000
Param 10/10 Step 15004/20000
Param 10/10 Step 15005/20000
Param 10/10 Step 15006/20000
Param 10/10 Step 15007/20000
Param 10/10 Step 15008/20000
Param 10/10 Step 15009/20000
Param 10/10 Step 15010/20000
Param 10/10 Step 15011/20000
Param 10/10 Step 15012/20000
Param 10/10 Step 15013/20000
Param 10/10 Step 15014/20000
Param 10/10 Step 15015/20000
Param 10/10 Step 15016/20000
Param 10/10 Step 15017/20000
Param 10/10 Step 15018/20000
Param 10/10 Step 15019/20000
Param 10/10 Step 15020/20000
Param 10/10 Step 15021/20000
Param 10/10 Step 15022/20000
Param 10/10 Step 15023/20000
Param 10/10 Step 15024/20000
Param 10/10 Step 15025/20000
Param 10/10 Step 15026/20000
Param 10/10 Step 15027/20000
Param 10/10 Step 15028/20000
Param 10/10 Step 15029/20000
Param 10/10 Step 15030/20000
Param 10/10 Step 15031/20000
Param 10/10 Step 15032/20000
Param 10/10 Step 15033/20000
Param 10/10 Step 15034/20000
Param 10/10 Step 15035/20000
Param 10/10 Step 15036/20000
Param 10/10 Step 15037/20000
Param 10/10 Step 15038/20000
Param 10/10 Step 15039/20000
Param 10/10 Step 15040/20000
Param 10/10 Step 15041/20000
Param 10/10 Step 15042/20000
Param 10/10 Step 15043/20000
Param 10/10 Step 15044/20000
Param 10/10 Step 15045/20000
Param 10/10 Step 15046/20000
Param 10/10 Step 15047/20000
Param 10/10 Step 15048/20000
Param 10/10 Step 15049/20000
Param 10/10 Step 15050/20000
Param 10/10 Step 15051/20000
Param 10/10 Step 15052/20000
Param 10/10 Step 15053/20000
Param 10/10 Step 15054/20000
Param 10/10 Step 15055/20000
Param 10/10 Step 15056/20000
Param 10/10 Step 15057/20000
Param 10/10 Step 15058/20000
Param 10/10 Step 15059/20000
Param 10/10 Step 15060/20000
Param 10/10 Step 15061/20000
Param 10/10 Step 15062/20000
Param 10/10 Step 15063/20000
Param 10/10 Step 15064/20000
Param 10/10 Step 15065/20000
Param 10/10 Step 15066/20000
Param 10/10 Step 15067/20000
Param 10/10 Step 15068/20000
Param 10/10 Step 15069/20000
Param 10/10 Step 15070/20000
Param 10/10 Step 15071/20000
Param 10/10 Step 15072/20000
Param 10/10 Step 15073/20000
Param 10/10 Step 15074/20000
Param 10/10 Step 15075/20000
Param 10/10 Step 15076/20000
Param 10/10 Step 15077/20000
Param 10/10 Step 15078/20000
Param 10/10 Step 15079/20000
Param 10/10 Step 15080/20000
Param 10/10 Step 15081/20000
Param 10/10 Step 15082/20000
Param 10/10 Step 15083/20000
Param 10/10 Step 15084/20000
Param 10/10 Step 15085/20000
Param 10/10 Step 15086/20000
Param 10/10 Step 15087/20000
Param 10/10 Step 15088/20000
Param 10/10 Step 15089/20000
Param 10/10 Step 15090/20000
Param 10/10 Step 15091/20000
Param 10/10 Step 15092/20000
Param 10/10 Step 15093/20000
Param 10/10 Step 15094/20000
Param 10/10 Step 15095/20000
Param 10/10 Step 15096/20000
Param 10/10 Step 15097/20000
Param 10/10 Step 15098/20000
Param 10/10 Step 15099/20000
Param 10/10 Step 15100/20000
Param 10/10 Step 15101/20000
Param 10/10 Step 15102/20000
Param 10/10 Step 15103/20000
Param 10/10 Step 15104/20000
Param 10/10 Step 15105/20000
Param 10/10 Step 15106/20000
Param 10/10 Step 15107/20000
Param 10/10 Step 15108/20000
Param 10/10 Step 15109/20000
Param 10/10 Step 15110/20000
Param 10/10 Step 15111/20000
Param 10/10 Step 15112/20000
Param 10/10 Step 15113/20000
Param 10/10 Step 15114/20000
Param 10/10 Step 15115/20000
Param 10/10 Step 15116/20000
Param 10/10 Step 15117/20000
Param 10/10 Step 15118/20000
Param 10/10 Step 15119/20000
Param 10/10 Step 15120/20000
Param 10/10 Step 15121/20000
Param 10/10 Step 15122/20000
Param 10/10 Step 15123/20000
Param 10/10 Step 15124/20000
Param 10/10 Step 15125/20000
Param 10/10 Step 15126/20000
Param 10/10 Step 15127/20000
Param 10/10 Step 15128/20000
Param 10/10 Step 15129/20000
Param 10/10 Step 15130/20000
Param 10/10 Step 15131/20000
Param 10/10 Step 15132/20000
Param 10/10 Step 15133/20000
Param 10/10 Step 15134/20000
Param 10/10 Step 15135/20000
Param 10/10 Step 15136/20000
Param 10/10 Step 15137/20000
Param 10/10 Step 15138/20000
Param 10/10 Step 15139/20000
Param 10/10 Step 15140/20000
Param 10/10 Step 15141/20000
Param 10/10 Step 15142/20000
Param 10/10 Step 15143/20000
Param 10/10 Step 15144/20000
Param 10/10 Step 15145/20000
Param 10/10 Step 15146/20000
Param 10/10 Step 15147/20000
Param 10/10 Step 15148/20000
Param 10/10 Step 15149/20000
Param 10/10 Step 15150/20000
Param 10/10 Step 15151/20000
Param 10/10 Step 15152/20000
Param 10/10 Step 15153/20000
Param 10/10 Step 15154/20000
Param 10/10 Step 15155/20000
Param 10/10 Step 15156/20000
Param 10/10 Step 15157/20000
Param 10/10 Step 15158/20000
Param 10/10 Step 15159/20000
Param 10/10 Step 15160/20000
Param 10/10 Step 15161/20000
Param 10/10 Step 15162/20000
Param 10/10 Step 15163/20000
Param 10/10 Step 15164/20000
Param 10/10 Step 15165/20000
Param 10/10 Step 15166/20000
Param 10/10 Step 15167/20000
Param 10/10 Step 15168/20000
Param 10/10 Step 15169/20000
Param 10/10 Step 15170/20000
Param 10/10 Step 15171/20000
Param 10/10 Step 15172/20000
Param 10/10 Step 15173/20000
Param 10/10 Step 15174/20000
Param 10/10 Step 15175/20000
Param 10/10 Step 15176/20000
Param 10/10 Step 15177/20000
Param 10/10 Step 15178/20000
Param 10/10 Step 15179/20000
Param 10/10 Step 15180/20000
Param 10/10 Step 15181/20000
Param 10/10 Step 15182/20000
Param 10/10 Step 15183/20000
Param 10/10 Step 15184/20000
Param 10/10 Step 15185/20000
Param 10/10 Step 15186/20000
Param 10/10 Step 15187/20000
Param 10/10 Step 15188/20000
Param 10/10 Step 15189/20000
Param 10/10 Step 15190/20000
Param 10/10 Step 15191/20000
Param 10/10 Step 15192/20000
Param 10/10 Step 15193/20000
Param 10/10 Step 15194/20000
Param 10/10 Step 15195/20000
Param 10/10 Step 15196/20000
Param 10/10 Step 15197/20000
Param 10/10 Step 15198/20000
Param 10/10 Step 15199/20000
Param 10/10 Step 15200/20000
Param 10/10 Step 15201/20000
Param 10/10 Step 15202/20000
Param 10/10 Step 15203/20000
Param 10/10 Step 15204/20000
Param 10/10 Step 15205/20000
Param 10/10 Step 15206/20000
Param 10/10 Step 15207/20000
Param 10/10 Step 15208/20000
Param 10/10 Step 15209/20000
Param 10/10 Step 15210/20000
Param 10/10 Step 15211/20000
Param 10/10 Step 15212/20000
Param 10/10 Step 15213/20000
Param 10/10 Step 15214/20000
Param 10/10 Step 15215/20000
Param 10/10 Step 15216/20000
Param 10/10 Step 15217/20000
Param 10/10 Step 15218/20000
Param 10/10 Step 15219/20000
Param 10/10 Step 15220/20000
Param 10/10 Step 15221/20000
Param 10/10 Step 15222/20000
Param 10/10 Step 15223/20000
Param 10/10 Step 15224/20000
Param 10/10 Step 15225/20000
Param 10/10 Step 15226/20000
Param 10/10 Step 15227/20000
Param 10/10 Step 15228/20000
Param 10/10 Step 15229/20000
Param 10/10 Step 15230/20000
Param 10/10 Step 15231/20000
Param 10/10 Step 15232/20000
Param 10/10 Step 15233/20000
Param 10/10 Step 15234/20000
Param 10/10 Step 15235/20000
Param 10/10 Step 15236/20000
Param 10/10 Step 15237/20000
Param 10/10 Step 15238/20000
Param 10/10 Step 15239/20000
Param 10/10 Step 15240/20000
Param 10/10 Step 15241/20000
Param 10/10 Step 15242/20000
Param 10/10 Step 15243/20000
Param 10/10 Step 15244/20000
Param 10/10 Step 15245/20000
Param 10/10 Step 15246/20000
Param 10/10 Step 15247/20000
Param 10/10 Step 15248/20000
Param 10/10 Step 15249/20000
Param 10/10 Step 15250/20000
Param 10/10 Step 15251/20000
Param 10/10 Step 15252/20000
Param 10/10 Step 15253/20000
Param 10/10 Step 15254/20000
Param 10/10 Step 15255/20000
Param 10/10 Step 15256/20000
Param 10/10 Step 15257/20000
Param 10/10 Step 15258/20000
Param 10/10 Step 15259/20000
Param 10/10 Step 15260/20000
Param 10/10 Step 15261/20000
Param 10/10 Step 15262/20000
Param 10/10 Step 15263/20000
Param 10/10 Step 15264/20000
Param 10/10 Step 15265/20000
Param 10/10 Step 15266/20000
Param 10/10 Step 15267/20000
Param 10/10 Step 15268/20000
Param 10/10 Step 15269/20000
Param 10/10 Step 15270/20000
Param 10/10 Step 15271/20000
Param 10/10 Step 15272/20000
Param 10/10 Step 15273/20000
Param 10/10 Step 15274/20000
Param 10/10 Step 15275/20000
Param 10/10 Step 15276/20000
Param 10/10 Step 15277/20000
Param 10/10 Step 15278/20000
Param 10/10 Step 15279/20000
Param 10/10 Step 15280/20000
Param 10/10 Step 15281/20000
Param 10/10 Step 15282/20000
Param 10/10 Step 15283/20000
Param 10/10 Step 15284/20000
Param 10/10 Step 15285/20000
Param 10/10 Step 15286/20000
Param 10/10 Step 15287/20000
Param 10/10 Step 15288/20000
Param 10/10 Step 15289/20000
Param 10/10 Step 15290/20000
Param 10/10 Step 15291/20000
Param 10/10 Step 15292/20000
Param 10/10 Step 15293/20000
Param 10/10 Step 15294/20000
Param 10/10 Step 15295/20000
Param 10/10 Step 15296/20000
Param 10/10 Step 15297/20000
Param 10/10 Step 15298/20000
Param 10/10 Step 15299/20000
Param 10/10 Step 15300/20000
Param 10/10 Step 15301/20000
Param 10/10 Step 15302/20000
Param 10/10 Step 15303/20000
Param 10/10 Step 15304/20000
Param 10/10 Step 15305/20000
Param 10/10 Step 15306/20000
Param 10/10 Step 15307/20000
Param 10/10 Step 15308/20000
Param 10/10 Step 15309/20000
Param 10/10 Step 15310/20000
Param 10/10 Step 15311/20000
Param 10/10 Step 15312/20000
Param 10/10 Step 15313/20000
Param 10/10 Step 15314/20000
Param 10/10 Step 15315/20000
Param 10/10 Step 15316/20000
Param 10/10 Step 15317/20000
Param 10/10 Step 15318/20000
Param 10/10 Step 15319/20000
Param 10/10 Step 15320/20000
Param 10/10 Step 15321/20000
Param 10/10 Step 15322/20000
Param 10/10 Step 15323/20000
Param 10/10 Step 15324/20000
Param 10/10 Step 15325/20000
Param 10/10 Step 15326/20000
Param 10/10 Step 15327/20000
Param 10/10 Step 15328/20000
Param 10/10 Step 15329/20000
Param 10/10 Step 15330/20000
Param 10/10 Step 15331/20000
Param 10/10 Step 15332/20000
Param 10/10 Step 15333/20000
Param 10/10 Step 15334/20000
Param 10/10 Step 15335/20000
Param 10/10 Step 15336/20000
Param 10/10 Step 15337/20000
Param 10/10 Step 15338/20000
Param 10/10 Step 15339/20000
Param 10/10 Step 15340/20000
Param 10/10 Step 15341/20000
Param 10/10 Step 15342/20000
Param 10/10 Step 15343/20000
Param 10/10 Step 15344/20000
Param 10/10 Step 15345/20000
Param 10/10 Step 15346/20000
Param 10/10 Step 15347/20000
Param 10/10 Step 15348/20000
Param 10/10 Step 15349/20000
Param 10/10 Step 15350/20000
Param 10/10 Step 15351/20000
Param 10/10 Step 15352/20000
Param 10/10 Step 15353/20000
Param 10/10 Step 15354/20000
Param 10/10 Step 15355/20000
Param 10/10 Step 15356/20000
Param 10/10 Step 15357/20000
Param 10/10 Step 15358/20000
Param 10/10 Step 15359/20000
Param 10/10 Step 15360/20000
Param 10/10 Step 15361/20000
Param 10/10 Step 15362/20000
Param 10/10 Step 15363/20000
Param 10/10 Step 15364/20000
Param 10/10 Step 15365/20000
Param 10/10 Step 15366/20000
Param 10/10 Step 15367/20000
Param 10/10 Step 15368/20000
Param 10/10 Step 15369/20000
Param 10/10 Step 15370/20000
Param 10/10 Step 15371/20000
Param 10/10 Step 15372/20000
Param 10/10 Step 15373/20000
Param 10/10 Step 15374/20000
Param 10/10 Step 15375/20000
Param 10/10 Step 15376/20000
Param 10/10 Step 15377/20000
Param 10/10 Step 15378/20000
Param 10/10 Step 15379/20000
Param 10/10 Step 15380/20000
Param 10/10 Step 15381/20000
Param 10/10 Step 15382/20000
Param 10/10 Step 15383/20000
Param 10/10 Step 15384/20000
Param 10/10 Step 15385/20000
Param 10/10 Step 15386/20000
Param 10/10 Step 15387/20000
Param 10/10 Step 15388/20000
Param 10/10 Step 15389/20000
Param 10/10 Step 15390/20000
Param 10/10 Step 15391/20000
Param 10/10 Step 15392/20000
Param 10/10 Step 15393/20000
Param 10/10 Step 15394/20000
Param 10/10 Step 15395/20000
Param 10/10 Step 15396/20000
Param 10/10 Step 15397/20000
Param 10/10 Step 15398/20000
Param 10/10 Step 15399/20000
Param 10/10 Step 15400/20000
Param 10/10 Step 15401/20000
Param 10/10 Step 15402/20000
Param 10/10 Step 15403/20000
Param 10/10 Step 15404/20000
Param 10/10 Step 15405/20000
Param 10/10 Step 15406/20000
Param 10/10 Step 15407/20000
Param 10/10 Step 15408/20000
Param 10/10 Step 15409/20000
Param 10/10 Step 15410/20000
Param 10/10 Step 15411/20000
Param 10/10 Step 15412/20000
Param 10/10 Step 15413/20000
Param 10/10 Step 15414/20000
Param 10/10 Step 15415/20000
Param 10/10 Step 15416/20000
Param 10/10 Step 15417/20000
Param 10/10 Step 15418/20000
Param 10/10 Step 15419/20000
Param 10/10 Step 15420/20000
Param 10/10 Step 15421/20000
Param 10/10 Step 15422/20000
Param 10/10 Step 15423/20000
Param 10/10 Step 15424/20000
Param 10/10 Step 15425/20000
Param 10/10 Step 15426/20000
Param 10/10 Step 15427/20000
Param 10/10 Step 15428/20000
Param 10/10 Step 15429/20000
Param 10/10 Step 15430/20000
Param 10/10 Step 15431/20000
Param 10/10 Step 15432/20000
Param 10/10 Step 15433/20000
Param 10/10 Step 15434/20000
Param 10/10 Step 15435/20000
Param 10/10 Step 15436/20000
Param 10/10 Step 15437/20000
Param 10/10 Step 15438/20000
Param 10/10 Step 15439/20000
Param 10/10 Step 15440/20000
Param 10/10 Step 15441/20000
Param 10/10 Step 15442/20000
Param 10/10 Step 15443/20000
Param 10/10 Step 15444/20000
Param 10/10 Step 15445/20000
Param 10/10 Step 15446/20000
Param 10/10 Step 15447/20000
Param 10/10 Step 15448/20000
Param 10/10 Step 15449/20000
Param 10/10 Step 15450/20000
Param 10/10 Step 15451/20000
Param 10/10 Step 15452/20000
Param 10/10 Step 15453/20000
Param 10/10 Step 15454/20000
Param 10/10 Step 15455/20000
Param 10/10 Step 15456/20000
Param 10/10 Step 15457/20000
Param 10/10 Step 15458/20000
Param 10/10 Step 15459/20000
Param 10/10 Step 15460/20000
Param 10/10 Step 15461/20000
Param 10/10 Step 15462/20000
Param 10/10 Step 15463/20000
Param 10/10 Step 15464/20000
Param 10/10 Step 15465/20000
Param 10/10 Step 15466/20000
Param 10/10 Step 15467/20000
Param 10/10 Step 15468/20000
Param 10/10 Step 15469/20000
Param 10/10 Step 15470/20000
Param 10/10 Step 15471/20000
Param 10/10 Step 15472/20000
Param 10/10 Step 15473/20000
Param 10/10 Step 15474/20000
Param 10/10 Step 15475/20000
Param 10/10 Step 15476/20000
Param 10/10 Step 15477/20000
Param 10/10 Step 15478/20000
Param 10/10 Step 15479/20000
Param 10/10 Step 15480/20000
Param 10/10 Step 15481/20000
Param 10/10 Step 15482/20000
Param 10/10 Step 15483/20000
Param 10/10 Step 15484/20000
Param 10/10 Step 15485/20000
Param 10/10 Step 15486/20000
Param 10/10 Step 15487/20000
Param 10/10 Step 15488/20000
Param 10/10 Step 15489/20000
Param 10/10 Step 15490/20000
Param 10/10 Step 15491/20000
Param 10/10 Step 15492/20000
Param 10/10 Step 15493/20000
Param 10/10 Step 15494/20000
Param 10/10 Step 15495/20000
Param 10/10 Step 15496/20000
Param 10/10 Step 15497/20000
Param 10/10 Step 15498/20000
Param 10/10 Step 15499/20000
Param 10/10 Step 15500/20000
Param 10/10 Step 15501/20000
Param 10/10 Step 15502/20000
Param 10/10 Step 15503/20000
Param 10/10 Step 15504/20000
Param 10/10 Step 15505/20000
Param 10/10 Step 15506/20000
Param 10/10 Step 15507/20000
Param 10/10 Step 15508/20000
Param 10/10 Step 15509/20000
Param 10/10 Step 15510/20000
Param 10/10 Step 15511/20000
Param 10/10 Step 15512/20000
Param 10/10 Step 15513/20000
Param 10/10 Step 15514/20000
Param 10/10 Step 15515/20000
Param 10/10 Step 15516/20000
Param 10/10 Step 15517/20000
Param 10/10 Step 15518/20000
Param 10/10 Step 15519/20000
Param 10/10 Step 15520/20000
Param 10/10 Step 15521/20000
Param 10/10 Step 15522/20000
Param 10/10 Step 15523/20000
Param 10/10 Step 15524/20000
Param 10/10 Step 15525/20000
Param 10/10 Step 15526/20000
Param 10/10 Step 15527/20000
Param 10/10 Step 15528/20000
Param 10/10 Step 15529/20000
Param 10/10 Step 15530/20000
Param 10/10 Step 15531/20000
Param 10/10 Step 15532/20000
Param 10/10 Step 15533/20000
Param 10/10 Step 15534/20000
Param 10/10 Step 15535/20000
Param 10/10 Step 15536/20000
Param 10/10 Step 15537/20000
Param 10/10 Step 15538/20000
Param 10/10 Step 15539/20000
Param 10/10 Step 15540/20000
Param 10/10 Step 15541/20000
Param 10/10 Step 15542/20000
Param 10/10 Step 15543/20000
Param 10/10 Step 15544/20000
Param 10/10 Step 15545/20000
Param 10/10 Step 15546/20000
Param 10/10 Step 15547/20000
Param 10/10 Step 15548/20000
Param 10/10 Step 15549/20000
Param 10/10 Step 15550/20000
Param 10/10 Step 15551/20000
Param 10/10 Step 15552/20000
Param 10/10 Step 15553/20000
Param 10/10 Step 15554/20000
Param 10/10 Step 15555/20000
Param 10/10 Step 15556/20000
Param 10/10 Step 15557/20000
Param 10/10 Step 15558/20000
Param 10/10 Step 15559/20000
Param 10/10 Step 15560/20000
Param 10/10 Step 15561/20000
Param 10/10 Step 15562/20000
Param 10/10 Step 15563/20000
Param 10/10 Step 15564/20000
Param 10/10 Step 15565/20000
Param 10/10 Step 15566/20000
Param 10/10 Step 15567/20000
Param 10/10 Step 15568/20000
Param 10/10 Step 15569/20000
Param 10/10 Step 15570/20000
Param 10/10 Step 15571/20000
Param 10/10 Step 15572/20000
Param 10/10 Step 15573/20000
Param 10/10 Step 15574/20000
Param 10/10 Step 15575/20000
Param 10/10 Step 15576/20000
Param 10/10 Step 15577/20000
Param 10/10 Step 15578/20000
Param 10/10 Step 15579/20000
Param 10/10 Step 15580/20000
Param 10/10 Step 15581/20000
Param 10/10 Step 15582/20000
Param 10/10 Step 15583/20000
Param 10/10 Step 15584/20000
Param 10/10 Step 15585/20000
Param 10/10 Step 15586/20000
Param 10/10 Step 15587/20000
Param 10/10 Step 15588/20000
Param 10/10 Step 15589/20000
Param 10/10 Step 15590/20000
Param 10/10 Step 15591/20000
Param 10/10 Step 15592/20000
Param 10/10 Step 15593/20000
Param 10/10 Step 15594/20000
Param 10/10 Step 15595/20000
Param 10/10 Step 15596/20000
Param 10/10 Step 15597/20000
Param 10/10 Step 15598/20000
Param 10/10 Step 15599/20000
Param 10/10 Step 15600/20000
Param 10/10 Step 15601/20000
Param 10/10 Step 15602/20000
Param 10/10 Step 15603/20000
Param 10/10 Step 15604/20000
Param 10/10 Step 15605/20000
Param 10/10 Step 15606/20000
Param 10/10 Step 15607/20000
Param 10/10 Step 15608/20000
Param 10/10 Step 15609/20000
Param 10/10 Step 15610/20000
Param 10/10 Step 15611/20000
Param 10/10 Step 15612/20000
Param 10/10 Step 15613/20000
Param 10/10 Step 15614/20000
Param 10/10 Step 15615/20000
Param 10/10 Step 15616/20000
Param 10/10 Step 15617/20000
Param 10/10 Step 15618/20000
Param 10/10 Step 15619/20000
Param 10/10 Step 15620/20000
Param 10/10 Step 15621/20000
Param 10/10 Step 15622/20000
Param 10/10 Step 15623/20000
Param 10/10 Step 15624/20000
Param 10/10 Step 15625/20000
Param 10/10 Step 15626/20000
Param 10/10 Step 15627/20000
Param 10/10 Step 15628/20000
Param 10/10 Step 15629/20000
Param 10/10 Step 15630/20000
Param 10/10 Step 15631/20000
Param 10/10 Step 15632/20000
Param 10/10 Step 15633/20000
Param 10/10 Step 15634/20000
Param 10/10 Step 15635/20000
Param 10/10 Step 15636/20000
Param 10/10 Step 15637/20000
Param 10/10 Step 15638/20000
Param 10/10 Step 15639/20000
Param 10/10 Step 15640/20000
Param 10/10 Step 15641/20000
Param 10/10 Step 15642/20000
Param 10/10 Step 15643/20000
Param 10/10 Step 15644/20000
Param 10/10 Step 15645/20000
Param 10/10 Step 15646/20000
Param 10/10 Step 15647/20000
Param 10/10 Step 15648/20000
Param 10/10 Step 15649/20000
Param 10/10 Step 15650/20000
Param 10/10 Step 15651/20000
Param 10/10 Step 15652/20000
Param 10/10 Step 15653/20000
Param 10/10 Step 15654/20000
Param 10/10 Step 15655/20000
Param 10/10 Step 15656/20000
Param 10/10 Step 15657/20000
Param 10/10 Step 15658/20000
Param 10/10 Step 15659/20000
Param 10/10 Step 15660/20000
Param 10/10 Step 15661/20000
Param 10/10 Step 15662/20000
Param 10/10 Step 15663/20000
Param 10/10 Step 15664/20000
Param 10/10 Step 15665/20000
Param 10/10 Step 15666/20000
Param 10/10 Step 15667/20000
Param 10/10 Step 15668/20000
Param 10/10 Step 15669/20000
Param 10/10 Step 15670/20000
Param 10/10 Step 15671/20000
Param 10/10 Step 15672/20000
Param 10/10 Step 15673/20000
Param 10/10 Step 15674/20000
Param 10/10 Step 15675/20000
Param 10/10 Step 15676/20000
Param 10/10 Step 15677/20000
Param 10/10 Step 15678/20000
Param 10/10 Step 15679/20000
Param 10/10 Step 15680/20000
Param 10/10 Step 15681/20000
Param 10/10 Step 15682/20000
Param 10/10 Step 15683/20000
Param 10/10 Step 15684/20000
Param 10/10 Step 15685/20000
Param 10/10 Step 15686/20000
Param 10/10 Step 15687/20000
Param 10/10 Step 15688/20000
Param 10/10 Step 15689/20000
Param 10/10 Step 15690/20000
Param 10/10 Step 15691/20000
Param 10/10 Step 15692/20000
Param 10/10 Step 15693/20000
Param 10/10 Step 15694/20000
Param 10/10 Step 15695/20000
Param 10/10 Step 15696/20000
Param 10/10 Step 15697/20000
Param 10/10 Step 15698/20000
Param 10/10 Step 15699/20000
Param 10/10 Step 15700/20000
Param 10/10 Step 15701/20000
Param 10/10 Step 15702/20000
Param 10/10 Step 15703/20000
Param 10/10 Step 15704/20000
Param 10/10 Step 15705/20000
Param 10/10 Step 15706/20000
Param 10/10 Step 15707/20000
Param 10/10 Step 15708/20000
Param 10/10 Step 15709/20000
Param 10/10 Step 15710/20000
Param 10/10 Step 15711/20000
Param 10/10 Step 15712/20000
Param 10/10 Step 15713/20000
Param 10/10 Step 15714/20000
Param 10/10 Step 15715/20000
Param 10/10 Step 15716/20000
Param 10/10 Step 15717/20000
Param 10/10 Step 15718/20000
Param 10/10 Step 15719/20000
Param 10/10 Step 15720/20000
Param 10/10 Step 15721/20000
Param 10/10 Step 15722/20000
Param 10/10 Step 15723/20000
Param 10/10 Step 15724/20000
Param 10/10 Step 15725/20000
Param 10/10 Step 15726/20000
Param 10/10 Step 15727/20000
Param 10/10 Step 15728/20000
Param 10/10 Step 15729/20000
Param 10/10 Step 15730/20000
Param 10/10 Step 15731/20000
Param 10/10 Step 15732/20000
Param 10/10 Step 15733/20000
Param 10/10 Step 15734/20000
Param 10/10 Step 15735/20000
Param 10/10 Step 15736/20000
Param 10/10 Step 15737/20000
Param 10/10 Step 15738/20000
Param 10/10 Step 15739/20000
Param 10/10 Step 15740/20000
Param 10/10 Step 15741/20000
Param 10/10 Step 15742/20000
Param 10/10 Step 15743/20000
Param 10/10 Step 15744/20000
Param 10/10 Step 15745/20000
Param 10/10 Step 15746/20000
Param 10/10 Step 15747/20000
Param 10/10 Step 15748/20000
Param 10/10 Step 15749/20000
Param 10/10 Step 15750/20000
Param 10/10 Step 15751/20000
Param 10/10 Step 15752/20000
Param 10/10 Step 15753/20000
Param 10/10 Step 15754/20000
Param 10/10 Step 15755/20000
Param 10/10 Step 15756/20000
Param 10/10 Step 15757/20000
Param 10/10 Step 15758/20000
Param 10/10 Step 15759/20000
Param 10/10 Step 15760/20000
Param 10/10 Step 15761/20000
Param 10/10 Step 15762/20000
Param 10/10 Step 15763/20000
Param 10/10 Step 15764/20000
Param 10/10 Step 15765/20000
Param 10/10 Step 15766/20000
Param 10/10 Step 15767/20000
Param 10/10 Step 15768/20000
Param 10/10 Step 15769/20000
Param 10/10 Step 15770/20000
Param 10/10 Step 15771/20000
Param 10/10 Step 15772/20000
Param 10/10 Step 15773/20000
Param 10/10 Step 15774/20000
Param 10/10 Step 15775/20000
Param 10/10 Step 15776/20000
Param 10/10 Step 15777/20000
Param 10/10 Step 15778/20000
Param 10/10 Step 15779/20000
Param 10/10 Step 15780/20000
Param 10/10 Step 15781/20000
Param 10/10 Step 15782/20000
Param 10/10 Step 15783/20000
Param 10/10 Step 15784/20000
Param 10/10 Step 15785/20000
Param 10/10 Step 15786/20000
Param 10/10 Step 15787/20000
Param 10/10 Step 15788/20000
Param 10/10 Step 15789/20000
Param 10/10 Step 15790/20000
Param 10/10 Step 15791/20000
Param 10/10 Step 15792/20000
Param 10/10 Step 15793/20000
Param 10/10 Step 15794/20000
Param 10/10 Step 15795/20000
Param 10/10 Step 15796/20000
Param 10/10 Step 15797/20000
Param 10/10 Step 15798/20000
Param 10/10 Step 15799/20000
Param 10/10 Step 15800/20000
Param 10/10 Step 15801/20000
Param 10/10 Step 15802/20000
Param 10/10 Step 15803/20000
Param 10/10 Step 15804/20000
Param 10/10 Step 15805/20000
Param 10/10 Step 15806/20000
Param 10/10 Step 15807/20000
Param 10/10 Step 15808/20000
Param 10/10 Step 15809/20000
Param 10/10 Step 15810/20000
Param 10/10 Step 15811/20000
Param 10/10 Step 15812/20000
Param 10/10 Step 15813/20000
Param 10/10 Step 15814/20000
Param 10/10 Step 15815/20000
Param 10/10 Step 15816/20000
Param 10/10 Step 15817/20000
Param 10/10 Step 15818/20000
Param 10/10 Step 15819/20000
Param 10/10 Step 15820/20000
Param 10/10 Step 15821/20000
Param 10/10 Step 15822/20000
Param 10/10 Step 15823/20000
Param 10/10 Step 15824/20000
Param 10/10 Step 15825/20000
Param 10/10 Step 15826/20000
Param 10/10 Step 15827/20000
Param 10/10 Step 15828/20000
Param 10/10 Step 15829/20000
Param 10/10 Step 15830/20000
Param 10/10 Step 15831/20000
Param 10/10 Step 15832/20000
Param 10/10 Step 15833/20000
Param 10/10 Step 15834/20000
Param 10/10 Step 15835/20000
Param 10/10 Step 15836/20000
Param 10/10 Step 15837/20000
Param 10/10 Step 15838/20000
Param 10/10 Step 15839/20000
Param 10/10 Step 15840/20000
Param 10/10 Step 15841/20000
Param 10/10 Step 15842/20000
Param 10/10 Step 15843/20000
Param 10/10 Step 15844/20000
Param 10/10 Step 15845/20000
Param 10/10 Step 15846/20000
Param 10/10 Step 15847/20000
Param 10/10 Step 15848/20000
Param 10/10 Step 15849/20000
Param 10/10 Step 15850/20000
Param 10/10 Step 15851/20000
Param 10/10 Step 15852/20000
Param 10/10 Step 15853/20000
Param 10/10 Step 15854/20000
Param 10/10 Step 15855/20000
Param 10/10 Step 15856/20000
Param 10/10 Step 15857/20000
Param 10/10 Step 15858/20000
Param 10/10 Step 15859/20000
Param 10/10 Step 15860/20000
Param 10/10 Step 15861/20000
Param 10/10 Step 15862/20000
Param 10/10 Step 15863/20000
Param 10/10 Step 15864/20000
Param 10/10 Step 15865/20000
Param 10/10 Step 15866/20000
Param 10/10 Step 15867/20000
Param 10/10 Step 15868/20000
Param 10/10 Step 15869/20000
Param 10/10 Step 15870/20000
Param 10/10 Step 15871/20000
Param 10/10 Step 15872/20000
Param 10/10 Step 15873/20000
Param 10/10 Step 15874/20000
Param 10/10 Step 15875/20000
Param 10/10 Step 15876/20000
Param 10/10 Step 15877/20000
Param 10/10 Step 15878/20000
Param 10/10 Step 15879/20000
Param 10/10 Step 15880/20000
Param 10/10 Step 15881/20000
Param 10/10 Step 15882/20000
Param 10/10 Step 15883/20000
Param 10/10 Step 15884/20000
Param 10/10 Step 15885/20000
Param 10/10 Step 15886/20000
Param 10/10 Step 15887/20000
Param 10/10 Step 15888/20000
Param 10/10 Step 15889/20000
Param 10/10 Step 15890/20000
Param 10/10 Step 15891/20000
Param 10/10 Step 15892/20000
Param 10/10 Step 15893/20000
Param 10/10 Step 15894/20000
Param 10/10 Step 15895/20000
Param 10/10 Step 15896/20000
Param 10/10 Step 15897/20000
Param 10/10 Step 15898/20000
Param 10/10 Step 15899/20000
Param 10/10 Step 15900/20000
Param 10/10 Step 15901/20000
Param 10/10 Step 15902/20000
Param 10/10 Step 15903/20000
Param 10/10 Step 15904/20000
Param 10/10 Step 15905/20000
Param 10/10 Step 15906/20000
Param 10/10 Step 15907/20000
Param 10/10 Step 15908/20000
Param 10/10 Step 15909/20000
Param 10/10 Step 15910/20000
Param 10/10 Step 15911/20000
Param 10/10 Step 15912/20000
Param 10/10 Step 15913/20000
Param 10/10 Step 15914/20000
Param 10/10 Step 15915/20000
Param 10/10 Step 15916/20000
Param 10/10 Step 15917/20000
Param 10/10 Step 15918/20000
Param 10/10 Step 15919/20000
Param 10/10 Step 15920/20000
Param 10/10 Step 15921/20000
Param 10/10 Step 15922/20000
Param 10/10 Step 15923/20000
Param 10/10 Step 15924/20000
Param 10/10 Step 15925/20000
Param 10/10 Step 15926/20000
Param 10/10 Step 15927/20000
Param 10/10 Step 15928/20000
Param 10/10 Step 15929/20000
Param 10/10 Step 15930/20000
Param 10/10 Step 15931/20000
Param 10/10 Step 15932/20000
Param 10/10 Step 15933/20000
Param 10/10 Step 15934/20000
Param 10/10 Step 15935/20000
Param 10/10 Step 15936/20000
Param 10/10 Step 15937/20000
Param 10/10 Step 15938/20000
Param 10/10 Step 15939/20000
Param 10/10 Step 15940/20000
Param 10/10 Step 15941/20000
Param 10/10 Step 15942/20000
Param 10/10 Step 15943/20000
Param 10/10 Step 15944/20000
Param 10/10 Step 15945/20000
Param 10/10 Step 15946/20000
Param 10/10 Step 15947/20000
Param 10/10 Step 15948/20000
Param 10/10 Step 15949/20000
Param 10/10 Step 15950/20000
Param 10/10 Step 15951/20000
Param 10/10 Step 15952/20000
Param 10/10 Step 15953/20000
Param 10/10 Step 15954/20000
Param 10/10 Step 15955/20000
Param 10/10 Step 15956/20000
Param 10/10 Step 15957/20000
Param 10/10 Step 15958/20000
Param 10/10 Step 15959/20000
Param 10/10 Step 15960/20000
Param 10/10 Step 15961/20000
Param 10/10 Step 15962/20000
Param 10/10 Step 15963/20000
Param 10/10 Step 15964/20000
Param 10/10 Step 15965/20000
Param 10/10 Step 15966/20000
Param 10/10 Step 15967/20000
Param 10/10 Step 15968/20000
Param 10/10 Step 15969/20000
Param 10/10 Step 15970/20000
Param 10/10 Step 15971/20000
Param 10/10 Step 15972/20000
Param 10/10 Step 15973/20000
Param 10/10 Step 15974/20000
Param 10/10 Step 15975/20000
Param 10/10 Step 15976/20000
Param 10/10 Step 15977/20000
Param 10/10 Step 15978/20000
Param 10/10 Step 15979/20000
Param 10/10 Step 15980/20000
Param 10/10 Step 15981/20000
Param 10/10 Step 15982/20000
Param 10/10 Step 15983/20000
Param 10/10 Step 15984/20000
Param 10/10 Step 15985/20000
Param 10/10 Step 15986/20000
Param 10/10 Step 15987/20000
Param 10/10 Step 15988/20000
Param 10/10 Step 15989/20000
Param 10/10 Step 15990/20000
Param 10/10 Step 15991/20000
Param 10/10 Step 15992/20000
Param 10/10 Step 15993/20000
Param 10/10 Step 15994/20000
Param 10/10 Step 15995/20000
Param 10/10 Step 15996/20000
Param 10/10 Step 15997/20000
Param 10/10 Step 15998/20000
Param 10/10 Step 15999/20000
Param 10/10 Step 16000/20000
Param 10/10 Step 16001/20000
Param 10/10 Step 16002/20000
Param 10/10 Step 16003/20000
Param 10/10 Step 16004/20000
Param 10/10 Step 16005/20000
Param 10/10 Step 16006/20000
Param 10/10 Step 16007/20000
Param 10/10 Step 16008/20000
Param 10/10 Step 16009/20000
Param 10/10 Step 16010/20000
Param 10/10 Step 16011/20000
Param 10/10 Step 16012/20000
Param 10/10 Step 16013/20000
Param 10/10 Step 16014/20000
Param 10/10 Step 16015/20000
Param 10/10 Step 16016/20000
Param 10/10 Step 16017/20000
Param 10/10 Step 16018/20000
Param 10/10 Step 16019/20000
Param 10/10 Step 16020/20000
Param 10/10 Step 16021/20000
Param 10/10 Step 16022/20000
Param 10/10 Step 16023/20000
Param 10/10 Step 16024/20000
Param 10/10 Step 16025/20000
Param 10/10 Step 16026/20000
Param 10/10 Step 16027/20000
Param 10/10 Step 16028/20000
Param 10/10 Step 16029/20000
Param 10/10 Step 16030/20000
Param 10/10 Step 16031/20000
Param 10/10 Step 16032/20000
Param 10/10 Step 16033/20000
Param 10/10 Step 16034/20000
Param 10/10 Step 16035/20000
Param 10/10 Step 16036/20000
Param 10/10 Step 16037/20000
Param 10/10 Step 16038/20000
Param 10/10 Step 16039/20000
Param 10/10 Step 16040/20000
Param 10/10 Step 16041/20000
Param 10/10 Step 16042/20000
Param 10/10 Step 16043/20000
Param 10/10 Step 16044/20000
Param 10/10 Step 16045/20000
Param 10/10 Step 16046/20000
Param 10/10 Step 16047/20000
Param 10/10 Step 16048/20000
Param 10/10 Step 16049/20000
Param 10/10 Step 16050/20000
Param 10/10 Step 16051/20000
Param 10/10 Step 16052/20000
Param 10/10 Step 16053/20000
Param 10/10 Step 16054/20000
Param 10/10 Step 16055/20000
Param 10/10 Step 16056/20000
Param 10/10 Step 16057/20000
Param 10/10 Step 16058/20000
Param 10/10 Step 16059/20000
Param 10/10 Step 16060/20000
Param 10/10 Step 16061/20000
Param 10/10 Step 16062/20000
Param 10/10 Step 16063/20000
Param 10/10 Step 16064/20000
Param 10/10 Step 16065/20000
Param 10/10 Step 16066/20000
Param 10/10 Step 16067/20000
Param 10/10 Step 16068/20000
Param 10/10 Step 16069/20000
Param 10/10 Step 16070/20000
Param 10/10 Step 16071/20000
Param 10/10 Step 16072/20000
Param 10/10 Step 16073/20000
Param 10/10 Step 16074/20000
Param 10/10 Step 16075/20000
Param 10/10 Step 16076/20000
Param 10/10 Step 16077/20000
Param 10/10 Step 16078/20000
Param 10/10 Step 16079/20000
Param 10/10 Step 16080/20000
Param 10/10 Step 16081/20000
Param 10/10 Step 16082/20000
Param 10/10 Step 16083/20000
Param 10/10 Step 16084/20000
Param 10/10 Step 16085/20000
Param 10/10 Step 16086/20000
Param 10/10 Step 16087/20000
Param 10/10 Step 16088/20000
Param 10/10 Step 16089/20000
Param 10/10 Step 16090/20000
Param 10/10 Step 16091/20000
Param 10/10 Step 16092/20000
Param 10/10 Step 16093/20000
Param 10/10 Step 16094/20000
Param 10/10 Step 16095/20000
Param 10/10 Step 16096/20000
Param 10/10 Step 16097/20000
Param 10/10 Step 16098/20000
Param 10/10 Step 16099/20000
Param 10/10 Step 16100/20000
Param 10/10 Step 16101/20000
Param 10/10 Step 16102/20000
Param 10/10 Step 16103/20000
Param 10/10 Step 16104/20000
Param 10/10 Step 16105/20000
Param 10/10 Step 16106/20000
Param 10/10 Step 16107/20000
Param 10/10 Step 16108/20000
Param 10/10 Step 16109/20000
Param 10/10 Step 16110/20000
Param 10/10 Step 16111/20000
Param 10/10 Step 16112/20000
Param 10/10 Step 16113/20000
Param 10/10 Step 16114/20000
Param 10/10 Step 16115/20000
Param 10/10 Step 16116/20000
Param 10/10 Step 16117/20000
Param 10/10 Step 16118/20000
Param 10/10 Step 16119/20000
Param 10/10 Step 16120/20000
Param 10/10 Step 16121/20000
Param 10/10 Step 16122/20000
Param 10/10 Step 16123/20000
Param 10/10 Step 16124/20000
Param 10/10 Step 16125/20000
Param 10/10 Step 16126/20000
Param 10/10 Step 16127/20000
Param 10/10 Step 16128/20000
Param 10/10 Step 16129/20000
Param 10/10 Step 16130/20000
Param 10/10 Step 16131/20000
Param 10/10 Step 16132/20000
Param 10/10 Step 16133/20000
Param 10/10 Step 16134/20000
Param 10/10 Step 16135/20000
Param 10/10 Step 16136/20000
Param 10/10 Step 16137/20000
Param 10/10 Step 16138/20000
Param 10/10 Step 16139/20000
Param 10/10 Step 16140/20000
Param 10/10 Step 16141/20000
Param 10/10 Step 16142/20000
Param 10/10 Step 16143/20000
Param 10/10 Step 16144/20000
Param 10/10 Step 16145/20000
Param 10/10 Step 16146/20000
Param 10/10 Step 16147/20000
Param 10/10 Step 16148/20000
Param 10/10 Step 16149/20000
Param 10/10 Step 16150/20000
Param 10/10 Step 16151/20000
Param 10/10 Step 16152/20000
Param 10/10 Step 16153/20000
Param 10/10 Step 16154/20000
Param 10/10 Step 16155/20000
Param 10/10 Step 16156/20000
Param 10/10 Step 16157/20000
Param 10/10 Step 16158/20000
Param 10/10 Step 16159/20000
Param 10/10 Step 16160/20000
Param 10/10 Step 16161/20000
Param 10/10 Step 16162/20000
Param 10/10 Step 16163/20000
Param 10/10 Step 16164/20000
Param 10/10 Step 16165/20000
Param 10/10 Step 16166/20000
Param 10/10 Step 16167/20000
Param 10/10 Step 16168/20000
Param 10/10 Step 16169/20000
Param 10/10 Step 16170/20000
Param 10/10 Step 16171/20000
Param 10/10 Step 16172/20000
Param 10/10 Step 16173/20000
Param 10/10 Step 16174/20000
Param 10/10 Step 16175/20000
Param 10/10 Step 16176/20000
Param 10/10 Step 16177/20000
Param 10/10 Step 16178/20000
Param 10/10 Step 16179/20000
Param 10/10 Step 16180/20000
Param 10/10 Step 16181/20000
Param 10/10 Step 16182/20000
Param 10/10 Step 16183/20000
Param 10/10 Step 16184/20000
Param 10/10 Step 16185/20000
Param 10/10 Step 16186/20000
Param 10/10 Step 16187/20000
Param 10/10 Step 16188/20000
Param 10/10 Step 16189/20000
Param 10/10 Step 16190/20000
Param 10/10 Step 16191/20000
Param 10/10 Step 16192/20000
Param 10/10 Step 16193/20000
Param 10/10 Step 16194/20000
Param 10/10 Step 16195/20000
Param 10/10 Step 16196/20000
Param 10/10 Step 16197/20000
Param 10/10 Step 16198/20000
Param 10/10 Step 16199/20000
Param 10/10 Step 16200/20000
Param 10/10 Step 16201/20000
Param 10/10 Step 16202/20000
Param 10/10 Step 16203/20000
Param 10/10 Step 16204/20000
Param 10/10 Step 16205/20000
Param 10/10 Step 16206/20000
Param 10/10 Step 16207/20000
Param 10/10 Step 16208/20000
Param 10/10 Step 16209/20000
Param 10/10 Step 16210/20000
Param 10/10 Step 16211/20000
Param 10/10 Step 16212/20000
Param 10/10 Step 16213/20000
Param 10/10 Step 16214/20000
Param 10/10 Step 16215/20000
Param 10/10 Step 16216/20000
Param 10/10 Step 16217/20000
Param 10/10 Step 16218/20000
Param 10/10 Step 16219/20000
Param 10/10 Step 16220/20000
Param 10/10 Step 16221/20000
Param 10/10 Step 16222/20000
Param 10/10 Step 16223/20000
Param 10/10 Step 16224/20000
Param 10/10 Step 16225/20000
Param 10/10 Step 16226/20000
Param 10/10 Step 16227/20000
Param 10/10 Step 16228/20000
Param 10/10 Step 16229/20000
Param 10/10 Step 16230/20000
Param 10/10 Step 16231/20000
Param 10/10 Step 16232/20000
Param 10/10 Step 16233/20000
Param 10/10 Step 16234/20000
Param 10/10 Step 16235/20000
Param 10/10 Step 16236/20000
Param 10/10 Step 16237/20000
Param 10/10 Step 16238/20000
Param 10/10 Step 16239/20000
Param 10/10 Step 16240/20000
Param 10/10 Step 16241/20000
Param 10/10 Step 16242/20000
Param 10/10 Step 16243/20000
Param 10/10 Step 16244/20000
Param 10/10 Step 16245/20000
Param 10/10 Step 16246/20000
Param 10/10 Step 16247/20000
Param 10/10 Step 16248/20000
Param 10/10 Step 16249/20000
Param 10/10 Step 16250/20000
Param 10/10 Step 16251/20000
Param 10/10 Step 16252/20000
Param 10/10 Step 16253/20000
Param 10/10 Step 16254/20000
Param 10/10 Step 16255/20000
Param 10/10 Step 16256/20000
Param 10/10 Step 16257/20000
Param 10/10 Step 16258/20000
Param 10/10 Step 16259/20000
Param 10/10 Step 16260/20000
Param 10/10 Step 16261/20000
Param 10/10 Step 16262/20000
Param 10/10 Step 16263/20000
Param 10/10 Step 16264/20000
Param 10/10 Step 16265/20000
Param 10/10 Step 16266/20000
Param 10/10 Step 16267/20000
Param 10/10 Step 16268/20000
Param 10/10 Step 16269/20000
Param 10/10 Step 16270/20000
Param 10/10 Step 16271/20000
Param 10/10 Step 16272/20000
Param 10/10 Step 16273/20000
Param 10/10 Step 16274/20000
Param 10/10 Step 16275/20000
Param 10/10 Step 16276/20000
Param 10/10 Step 16277/20000
Param 10/10 Step 16278/20000
Param 10/10 Step 16279/20000
Param 10/10 Step 16280/20000
Param 10/10 Step 16281/20000
Param 10/10 Step 16282/20000
Param 10/10 Step 16283/20000
Param 10/10 Step 16284/20000
Param 10/10 Step 16285/20000
Param 10/10 Step 16286/20000
Param 10/10 Step 16287/20000
Param 10/10 Step 16288/20000
Param 10/10 Step 16289/20000
Param 10/10 Step 16290/20000
Param 10/10 Step 16291/20000
Param 10/10 Step 16292/20000
Param 10/10 Step 16293/20000
Param 10/10 Step 16294/20000
Param 10/10 Step 16295/20000
Param 10/10 Step 16296/20000
Param 10/10 Step 16297/20000
Param 10/10 Step 16298/20000
Param 10/10 Step 16299/20000
Param 10/10 Step 16300/20000
Param 10/10 Step 16301/20000
Param 10/10 Step 16302/20000
Param 10/10 Step 16303/20000
Param 10/10 Step 16304/20000
Param 10/10 Step 16305/20000
Param 10/10 Step 16306/20000
Param 10/10 Step 16307/20000
Param 10/10 Step 16308/20000
Param 10/10 Step 16309/20000
Param 10/10 Step 16310/20000
Param 10/10 Step 16311/20000
Param 10/10 Step 16312/20000
Param 10/10 Step 16313/20000
Param 10/10 Step 16314/20000
Param 10/10 Step 16315/20000
Param 10/10 Step 16316/20000
Param 10/10 Step 16317/20000
Param 10/10 Step 16318/20000
Param 10/10 Step 16319/20000
Param 10/10 Step 16320/20000
Param 10/10 Step 16321/20000
Param 10/10 Step 16322/20000
Param 10/10 Step 16323/20000
Param 10/10 Step 16324/20000
Param 10/10 Step 16325/20000
Param 10/10 Step 16326/20000
Param 10/10 Step 16327/20000
Param 10/10 Step 16328/20000
Param 10/10 Step 16329/20000
Param 10/10 Step 16330/20000
Param 10/10 Step 16331/20000
Param 10/10 Step 16332/20000
Param 10/10 Step 16333/20000
Param 10/10 Step 16334/20000
Param 10/10 Step 16335/20000
Param 10/10 Step 16336/20000
Param 10/10 Step 16337/20000
Param 10/10 Step 16338/20000
Param 10/10 Step 16339/20000
Param 10/10 Step 16340/20000
Param 10/10 Step 16341/20000
Param 10/10 Step 16342/20000
Param 10/10 Step 16343/20000
Param 10/10 Step 16344/20000
Param 10/10 Step 16345/20000
Param 10/10 Step 16346/20000
Param 10/10 Step 16347/20000
Param 10/10 Step 16348/20000
Param 10/10 Step 16349/20000
Param 10/10 Step 16350/20000
Param 10/10 Step 16351/20000
Param 10/10 Step 16352/20000
Param 10/10 Step 16353/20000
Param 10/10 Step 16354/20000
Param 10/10 Step 16355/20000
Param 10/10 Step 16356/20000
Param 10/10 Step 16357/20000
Param 10/10 Step 16358/20000
Param 10/10 Step 16359/20000
Param 10/10 Step 16360/20000
Param 10/10 Step 16361/20000
Param 10/10 Step 16362/20000
Param 10/10 Step 16363/20000
Param 10/10 Step 16364/20000
Param 10/10 Step 16365/20000
Param 10/10 Step 16366/20000
Param 10/10 Step 16367/20000
Param 10/10 Step 16368/20000
Param 10/10 Step 16369/20000
Param 10/10 Step 16370/20000
Param 10/10 Step 16371/20000
Param 10/10 Step 16372/20000
Param 10/10 Step 16373/20000
Param 10/10 Step 16374/20000
Param 10/10 Step 16375/20000
Param 10/10 Step 16376/20000
Param 10/10 Step 16377/20000
Param 10/10 Step 16378/20000
Param 10/10 Step 16379/20000
Param 10/10 Step 16380/20000
Param 10/10 Step 16381/20000
Param 10/10 Step 16382/20000
Param 10/10 Step 16383/20000
Param 10/10 Step 16384/20000
Param 10/10 Step 16385/20000
Param 10/10 Step 16386/20000
Param 10/10 Step 16387/20000
Param 10/10 Step 16388/20000
Param 10/10 Step 16389/20000
Param 10/10 Step 16390/20000
Param 10/10 Step 16391/20000
Param 10/10 Step 16392/20000
Param 10/10 Step 16393/20000
Param 10/10 Step 16394/20000
Param 10/10 Step 16395/20000
Param 10/10 Step 16396/20000
Param 10/10 Step 16397/20000
Param 10/10 Step 16398/20000
Param 10/10 Step 16399/20000
Param 10/10 Step 16400/20000
Param 10/10 Step 16401/20000
Param 10/10 Step 16402/20000
Param 10/10 Step 16403/20000
Param 10/10 Step 16404/20000
Param 10/10 Step 16405/20000
Param 10/10 Step 16406/20000
Param 10/10 Step 16407/20000
Param 10/10 Step 16408/20000
Param 10/10 Step 16409/20000
Param 10/10 Step 16410/20000
Param 10/10 Step 16411/20000
Param 10/10 Step 16412/20000
Param 10/10 Step 16413/20000
Param 10/10 Step 16414/20000
Param 10/10 Step 16415/20000
Param 10/10 Step 16416/20000
Param 10/10 Step 16417/20000
Param 10/10 Step 16418/20000
Param 10/10 Step 16419/20000
Param 10/10 Step 16420/20000
Param 10/10 Step 16421/20000
Param 10/10 Step 16422/20000
Param 10/10 Step 16423/20000
Param 10/10 Step 16424/20000
Param 10/10 Step 16425/20000
Param 10/10 Step 16426/20000
Param 10/10 Step 16427/20000
Param 10/10 Step 16428/20000
Param 10/10 Step 16429/20000
Param 10/10 Step 16430/20000
Param 10/10 Step 16431/20000
Param 10/10 Step 16432/20000
Param 10/10 Step 16433/20000
Param 10/10 Step 16434/20000
Param 10/10 Step 16435/20000
Param 10/10 Step 16436/20000
Param 10/10 Step 16437/20000
Param 10/10 Step 16438/20000
Param 10/10 Step 16439/20000
Param 10/10 Step 16440/20000
Param 10/10 Step 16441/20000
Param 10/10 Step 16442/20000
Param 10/10 Step 16443/20000
Param 10/10 Step 16444/20000
Param 10/10 Step 16445/20000
Param 10/10 Step 16446/20000
Param 10/10 Step 16447/20000
Param 10/10 Step 16448/20000
Param 10/10 Step 16449/20000
Param 10/10 Step 16450/20000
Param 10/10 Step 16451/20000
Param 10/10 Step 16452/20000
Param 10/10 Step 16453/20000
Param 10/10 Step 16454/20000
Param 10/10 Step 16455/20000
Param 10/10 Step 16456/20000
Param 10/10 Step 16457/20000
Param 10/10 Step 16458/20000
Param 10/10 Step 16459/20000
Param 10/10 Step 16460/20000
Param 10/10 Step 16461/20000
Param 10/10 Step 16462/20000
Param 10/10 Step 16463/20000
Param 10/10 Step 16464/20000
Param 10/10 Step 16465/20000
Param 10/10 Step 16466/20000
Param 10/10 Step 16467/20000
Param 10/10 Step 16468/20000
Param 10/10 Step 16469/20000
Param 10/10 Step 16470/20000
Param 10/10 Step 16471/20000
Param 10/10 Step 16472/20000
Param 10/10 Step 16473/20000
Param 10/10 Step 16474/20000
Param 10/10 Step 16475/20000
Param 10/10 Step 16476/20000
Param 10/10 Step 16477/20000
Param 10/10 Step 16478/20000
Param 10/10 Step 16479/20000
Param 10/10 Step 16480/20000
Param 10/10 Step 16481/20000
Param 10/10 Step 16482/20000
Param 10/10 Step 16483/20000
Param 10/10 Step 16484/20000
Param 10/10 Step 16485/20000
Param 10/10 Step 16486/20000
Param 10/10 Step 16487/20000
Param 10/10 Step 16488/20000
Param 10/10 Step 16489/20000
Param 10/10 Step 16490/20000
Param 10/10 Step 16491/20000
Param 10/10 Step 16492/20000
Param 10/10 Step 16493/20000
Param 10/10 Step 16494/20000
Param 10/10 Step 16495/20000
Param 10/10 Step 16496/20000
Param 10/10 Step 16497/20000
Param 10/10 Step 16498/20000
Param 10/10 Step 16499/20000
Param 10/10 Step 16500/20000
Param 10/10 Step 16501/20000
Param 10/10 Step 16502/20000
Param 10/10 Step 16503/20000
Param 10/10 Step 16504/20000
Param 10/10 Step 16505/20000
Param 10/10 Step 16506/20000
Param 10/10 Step 16507/20000
Param 10/10 Step 16508/20000
Param 10/10 Step 16509/20000
Param 10/10 Step 16510/20000
Param 10/10 Step 16511/20000
Param 10/10 Step 16512/20000
Param 10/10 Step 16513/20000
Param 10/10 Step 16514/20000
Param 10/10 Step 16515/20000
Param 10/10 Step 16516/20000
Param 10/10 Step 16517/20000
Param 10/10 Step 16518/20000
Param 10/10 Step 16519/20000
Param 10/10 Step 16520/20000
Param 10/10 Step 16521/20000
Param 10/10 Step 16522/20000
Param 10/10 Step 16523/20000
Param 10/10 Step 16524/20000
Param 10/10 Step 16525/20000
Param 10/10 Step 16526/20000
Param 10/10 Step 16527/20000
Param 10/10 Step 16528/20000
Param 10/10 Step 16529/20000
Param 10/10 Step 16530/20000
Param 10/10 Step 16531/20000
Param 10/10 Step 16532/20000
Param 10/10 Step 16533/20000
Param 10/10 Step 16534/20000
Param 10/10 Step 16535/20000
Param 10/10 Step 16536/20000
Param 10/10 Step 16537/20000
Param 10/10 Step 16538/20000
Param 10/10 Step 16539/20000
Param 10/10 Step 16540/20000
Param 10/10 Step 16541/20000
Param 10/10 Step 16542/20000
Param 10/10 Step 16543/20000
Param 10/10 Step 16544/20000
Param 10/10 Step 16545/20000
Param 10/10 Step 16546/20000
Param 10/10 Step 16547/20000
Param 10/10 Step 16548/20000
Param 10/10 Step 16549/20000
Param 10/10 Step 16550/20000
Param 10/10 Step 16551/20000
Param 10/10 Step 16552/20000
Param 10/10 Step 16553/20000
Param 10/10 Step 16554/20000
Param 10/10 Step 16555/20000
Param 10/10 Step 16556/20000
Param 10/10 Step 16557/20000
Param 10/10 Step 16558/20000
Param 10/10 Step 16559/20000
Param 10/10 Step 16560/20000
Param 10/10 Step 16561/20000
Param 10/10 Step 16562/20000
Param 10/10 Step 16563/20000
Param 10/10 Step 16564/20000
Param 10/10 Step 16565/20000
Param 10/10 Step 16566/20000
Param 10/10 Step 16567/20000
Param 10/10 Step 16568/20000
Param 10/10 Step 16569/20000
Param 10/10 Step 16570/20000
Param 10/10 Step 16571/20000
Param 10/10 Step 16572/20000
Param 10/10 Step 16573/20000
Param 10/10 Step 16574/20000
Param 10/10 Step 16575/20000
Param 10/10 Step 16576/20000
Param 10/10 Step 16577/20000
Param 10/10 Step 16578/20000
Param 10/10 Step 16579/20000
Param 10/10 Step 16580/20000
Param 10/10 Step 16581/20000
Param 10/10 Step 16582/20000
Param 10/10 Step 16583/20000
Param 10/10 Step 16584/20000
Param 10/10 Step 16585/20000
Param 10/10 Step 16586/20000
Param 10/10 Step 16587/20000
Param 10/10 Step 16588/20000
Param 10/10 Step 16589/20000
Param 10/10 Step 16590/20000
Param 10/10 Step 16591/20000
Param 10/10 Step 16592/20000
Param 10/10 Step 16593/20000
Param 10/10 Step 16594/20000
Param 10/10 Step 16595/20000
Param 10/10 Step 16596/20000
Param 10/10 Step 16597/20000
Param 10/10 Step 16598/20000
Param 10/10 Step 16599/20000
Param 10/10 Step 16600/20000
Param 10/10 Step 16601/20000
Param 10/10 Step 16602/20000
Param 10/10 Step 16603/20000
Param 10/10 Step 16604/20000
Param 10/10 Step 16605/20000
Param 10/10 Step 16606/20000
Param 10/10 Step 16607/20000
Param 10/10 Step 16608/20000
Param 10/10 Step 16609/20000
Param 10/10 Step 16610/20000
Param 10/10 Step 16611/20000
Param 10/10 Step 16612/20000
Param 10/10 Step 16613/20000
Param 10/10 Step 16614/20000
Param 10/10 Step 16615/20000
Param 10/10 Step 16616/20000
Param 10/10 Step 16617/20000
Param 10/10 Step 16618/20000
Param 10/10 Step 16619/20000
Param 10/10 Step 16620/20000
Param 10/10 Step 16621/20000
Param 10/10 Step 16622/20000
Param 10/10 Step 16623/20000
Param 10/10 Step 16624/20000
Param 10/10 Step 16625/20000
Param 10/10 Step 16626/20000
Param 10/10 Step 16627/20000
Param 10/10 Step 16628/20000
Param 10/10 Step 16629/20000
Param 10/10 Step 16630/20000
Param 10/10 Step 16631/20000
Param 10/10 Step 16632/20000
Param 10/10 Step 16633/20000
Param 10/10 Step 16634/20000
Param 10/10 Step 16635/20000
Param 10/10 Step 16636/20000
Param 10/10 Step 16637/20000
Param 10/10 Step 16638/20000
Param 10/10 Step 16639/20000
Param 10/10 Step 16640/20000
Param 10/10 Step 16641/20000
Param 10/10 Step 16642/20000
Param 10/10 Step 16643/20000
Param 10/10 Step 16644/20000
Param 10/10 Step 16645/20000
Param 10/10 Step 16646/20000
Param 10/10 Step 16647/20000
Param 10/10 Step 16648/20000
Param 10/10 Step 16649/20000
Param 10/10 Step 16650/20000
Param 10/10 Step 16651/20000
Param 10/10 Step 16652/20000
Param 10/10 Step 16653/20000
Param 10/10 Step 16654/20000
Param 10/10 Step 16655/20000
Param 10/10 Step 16656/20000
Param 10/10 Step 16657/20000
Param 10/10 Step 16658/20000
Param 10/10 Step 16659/20000
Param 10/10 Step 16660/20000
Param 10/10 Step 16661/20000
Param 10/10 Step 16662/20000
Param 10/10 Step 16663/20000
Param 10/10 Step 16664/20000
Param 10/10 Step 16665/20000
Param 10/10 Step 16666/20000
Param 10/10 Step 16667/20000
Param 10/10 Step 16668/20000
Param 10/10 Step 16669/20000
Param 10/10 Step 16670/20000
Param 10/10 Step 16671/20000
Param 10/10 Step 16672/20000
Param 10/10 Step 16673/20000
Param 10/10 Step 16674/20000
Param 10/10 Step 16675/20000
Param 10/10 Step 16676/20000
Param 10/10 Step 16677/20000
Param 10/10 Step 16678/20000
Param 10/10 Step 16679/20000
Param 10/10 Step 16680/20000
Param 10/10 Step 16681/20000
Param 10/10 Step 16682/20000
Param 10/10 Step 16683/20000
Param 10/10 Step 16684/20000
Param 10/10 Step 16685/20000
Param 10/10 Step 16686/20000
Param 10/10 Step 16687/20000
Param 10/10 Step 16688/20000
Param 10/10 Step 16689/20000
Param 10/10 Step 16690/20000
Param 10/10 Step 16691/20000
Param 10/10 Step 16692/20000
Param 10/10 Step 16693/20000
Param 10/10 Step 16694/20000
Param 10/10 Step 16695/20000
Param 10/10 Step 16696/20000
Param 10/10 Step 16697/20000
Param 10/10 Step 16698/20000
Param 10/10 Step 16699/20000
Param 10/10 Step 16700/20000
Param 10/10 Step 16701/20000
Param 10/10 Step 16702/20000
Param 10/10 Step 16703/20000
Param 10/10 Step 16704/20000
Param 10/10 Step 16705/20000
Param 10/10 Step 16706/20000
Param 10/10 Step 16707/20000
Param 10/10 Step 16708/20000
Param 10/10 Step 16709/20000
Param 10/10 Step 16710/20000
Param 10/10 Step 16711/20000
Param 10/10 Step 16712/20000
Param 10/10 Step 16713/20000
Param 10/10 Step 16714/20000
Param 10/10 Step 16715/20000
Param 10/10 Step 16716/20000
Param 10/10 Step 16717/20000
Param 10/10 Step 16718/20000
Param 10/10 Step 16719/20000
Param 10/10 Step 16720/20000
Param 10/10 Step 16721/20000
Param 10/10 Step 16722/20000
Param 10/10 Step 16723/20000
Param 10/10 Step 16724/20000
Param 10/10 Step 16725/20000
Param 10/10 Step 16726/20000
Param 10/10 Step 16727/20000
Param 10/10 Step 16728/20000
Param 10/10 Step 16729/20000
Param 10/10 Step 16730/20000
Param 10/10 Step 16731/20000
Param 10/10 Step 16732/20000
Param 10/10 Step 16733/20000
Param 10/10 Step 16734/20000
Param 10/10 Step 16735/20000
Param 10/10 Step 16736/20000
Param 10/10 Step 16737/20000
Param 10/10 Step 16738/20000
Param 10/10 Step 16739/20000
Param 10/10 Step 16740/20000
Param 10/10 Step 16741/20000
Param 10/10 Step 16742/20000
Param 10/10 Step 16743/20000
Param 10/10 Step 16744/20000
Param 10/10 Step 16745/20000
Param 10/10 Step 16746/20000
Param 10/10 Step 16747/20000
Param 10/10 Step 16748/20000
Param 10/10 Step 16749/20000
Param 10/10 Step 16750/20000
Param 10/10 Step 16751/20000
Param 10/10 Step 16752/20000
Param 10/10 Step 16753/20000
Param 10/10 Step 16754/20000
Param 10/10 Step 16755/20000
Param 10/10 Step 16756/20000
Param 10/10 Step 16757/20000
Param 10/10 Step 16758/20000
Param 10/10 Step 16759/20000
Param 10/10 Step 16760/20000
Param 10/10 Step 16761/20000
Param 10/10 Step 16762/20000
Param 10/10 Step 16763/20000
Param 10/10 Step 16764/20000
Param 10/10 Step 16765/20000
Param 10/10 Step 16766/20000
Param 10/10 Step 16767/20000
Param 10/10 Step 16768/20000
Param 10/10 Step 16769/20000
Param 10/10 Step 16770/20000
Param 10/10 Step 16771/20000
Param 10/10 Step 16772/20000
Param 10/10 Step 16773/20000
Param 10/10 Step 16774/20000
Param 10/10 Step 16775/20000
Param 10/10 Step 16776/20000
Param 10/10 Step 16777/20000
Param 10/10 Step 16778/20000
Param 10/10 Step 16779/20000
Param 10/10 Step 16780/20000
Param 10/10 Step 16781/20000
Param 10/10 Step 16782/20000
Param 10/10 Step 16783/20000
Param 10/10 Step 16784/20000
Param 10/10 Step 16785/20000
Param 10/10 Step 16786/20000
Param 10/10 Step 16787/20000
Param 10/10 Step 16788/20000
Param 10/10 Step 16789/20000
Param 10/10 Step 16790/20000
Param 10/10 Step 16791/20000
Param 10/10 Step 16792/20000
Param 10/10 Step 16793/20000
Param 10/10 Step 16794/20000
Param 10/10 Step 16795/20000
Param 10/10 Step 16796/20000
Param 10/10 Step 16797/20000
Param 10/10 Step 16798/20000
Param 10/10 Step 16799/20000
Param 10/10 Step 16800/20000
Param 10/10 Step 16801/20000
Param 10/10 Step 16802/20000
Param 10/10 Step 16803/20000
Param 10/10 Step 16804/20000
Param 10/10 Step 16805/20000
Param 10/10 Step 16806/20000
Param 10/10 Step 16807/20000
Param 10/10 Step 16808/20000
Param 10/10 Step 16809/20000
Param 10/10 Step 16810/20000
Param 10/10 Step 16811/20000
Param 10/10 Step 16812/20000
Param 10/10 Step 16813/20000
Param 10/10 Step 16814/20000
Param 10/10 Step 16815/20000
Param 10/10 Step 16816/20000
Param 10/10 Step 16817/20000
Param 10/10 Step 16818/20000
Param 10/10 Step 16819/20000
Param 10/10 Step 16820/20000
Param 10/10 Step 16821/20000
Param 10/10 Step 16822/20000
Param 10/10 Step 16823/20000
Param 10/10 Step 16824/20000
Param 10/10 Step 16825/20000
Param 10/10 Step 16826/20000
Param 10/10 Step 16827/20000
Param 10/10 Step 16828/20000
Param 10/10 Step 16829/20000
Param 10/10 Step 16830/20000
Param 10/10 Step 16831/20000
Param 10/10 Step 16832/20000
Param 10/10 Step 16833/20000
Param 10/10 Step 16834/20000
Param 10/10 Step 16835/20000
Param 10/10 Step 16836/20000
Param 10/10 Step 16837/20000
Param 10/10 Step 16838/20000
Param 10/10 Step 16839/20000
Param 10/10 Step 16840/20000
Param 10/10 Step 16841/20000
Param 10/10 Step 16842/20000
Param 10/10 Step 16843/20000
Param 10/10 Step 16844/20000
Param 10/10 Step 16845/20000
Param 10/10 Step 16846/20000
Param 10/10 Step 16847/20000
Param 10/10 Step 16848/20000
Param 10/10 Step 16849/20000
Param 10/10 Step 16850/20000
Param 10/10 Step 16851/20000
Param 10/10 Step 16852/20000
Param 10/10 Step 16853/20000
Param 10/10 Step 16854/20000
Param 10/10 Step 16855/20000
Param 10/10 Step 16856/20000
Param 10/10 Step 16857/20000
Param 10/10 Step 16858/20000
Param 10/10 Step 16859/20000
Param 10/10 Step 16860/20000
Param 10/10 Step 16861/20000
Param 10/10 Step 16862/20000
Param 10/10 Step 16863/20000
Param 10/10 Step 16864/20000
Param 10/10 Step 16865/20000
Param 10/10 Step 16866/20000
Param 10/10 Step 16867/20000
Param 10/10 Step 16868/20000
Param 10/10 Step 16869/20000
Param 10/10 Step 16870/20000
Param 10/10 Step 16871/20000
Param 10/10 Step 16872/20000
Param 10/10 Step 16873/20000
Param 10/10 Step 16874/20000
Param 10/10 Step 16875/20000
Param 10/10 Step 16876/20000
Param 10/10 Step 16877/20000
Param 10/10 Step 16878/20000
Param 10/10 Step 16879/20000
Param 10/10 Step 16880/20000
Param 10/10 Step 16881/20000
Param 10/10 Step 16882/20000
Param 10/10 Step 16883/20000
Param 10/10 Step 16884/20000
Param 10/10 Step 16885/20000
Param 10/10 Step 16886/20000
Param 10/10 Step 16887/20000
Param 10/10 Step 16888/20000
Param 10/10 Step 16889/20000
Param 10/10 Step 16890/20000
Param 10/10 Step 16891/20000
Param 10/10 Step 16892/20000
Param 10/10 Step 16893/20000
Param 10/10 Step 16894/20000
Param 10/10 Step 16895/20000
Param 10/10 Step 16896/20000
Param 10/10 Step 16897/20000
Param 10/10 Step 16898/20000
Param 10/10 Step 16899/20000
Param 10/10 Step 16900/20000
Param 10/10 Step 16901/20000
Param 10/10 Step 16902/20000
Param 10/10 Step 16903/20000
Param 10/10 Step 16904/20000
Param 10/10 Step 16905/20000
Param 10/10 Step 16906/20000
Param 10/10 Step 16907/20000
Param 10/10 Step 16908/20000
Param 10/10 Step 16909/20000
Param 10/10 Step 16910/20000
Param 10/10 Step 16911/20000
Param 10/10 Step 16912/20000
Param 10/10 Step 16913/20000
Param 10/10 Step 16914/20000
Param 10/10 Step 16915/20000
Param 10/10 Step 16916/20000
Param 10/10 Step 16917/20000
Param 10/10 Step 16918/20000
Param 10/10 Step 16919/20000
Param 10/10 Step 16920/20000
Param 10/10 Step 16921/20000
Param 10/10 Step 16922/20000
Param 10/10 Step 16923/20000
Param 10/10 Step 16924/20000
Param 10/10 Step 16925/20000
Param 10/10 Step 16926/20000
Param 10/10 Step 16927/20000
Param 10/10 Step 16928/20000
Param 10/10 Step 16929/20000
Param 10/10 Step 16930/20000
Param 10/10 Step 16931/20000
Param 10/10 Step 16932/20000
Param 10/10 Step 16933/20000
Param 10/10 Step 16934/20000
Param 10/10 Step 16935/20000
Param 10/10 Step 16936/20000
Param 10/10 Step 16937/20000
Param 10/10 Step 16938/20000
Param 10/10 Step 16939/20000
Param 10/10 Step 16940/20000
Param 10/10 Step 16941/20000
Param 10/10 Step 16942/20000
Param 10/10 Step 16943/20000
Param 10/10 Step 16944/20000
Param 10/10 Step 16945/20000
Param 10/10 Step 16946/20000
Param 10/10 Step 16947/20000
Param 10/10 Step 16948/20000
Param 10/10 Step 16949/20000
Param 10/10 Step 16950/20000
Param 10/10 Step 16951/20000
Param 10/10 Step 16952/20000
Param 10/10 Step 16953/20000
Param 10/10 Step 16954/20000
Param 10/10 Step 16955/20000
Param 10/10 Step 16956/20000
Param 10/10 Step 16957/20000
Param 10/10 Step 16958/20000
Param 10/10 Step 16959/20000
Param 10/10 Step 16960/20000
Param 10/10 Step 16961/20000
Param 10/10 Step 16962/20000
Param 10/10 Step 16963/20000
Param 10/10 Step 16964/20000
Param 10/10 Step 16965/20000
Param 10/10 Step 16966/20000
Param 10/10 Step 16967/20000
Param 10/10 Step 16968/20000
Param 10/10 Step 16969/20000
Param 10/10 Step 16970/20000
Param 10/10 Step 16971/20000
Param 10/10 Step 16972/20000
Param 10/10 Step 16973/20000
Param 10/10 Step 16974/20000
Param 10/10 Step 16975/20000
Param 10/10 Step 16976/20000
Param 10/10 Step 16977/20000
Param 10/10 Step 16978/20000
Param 10/10 Step 16979/20000
Param 10/10 Step 16980/20000
Param 10/10 Step 16981/20000
Param 10/10 Step 16982/20000
Param 10/10 Step 16983/20000
Param 10/10 Step 16984/20000
Param 10/10 Step 16985/20000
Param 10/10 Step 16986/20000
Param 10/10 Step 16987/20000
Param 10/10 Step 16988/20000
Param 10/10 Step 16989/20000
Param 10/10 Step 16990/20000
Param 10/10 Step 16991/20000
Param 10/10 Step 16992/20000
Param 10/10 Step 16993/20000
Param 10/10 Step 16994/20000
Param 10/10 Step 16995/20000
Param 10/10 Step 16996/20000
Param 10/10 Step 16997/20000
Param 10/10 Step 16998/20000
Param 10/10 Step 16999/20000
Param 10/10 Step 17000/20000
Param 10/10 Step 17001/20000
Param 10/10 Step 17002/20000
Param 10/10 Step 17003/20000
Param 10/10 Step 17004/20000
Param 10/10 Step 17005/20000
Param 10/10 Step 17006/20000
Param 10/10 Step 17007/20000
Param 10/10 Step 17008/20000
Param 10/10 Step 17009/20000
Param 10/10 Step 17010/20000
Param 10/10 Step 17011/20000
Param 10/10 Step 17012/20000
Param 10/10 Step 17013/20000
Param 10/10 Step 17014/20000
Param 10/10 Step 17015/20000
Param 10/10 Step 17016/20000
Param 10/10 Step 17017/20000
Param 10/10 Step 17018/20000
Param 10/10 Step 17019/20000
Param 10/10 Step 17020/20000
Param 10/10 Step 17021/20000
Param 10/10 Step 17022/20000
Param 10/10 Step 17023/20000
Param 10/10 Step 17024/20000
Param 10/10 Step 17025/20000
Param 10/10 Step 17026/20000
Param 10/10 Step 17027/20000
Param 10/10 Step 17028/20000
Param 10/10 Step 17029/20000
Param 10/10 Step 17030/20000
Param 10/10 Step 17031/20000
Param 10/10 Step 17032/20000
Param 10/10 Step 17033/20000
Param 10/10 Step 17034/20000
Param 10/10 Step 17035/20000
Param 10/10 Step 17036/20000
Param 10/10 Step 17037/20000
Param 10/10 Step 17038/20000
Param 10/10 Step 17039/20000
Param 10/10 Step 17040/20000
Param 10/10 Step 17041/20000
Param 10/10 Step 17042/20000
Param 10/10 Step 17043/20000
Param 10/10 Step 17044/20000
Param 10/10 Step 17045/20000
Param 10/10 Step 17046/20000
Param 10/10 Step 17047/20000
Param 10/10 Step 17048/20000
Param 10/10 Step 17049/20000
Param 10/10 Step 17050/20000
Param 10/10 Step 17051/20000
Param 10/10 Step 17052/20000
Param 10/10 Step 17053/20000
Param 10/10 Step 17054/20000
Param 10/10 Step 17055/20000
Param 10/10 Step 17056/20000
Param 10/10 Step 17057/20000
Param 10/10 Step 17058/20000
Param 10/10 Step 17059/20000
Param 10/10 Step 17060/20000
Param 10/10 Step 17061/20000
Param 10/10 Step 17062/20000
Param 10/10 Step 17063/20000
Param 10/10 Step 17064/20000
Param 10/10 Step 17065/20000
Param 10/10 Step 17066/20000
Param 10/10 Step 17067/20000
Param 10/10 Step 17068/20000
Param 10/10 Step 17069/20000
Param 10/10 Step 17070/20000
Param 10/10 Step 17071/20000
Param 10/10 Step 17072/20000
Param 10/10 Step 17073/20000
Param 10/10 Step 17074/20000
Param 10/10 Step 17075/20000
Param 10/10 Step 17076/20000
Param 10/10 Step 17077/20000
Param 10/10 Step 17078/20000
Param 10/10 Step 17079/20000
Param 10/10 Step 17080/20000
Param 10/10 Step 17081/20000
Param 10/10 Step 17082/20000
Param 10/10 Step 17083/20000
Param 10/10 Step 17084/20000
Param 10/10 Step 17085/20000
Param 10/10 Step 17086/20000
Param 10/10 Step 17087/20000
Param 10/10 Step 17088/20000
Param 10/10 Step 17089/20000
Param 10/10 Step 17090/20000
Param 10/10 Step 17091/20000
Param 10/10 Step 17092/20000
Param 10/10 Step 17093/20000
Param 10/10 Step 17094/20000
Param 10/10 Step 17095/20000
Param 10/10 Step 17096/20000
Param 10/10 Step 17097/20000
Param 10/10 Step 17098/20000
Param 10/10 Step 17099/20000
Param 10/10 Step 17100/20000
Param 10/10 Step 17101/20000
Param 10/10 Step 17102/20000
Param 10/10 Step 17103/20000
Param 10/10 Step 17104/20000
Param 10/10 Step 17105/20000
Param 10/10 Step 17106/20000
Param 10/10 Step 17107/20000
Param 10/10 Step 17108/20000
Param 10/10 Step 17109/20000
Param 10/10 Step 17110/20000
Param 10/10 Step 17111/20000
Param 10/10 Step 17112/20000
Param 10/10 Step 17113/20000
Param 10/10 Step 17114/20000
Param 10/10 Step 17115/20000
Param 10/10 Step 17116/20000
Param 10/10 Step 17117/20000
Param 10/10 Step 17118/20000
Param 10/10 Step 17119/20000
Param 10/10 Step 17120/20000
Param 10/10 Step 17121/20000
Param 10/10 Step 17122/20000
Param 10/10 Step 17123/20000
Param 10/10 Step 17124/20000
Param 10/10 Step 17125/20000
Param 10/10 Step 17126/20000
Param 10/10 Step 17127/20000
Param 10/10 Step 17128/20000
Param 10/10 Step 17129/20000
Param 10/10 Step 17130/20000
Param 10/10 Step 17131/20000
Param 10/10 Step 17132/20000
Param 10/10 Step 17133/20000
Param 10/10 Step 17134/20000
Param 10/10 Step 17135/20000
Param 10/10 Step 17136/20000
Param 10/10 Step 17137/20000
Param 10/10 Step 17138/20000
Param 10/10 Step 17139/20000
Param 10/10 Step 17140/20000
Param 10/10 Step 17141/20000
Param 10/10 Step 17142/20000
Param 10/10 Step 17143/20000
Param 10/10 Step 17144/20000
Param 10/10 Step 17145/20000
Param 10/10 Step 17146/20000
Param 10/10 Step 17147/20000
Param 10/10 Step 17148/20000
Param 10/10 Step 17149/20000
Param 10/10 Step 17150/20000
Param 10/10 Step 17151/20000
Param 10/10 Step 17152/20000
Param 10/10 Step 17153/20000
Param 10/10 Step 17154/20000
Param 10/10 Step 17155/20000
Param 10/10 Step 17156/20000
Param 10/10 Step 17157/20000
Param 10/10 Step 17158/20000
Param 10/10 Step 17159/20000
Param 10/10 Step 17160/20000
Param 10/10 Step 17161/20000
Param 10/10 Step 17162/20000
Param 10/10 Step 17163/20000
Param 10/10 Step 17164/20000
Param 10/10 Step 17165/20000
Param 10/10 Step 17166/20000
Param 10/10 Step 17167/20000
Param 10/10 Step 17168/20000
Param 10/10 Step 17169/20000
Param 10/10 Step 17170/20000
Param 10/10 Step 17171/20000
Param 10/10 Step 17172/20000
Param 10/10 Step 17173/20000
Param 10/10 Step 17174/20000
Param 10/10 Step 17175/20000
Param 10/10 Step 17176/20000
Param 10/10 Step 17177/20000
Param 10/10 Step 17178/20000
Param 10/10 Step 17179/20000
Param 10/10 Step 17180/20000
Param 10/10 Step 17181/20000
Param 10/10 Step 17182/20000
Param 10/10 Step 17183/20000
Param 10/10 Step 17184/20000
Param 10/10 Step 17185/20000
Param 10/10 Step 17186/20000
Param 10/10 Step 17187/20000
Param 10/10 Step 17188/20000
Param 10/10 Step 17189/20000
Param 10/10 Step 17190/20000
Param 10/10 Step 17191/20000
Param 10/10 Step 17192/20000
Param 10/10 Step 17193/20000
Param 10/10 Step 17194/20000
Param 10/10 Step 17195/20000
Param 10/10 Step 17196/20000
Param 10/10 Step 17197/20000
Param 10/10 Step 17198/20000
Param 10/10 Step 17199/20000
Param 10/10 Step 17200/20000
Param 10/10 Step 17201/20000
Param 10/10 Step 17202/20000
Param 10/10 Step 17203/20000
Param 10/10 Step 17204/20000
Param 10/10 Step 17205/20000
Param 10/10 Step 17206/20000
Param 10/10 Step 17207/20000
Param 10/10 Step 17208/20000
Param 10/10 Step 17209/20000
Param 10/10 Step 17210/20000
Param 10/10 Step 17211/20000
Param 10/10 Step 17212/20000
Param 10/10 Step 17213/20000
Param 10/10 Step 17214/20000
Param 10/10 Step 17215/20000
Param 10/10 Step 17216/20000
Param 10/10 Step 17217/20000
Param 10/10 Step 17218/20000
Param 10/10 Step 17219/20000
Param 10/10 Step 17220/20000
Param 10/10 Step 17221/20000
Param 10/10 Step 17222/20000
Param 10/10 Step 17223/20000
Param 10/10 Step 17224/20000
Param 10/10 Step 17225/20000
Param 10/10 Step 17226/20000
Param 10/10 Step 17227/20000
Param 10/10 Step 17228/20000
Param 10/10 Step 17229/20000
Param 10/10 Step 17230/20000
Param 10/10 Step 17231/20000
Param 10/10 Step 17232/20000
Param 10/10 Step 17233/20000
Param 10/10 Step 17234/20000
Param 10/10 Step 17235/20000
Param 10/10 Step 17236/20000
Param 10/10 Step 17237/20000
Param 10/10 Step 17238/20000
Param 10/10 Step 17239/20000
Param 10/10 Step 17240/20000
Param 10/10 Step 17241/20000
Param 10/10 Step 17242/20000
Param 10/10 Step 17243/20000
Param 10/10 Step 17244/20000
Param 10/10 Step 17245/20000
Param 10/10 Step 17246/20000
Param 10/10 Step 17247/20000
Param 10/10 Step 17248/20000
Param 10/10 Step 17249/20000
Param 10/10 Step 17250/20000
Param 10/10 Step 17251/20000
Param 10/10 Step 17252/20000
Param 10/10 Step 17253/20000
Param 10/10 Step 17254/20000
Param 10/10 Step 17255/20000
Param 10/10 Step 17256/20000
Param 10/10 Step 17257/20000
Param 10/10 Step 17258/20000
Param 10/10 Step 17259/20000
Param 10/10 Step 17260/20000
Param 10/10 Step 17261/20000
Param 10/10 Step 17262/20000
Param 10/10 Step 17263/20000
Param 10/10 Step 17264/20000
Param 10/10 Step 17265/20000
Param 10/10 Step 17266/20000
Param 10/10 Step 17267/20000
Param 10/10 Step 17268/20000
Param 10/10 Step 17269/20000
Param 10/10 Step 17270/20000
Param 10/10 Step 17271/20000
Param 10/10 Step 17272/20000
Param 10/10 Step 17273/20000
Param 10/10 Step 17274/20000
Param 10/10 Step 17275/20000
Param 10/10 Step 17276/20000
Param 10/10 Step 17277/20000
Param 10/10 Step 17278/20000
Param 10/10 Step 17279/20000
Param 10/10 Step 17280/20000
Param 10/10 Step 17281/20000
Param 10/10 Step 17282/20000
Param 10/10 Step 17283/20000
Param 10/10 Step 17284/20000
Param 10/10 Step 17285/20000
Param 10/10 Step 17286/20000
Param 10/10 Step 17287/20000
Param 10/10 Step 17288/20000
Param 10/10 Step 17289/20000
Param 10/10 Step 17290/20000
Param 10/10 Step 17291/20000
Param 10/10 Step 17292/20000
Param 10/10 Step 17293/20000
Param 10/10 Step 17294/20000
Param 10/10 Step 17295/20000
Param 10/10 Step 17296/20000
Param 10/10 Step 17297/20000
Param 10/10 Step 17298/20000
Param 10/10 Step 17299/20000
Param 10/10 Step 17300/20000
Param 10/10 Step 17301/20000
Param 10/10 Step 17302/20000
Param 10/10 Step 17303/20000
Param 10/10 Step 17304/20000
Param 10/10 Step 17305/20000
Param 10/10 Step 17306/20000
Param 10/10 Step 17307/20000
Param 10/10 Step 17308/20000
Param 10/10 Step 17309/20000
Param 10/10 Step 17310/20000
Param 10/10 Step 17311/20000
Param 10/10 Step 17312/20000
Param 10/10 Step 17313/20000
Param 10/10 Step 17314/20000
Param 10/10 Step 17315/20000
Param 10/10 Step 17316/20000
Param 10/10 Step 17317/20000
Param 10/10 Step 17318/20000
Param 10/10 Step 17319/20000
Param 10/10 Step 17320/20000
Param 10/10 Step 17321/20000
Param 10/10 Step 17322/20000
Param 10/10 Step 17323/20000
Param 10/10 Step 17324/20000
Param 10/10 Step 17325/20000
Param 10/10 Step 17326/20000
Param 10/10 Step 17327/20000
Param 10/10 Step 17328/20000
Param 10/10 Step 17329/20000
Param 10/10 Step 17330/20000
Param 10/10 Step 17331/20000
Param 10/10 Step 17332/20000
Param 10/10 Step 17333/20000
Param 10/10 Step 17334/20000
Param 10/10 Step 17335/20000
Param 10/10 Step 17336/20000
Param 10/10 Step 17337/20000
Param 10/10 Step 17338/20000
Param 10/10 Step 17339/20000
Param 10/10 Step 17340/20000
Param 10/10 Step 17341/20000
Param 10/10 Step 17342/20000
Param 10/10 Step 17343/20000
Param 10/10 Step 17344/20000
Param 10/10 Step 17345/20000
Param 10/10 Step 17346/20000
Param 10/10 Step 17347/20000
Param 10/10 Step 17348/20000
Param 10/10 Step 17349/20000
Param 10/10 Step 17350/20000
Param 10/10 Step 17351/20000
Param 10/10 Step 17352/20000
Param 10/10 Step 17353/20000
Param 10/10 Step 17354/20000
Param 10/10 Step 17355/20000
Param 10/10 Step 17356/20000
Param 10/10 Step 17357/20000
Param 10/10 Step 17358/20000
Param 10/10 Step 17359/20000
Param 10/10 Step 17360/20000
Param 10/10 Step 17361/20000
Param 10/10 Step 17362/20000
Param 10/10 Step 17363/20000
Param 10/10 Step 17364/20000
Param 10/10 Step 17365/20000
Param 10/10 Step 17366/20000
Param 10/10 Step 17367/20000
Param 10/10 Step 17368/20000
Param 10/10 Step 17369/20000
Param 10/10 Step 17370/20000
Param 10/10 Step 17371/20000
Param 10/10 Step 17372/20000
Param 10/10 Step 17373/20000
Param 10/10 Step 17374/20000
Param 10/10 Step 17375/20000
Param 10/10 Step 17376/20000
Param 10/10 Step 17377/20000
Param 10/10 Step 17378/20000
Param 10/10 Step 17379/20000
Param 10/10 Step 17380/20000
Param 10/10 Step 17381/20000
Param 10/10 Step 17382/20000
Param 10/10 Step 17383/20000
Param 10/10 Step 17384/20000
Param 10/10 Step 17385/20000
Param 10/10 Step 17386/20000
Param 10/10 Step 17387/20000
Param 10/10 Step 17388/20000
Param 10/10 Step 17389/20000
Param 10/10 Step 17390/20000
Param 10/10 Step 17391/20000
Param 10/10 Step 17392/20000
Param 10/10 Step 17393/20000
Param 10/10 Step 17394/20000
Param 10/10 Step 17395/20000
Param 10/10 Step 17396/20000
Param 10/10 Step 17397/20000
Param 10/10 Step 17398/20000
Param 10/10 Step 17399/20000
Param 10/10 Step 17400/20000
Param 10/10 Step 17401/20000
Param 10/10 Step 17402/20000
Param 10/10 Step 17403/20000
Param 10/10 Step 17404/20000
Param 10/10 Step 17405/20000
Param 10/10 Step 17406/20000
Param 10/10 Step 17407/20000
Param 10/10 Step 17408/20000
Param 10/10 Step 17409/20000
Param 10/10 Step 17410/20000
Param 10/10 Step 17411/20000
Param 10/10 Step 17412/20000
Param 10/10 Step 17413/20000
Param 10/10 Step 17414/20000
Param 10/10 Step 17415/20000
Param 10/10 Step 17416/20000
Param 10/10 Step 17417/20000
Param 10/10 Step 17418/20000
Param 10/10 Step 17419/20000
Param 10/10 Step 17420/20000
Param 10/10 Step 17421/20000
Param 10/10 Step 17422/20000
Param 10/10 Step 17423/20000
Param 10/10 Step 17424/20000
Param 10/10 Step 17425/20000
Param 10/10 Step 17426/20000
Param 10/10 Step 17427/20000
Param 10/10 Step 17428/20000
Param 10/10 Step 17429/20000
Param 10/10 Step 17430/20000
Param 10/10 Step 17431/20000
Param 10/10 Step 17432/20000
Param 10/10 Step 17433/20000
Param 10/10 Step 17434/20000
Param 10/10 Step 17435/20000
Param 10/10 Step 17436/20000
Param 10/10 Step 17437/20000
Param 10/10 Step 17438/20000
Param 10/10 Step 17439/20000
Param 10/10 Step 17440/20000
Param 10/10 Step 17441/20000
Param 10/10 Step 17442/20000
Param 10/10 Step 17443/20000
Param 10/10 Step 17444/20000
Param 10/10 Step 17445/20000
Param 10/10 Step 17446/20000
Param 10/10 Step 17447/20000
Param 10/10 Step 17448/20000
Param 10/10 Step 17449/20000
Param 10/10 Step 17450/20000
Param 10/10 Step 17451/20000
Param 10/10 Step 17452/20000
Param 10/10 Step 17453/20000
Param 10/10 Step 17454/20000
Param 10/10 Step 17455/20000
Param 10/10 Step 17456/20000
Param 10/10 Step 17457/20000
Param 10/10 Step 17458/20000
Param 10/10 Step 17459/20000
Param 10/10 Step 17460/20000
Param 10/10 Step 17461/20000
Param 10/10 Step 17462/20000
Param 10/10 Step 17463/20000
Param 10/10 Step 17464/20000
Param 10/10 Step 17465/20000
Param 10/10 Step 17466/20000
Param 10/10 Step 17467/20000
Param 10/10 Step 17468/20000
Param 10/10 Step 17469/20000
Param 10/10 Step 17470/20000
Param 10/10 Step 17471/20000
Param 10/10 Step 17472/20000
Param 10/10 Step 17473/20000
Param 10/10 Step 17474/20000
Param 10/10 Step 17475/20000
Param 10/10 Step 17476/20000
Param 10/10 Step 17477/20000
Param 10/10 Step 17478/20000
Param 10/10 Step 17479/20000
Param 10/10 Step 17480/20000
Param 10/10 Step 17481/20000
Param 10/10 Step 17482/20000
Param 10/10 Step 17483/20000
Param 10/10 Step 17484/20000
Param 10/10 Step 17485/20000
Param 10/10 Step 17486/20000
Param 10/10 Step 17487/20000
Param 10/10 Step 17488/20000
Param 10/10 Step 17489/20000
Param 10/10 Step 17490/20000
Param 10/10 Step 17491/20000
Param 10/10 Step 17492/20000
Param 10/10 Step 17493/20000
Param 10/10 Step 17494/20000
Param 10/10 Step 17495/20000
Param 10/10 Step 17496/20000
Param 10/10 Step 17497/20000
Param 10/10 Step 17498/20000
Param 10/10 Step 17499/20000
Param 10/10 Step 17500/20000
Param 10/10 Step 17501/20000
Param 10/10 Step 17502/20000
Param 10/10 Step 17503/20000
Param 10/10 Step 17504/20000
Param 10/10 Step 17505/20000
Param 10/10 Step 17506/20000
Param 10/10 Step 17507/20000
Param 10/10 Step 17508/20000
Param 10/10 Step 17509/20000
Param 10/10 Step 17510/20000
Param 10/10 Step 17511/20000
Param 10/10 Step 17512/20000
Param 10/10 Step 17513/20000
Param 10/10 Step 17514/20000
Param 10/10 Step 17515/20000
Param 10/10 Step 17516/20000
Param 10/10 Step 17517/20000
Param 10/10 Step 17518/20000
Param 10/10 Step 17519/20000
Param 10/10 Step 17520/20000
Param 10/10 Step 17521/20000
Param 10/10 Step 17522/20000
Param 10/10 Step 17523/20000
Param 10/10 Step 17524/20000
Param 10/10 Step 17525/20000
Param 10/10 Step 17526/20000
Param 10/10 Step 17527/20000
Param 10/10 Step 17528/20000
Param 10/10 Step 17529/20000
Param 10/10 Step 17530/20000
Param 10/10 Step 17531/20000
Param 10/10 Step 17532/20000
Param 10/10 Step 17533/20000
Param 10/10 Step 17534/20000
Param 10/10 Step 17535/20000
Param 10/10 Step 17536/20000
Param 10/10 Step 17537/20000
Param 10/10 Step 17538/20000
Param 10/10 Step 17539/20000
Param 10/10 Step 17540/20000
Param 10/10 Step 17541/20000
Param 10/10 Step 17542/20000
Param 10/10 Step 17543/20000
Param 10/10 Step 17544/20000
Param 10/10 Step 17545/20000
Param 10/10 Step 17546/20000
Param 10/10 Step 17547/20000
Param 10/10 Step 17548/20000
Param 10/10 Step 17549/20000
Param 10/10 Step 17550/20000
Param 10/10 Step 17551/20000
Param 10/10 Step 17552/20000
Param 10/10 Step 17553/20000
Param 10/10 Step 17554/20000
Param 10/10 Step 17555/20000
Param 10/10 Step 17556/20000
Param 10/10 Step 17557/20000
Param 10/10 Step 17558/20000
Param 10/10 Step 17559/20000
Param 10/10 Step 17560/20000
Param 10/10 Step 17561/20000
Param 10/10 Step 17562/20000
Param 10/10 Step 17563/20000
Param 10/10 Step 17564/20000
Param 10/10 Step 17565/20000
Param 10/10 Step 17566/20000
Param 10/10 Step 17567/20000
Param 10/10 Step 17568/20000
Param 10/10 Step 17569/20000
Param 10/10 Step 17570/20000
Param 10/10 Step 17571/20000
Param 10/10 Step 17572/20000
Param 10/10 Step 17573/20000
Param 10/10 Step 17574/20000
Param 10/10 Step 17575/20000
Param 10/10 Step 17576/20000
Param 10/10 Step 17577/20000
Param 10/10 Step 17578/20000
Param 10/10 Step 17579/20000
Param 10/10 Step 17580/20000
Param 10/10 Step 17581/20000
Param 10/10 Step 17582/20000
Param 10/10 Step 17583/20000
Param 10/10 Step 17584/20000
Param 10/10 Step 17585/20000
Param 10/10 Step 17586/20000
Param 10/10 Step 17587/20000
Param 10/10 Step 17588/20000
Param 10/10 Step 17589/20000
Param 10/10 Step 17590/20000
Param 10/10 Step 17591/20000
Param 10/10 Step 17592/20000
Param 10/10 Step 17593/20000
Param 10/10 Step 17594/20000
Param 10/10 Step 17595/20000
Param 10/10 Step 17596/20000
Param 10/10 Step 17597/20000
Param 10/10 Step 17598/20000
Param 10/10 Step 17599/20000
Param 10/10 Step 17600/20000
Param 10/10 Step 17601/20000
Param 10/10 Step 17602/20000
Param 10/10 Step 17603/20000
Param 10/10 Step 17604/20000
Param 10/10 Step 17605/20000
Param 10/10 Step 17606/20000
Param 10/10 Step 17607/20000
Param 10/10 Step 17608/20000
Param 10/10 Step 17609/20000
Param 10/10 Step 17610/20000
Param 10/10 Step 17611/20000
Param 10/10 Step 17612/20000
Param 10/10 Step 17613/20000
Param 10/10 Step 17614/20000
Param 10/10 Step 17615/20000
Param 10/10 Step 17616/20000
Param 10/10 Step 17617/20000
Param 10/10 Step 17618/20000
Param 10/10 Step 17619/20000
Param 10/10 Step 17620/20000
Param 10/10 Step 17621/20000
Param 10/10 Step 17622/20000
Param 10/10 Step 17623/20000
Param 10/10 Step 17624/20000
Param 10/10 Step 17625/20000
Param 10/10 Step 17626/20000
Param 10/10 Step 17627/20000
Param 10/10 Step 17628/20000
Param 10/10 Step 17629/20000
Param 10/10 Step 17630/20000
Param 10/10 Step 17631/20000
Param 10/10 Step 17632/20000
Param 10/10 Step 17633/20000
Param 10/10 Step 17634/20000
Param 10/10 Step 17635/20000
Param 10/10 Step 17636/20000
Param 10/10 Step 17637/20000
Param 10/10 Step 17638/20000
Param 10/10 Step 17639/20000
Param 10/10 Step 17640/20000
Param 10/10 Step 17641/20000
Param 10/10 Step 17642/20000
Param 10/10 Step 17643/20000
Param 10/10 Step 17644/20000
Param 10/10 Step 17645/20000
Param 10/10 Step 17646/20000
Param 10/10 Step 17647/20000
Param 10/10 Step 17648/20000
Param 10/10 Step 17649/20000
Param 10/10 Step 17650/20000
Param 10/10 Step 17651/20000
Param 10/10 Step 17652/20000
Param 10/10 Step 17653/20000
Param 10/10 Step 17654/20000
Param 10/10 Step 17655/20000
Param 10/10 Step 17656/20000
Param 10/10 Step 17657/20000
Param 10/10 Step 17658/20000
Param 10/10 Step 17659/20000
Param 10/10 Step 17660/20000
Param 10/10 Step 17661/20000
Param 10/10 Step 17662/20000
Param 10/10 Step 17663/20000
Param 10/10 Step 17664/20000
Param 10/10 Step 17665/20000
Param 10/10 Step 17666/20000
Param 10/10 Step 17667/20000
Param 10/10 Step 17668/20000
Param 10/10 Step 17669/20000
Param 10/10 Step 17670/20000
Param 10/10 Step 17671/20000
Param 10/10 Step 17672/20000
Param 10/10 Step 17673/20000
Param 10/10 Step 17674/20000
Param 10/10 Step 17675/20000
Param 10/10 Step 17676/20000
Param 10/10 Step 17677/20000
Param 10/10 Step 17678/20000
Param 10/10 Step 17679/20000
Param 10/10 Step 17680/20000
Param 10/10 Step 17681/20000
Param 10/10 Step 17682/20000
Param 10/10 Step 17683/20000
Param 10/10 Step 17684/20000
Param 10/10 Step 17685/20000
Param 10/10 Step 17686/20000
Param 10/10 Step 17687/20000
Param 10/10 Step 17688/20000
Param 10/10 Step 17689/20000
Param 10/10 Step 17690/20000
Param 10/10 Step 17691/20000
Param 10/10 Step 17692/20000
Param 10/10 Step 17693/20000
Param 10/10 Step 17694/20000
Param 10/10 Step 17695/20000
Param 10/10 Step 17696/20000
Param 10/10 Step 17697/20000
Param 10/10 Step 17698/20000
Param 10/10 Step 17699/20000
Param 10/10 Step 17700/20000
Param 10/10 Step 17701/20000
Param 10/10 Step 17702/20000
Param 10/10 Step 17703/20000
Param 10/10 Step 17704/20000
Param 10/10 Step 17705/20000
Param 10/10 Step 17706/20000
Param 10/10 Step 17707/20000
Param 10/10 Step 17708/20000
Param 10/10 Step 17709/20000
Param 10/10 Step 17710/20000
Param 10/10 Step 17711/20000
Param 10/10 Step 17712/20000
Param 10/10 Step 17713/20000
Param 10/10 Step 17714/20000
Param 10/10 Step 17715/20000
Param 10/10 Step 17716/20000
Param 10/10 Step 17717/20000
Param 10/10 Step 17718/20000
Param 10/10 Step 17719/20000
Param 10/10 Step 17720/20000
Param 10/10 Step 17721/20000
Param 10/10 Step 17722/20000
Param 10/10 Step 17723/20000
Param 10/10 Step 17724/20000
Param 10/10 Step 17725/20000
Param 10/10 Step 17726/20000
Param 10/10 Step 17727/20000
Param 10/10 Step 17728/20000
Param 10/10 Step 17729/20000
Param 10/10 Step 17730/20000
Param 10/10 Step 17731/20000
Param 10/10 Step 17732/20000
Param 10/10 Step 17733/20000
Param 10/10 Step 17734/20000
Param 10/10 Step 17735/20000
Param 10/10 Step 17736/20000
Param 10/10 Step 17737/20000
Param 10/10 Step 17738/20000
Param 10/10 Step 17739/20000
Param 10/10 Step 17740/20000
Param 10/10 Step 17741/20000
Param 10/10 Step 17742/20000
Param 10/10 Step 17743/20000
Param 10/10 Step 17744/20000
Param 10/10 Step 17745/20000
Param 10/10 Step 17746/20000
Param 10/10 Step 17747/20000
Param 10/10 Step 17748/20000
Param 10/10 Step 17749/20000
Param 10/10 Step 17750/20000
Param 10/10 Step 17751/20000
Param 10/10 Step 17752/20000
Param 10/10 Step 17753/20000
Param 10/10 Step 17754/20000
Param 10/10 Step 17755/20000
Param 10/10 Step 17756/20000
Param 10/10 Step 17757/20000
Param 10/10 Step 17758/20000
Param 10/10 Step 17759/20000
Param 10/10 Step 17760/20000
Param 10/10 Step 17761/20000
Param 10/10 Step 17762/20000
Param 10/10 Step 17763/20000
Param 10/10 Step 17764/20000
Param 10/10 Step 17765/20000
Param 10/10 Step 17766/20000
Param 10/10 Step 17767/20000
Param 10/10 Step 17768/20000
Param 10/10 Step 17769/20000
Param 10/10 Step 17770/20000
Param 10/10 Step 17771/20000
Param 10/10 Step 17772/20000
Param 10/10 Step 17773/20000
Param 10/10 Step 17774/20000
Param 10/10 Step 17775/20000
Param 10/10 Step 17776/20000
Param 10/10 Step 17777/20000
Param 10/10 Step 17778/20000
Param 10/10 Step 17779/20000
Param 10/10 Step 17780/20000
Param 10/10 Step 17781/20000
Param 10/10 Step 17782/20000
Param 10/10 Step 17783/20000
Param 10/10 Step 17784/20000
Param 10/10 Step 17785/20000
Param 10/10 Step 17786/20000
Param 10/10 Step 17787/20000
Param 10/10 Step 17788/20000
Param 10/10 Step 17789/20000
Param 10/10 Step 17790/20000
Param 10/10 Step 17791/20000
Param 10/10 Step 17792/20000
Param 10/10 Step 17793/20000
Param 10/10 Step 17794/20000
Param 10/10 Step 17795/20000
Param 10/10 Step 17796/20000
Param 10/10 Step 17797/20000
Param 10/10 Step 17798/20000
Param 10/10 Step 17799/20000
Param 10/10 Step 17800/20000
Param 10/10 Step 17801/20000
Param 10/10 Step 17802/20000
Param 10/10 Step 17803/20000
Param 10/10 Step 17804/20000
Param 10/10 Step 17805/20000
Param 10/10 Step 17806/20000
Param 10/10 Step 17807/20000
Param 10/10 Step 17808/20000
Param 10/10 Step 17809/20000
Param 10/10 Step 17810/20000
Param 10/10 Step 17811/20000
Param 10/10 Step 17812/20000
Param 10/10 Step 17813/20000
Param 10/10 Step 17814/20000
Param 10/10 Step 17815/20000
Param 10/10 Step 17816/20000
Param 10/10 Step 17817/20000
Param 10/10 Step 17818/20000
Param 10/10 Step 17819/20000
Param 10/10 Step 17820/20000
Param 10/10 Step 17821/20000
Param 10/10 Step 17822/20000
Param 10/10 Step 17823/20000
Param 10/10 Step 17824/20000
Param 10/10 Step 17825/20000
Param 10/10 Step 17826/20000
Param 10/10 Step 17827/20000
Param 10/10 Step 17828/20000
Param 10/10 Step 17829/20000
Param 10/10 Step 17830/20000
Param 10/10 Step 17831/20000
Param 10/10 Step 17832/20000
Param 10/10 Step 17833/20000
Param 10/10 Step 17834/20000
Param 10/10 Step 17835/20000
Param 10/10 Step 17836/20000
Param 10/10 Step 17837/20000
Param 10/10 Step 17838/20000
Param 10/10 Step 17839/20000
Param 10/10 Step 17840/20000
Param 10/10 Step 17841/20000
Param 10/10 Step 17842/20000
Param 10/10 Step 17843/20000
Param 10/10 Step 17844/20000
Param 10/10 Step 17845/20000
Param 10/10 Step 17846/20000
Param 10/10 Step 17847/20000
Param 10/10 Step 17848/20000
Param 10/10 Step 17849/20000
Param 10/10 Step 17850/20000
Param 10/10 Step 17851/20000
Param 10/10 Step 17852/20000
Param 10/10 Step 17853/20000
Param 10/10 Step 17854/20000
Param 10/10 Step 17855/20000
Param 10/10 Step 17856/20000
Param 10/10 Step 17857/20000
Param 10/10 Step 17858/20000
Param 10/10 Step 17859/20000
Param 10/10 Step 17860/20000
Param 10/10 Step 17861/20000
Param 10/10 Step 17862/20000
Param 10/10 Step 17863/20000
Param 10/10 Step 17864/20000
Param 10/10 Step 17865/20000
Param 10/10 Step 17866/20000
Param 10/10 Step 17867/20000
Param 10/10 Step 17868/20000
Param 10/10 Step 17869/20000
Param 10/10 Step 17870/20000
Param 10/10 Step 17871/20000
Param 10/10 Step 17872/20000
Param 10/10 Step 17873/20000
Param 10/10 Step 17874/20000
Param 10/10 Step 17875/20000
Param 10/10 Step 17876/20000
Param 10/10 Step 17877/20000
Param 10/10 Step 17878/20000
Param 10/10 Step 17879/20000
Param 10/10 Step 17880/20000
Param 10/10 Step 17881/20000
Param 10/10 Step 17882/20000
Param 10/10 Step 17883/20000
Param 10/10 Step 17884/20000
Param 10/10 Step 17885/20000
Param 10/10 Step 17886/20000
Param 10/10 Step 17887/20000
Param 10/10 Step 17888/20000
Param 10/10 Step 17889/20000
Param 10/10 Step 17890/20000
Param 10/10 Step 17891/20000
Param 10/10 Step 17892/20000
Param 10/10 Step 17893/20000
Param 10/10 Step 17894/20000
Param 10/10 Step 17895/20000
Param 10/10 Step 17896/20000
Param 10/10 Step 17897/20000
Param 10/10 Step 17898/20000
Param 10/10 Step 17899/20000
Param 10/10 Step 17900/20000
Param 10/10 Step 17901/20000
Param 10/10 Step 17902/20000
Param 10/10 Step 17903/20000
Param 10/10 Step 17904/20000
Param 10/10 Step 17905/20000
Param 10/10 Step 17906/20000
Param 10/10 Step 17907/20000
Param 10/10 Step 17908/20000
Param 10/10 Step 17909/20000
Param 10/10 Step 17910/20000
Param 10/10 Step 17911/20000
Param 10/10 Step 17912/20000
Param 10/10 Step 17913/20000
Param 10/10 Step 17914/20000
Param 10/10 Step 17915/20000
Param 10/10 Step 17916/20000
Param 10/10 Step 17917/20000
Param 10/10 Step 17918/20000
Param 10/10 Step 17919/20000
Param 10/10 Step 17920/20000
Param 10/10 Step 17921/20000
Param 10/10 Step 17922/20000
Param 10/10 Step 17923/20000
Param 10/10 Step 17924/20000
Param 10/10 Step 17925/20000
Param 10/10 Step 17926/20000
Param 10/10 Step 17927/20000
Param 10/10 Step 17928/20000
Param 10/10 Step 17929/20000
Param 10/10 Step 17930/20000
Param 10/10 Step 17931/20000
Param 10/10 Step 17932/20000
Param 10/10 Step 17933/20000
Param 10/10 Step 17934/20000
Param 10/10 Step 17935/20000
Param 10/10 Step 17936/20000
Param 10/10 Step 17937/20000
Param 10/10 Step 17938/20000
Param 10/10 Step 17939/20000
Param 10/10 Step 17940/20000
Param 10/10 Step 17941/20000
Param 10/10 Step 17942/20000
Param 10/10 Step 17943/20000
Param 10/10 Step 17944/20000
Param 10/10 Step 17945/20000
Param 10/10 Step 17946/20000
Param 10/10 Step 17947/20000
Param 10/10 Step 17948/20000
Param 10/10 Step 17949/20000
Param 10/10 Step 17950/20000
Param 10/10 Step 17951/20000
Param 10/10 Step 17952/20000
Param 10/10 Step 17953/20000
Param 10/10 Step 17954/20000
Param 10/10 Step 17955/20000
Param 10/10 Step 17956/20000
Param 10/10 Step 17957/20000
Param 10/10 Step 17958/20000
Param 10/10 Step 17959/20000
Param 10/10 Step 17960/20000
Param 10/10 Step 17961/20000
Param 10/10 Step 17962/20000
Param 10/10 Step 17963/20000
Param 10/10 Step 17964/20000
Param 10/10 Step 17965/20000
Param 10/10 Step 17966/20000
Param 10/10 Step 17967/20000
Param 10/10 Step 17968/20000
Param 10/10 Step 17969/20000
Param 10/10 Step 17970/20000
Param 10/10 Step 17971/20000
Param 10/10 Step 17972/20000
Param 10/10 Step 17973/20000
Param 10/10 Step 17974/20000
Param 10/10 Step 17975/20000
Param 10/10 Step 17976/20000
Param 10/10 Step 17977/20000
Param 10/10 Step 17978/20000
Param 10/10 Step 17979/20000
Param 10/10 Step 17980/20000
Param 10/10 Step 17981/20000
Param 10/10 Step 17982/20000
Param 10/10 Step 17983/20000
Param 10/10 Step 17984/20000
Param 10/10 Step 17985/20000
Param 10/10 Step 17986/20000
Param 10/10 Step 17987/20000
Param 10/10 Step 17988/20000
Param 10/10 Step 17989/20000
Param 10/10 Step 17990/20000
Param 10/10 Step 17991/20000
Param 10/10 Step 17992/20000
Param 10/10 Step 17993/20000
Param 10/10 Step 17994/20000
Param 10/10 Step 17995/20000
Param 10/10 Step 17996/20000
Param 10/10 Step 17997/20000
Param 10/10 Step 17998/20000
Param 10/10 Step 17999/20000
Param 10/10 Step 18000/20000
Param 10/10 Step 18001/20000
Param 10/10 Step 18002/20000
Param 10/10 Step 18003/20000
Param 10/10 Step 18004/20000
Param 10/10 Step 18005/20000
Param 10/10 Step 18006/20000
Param 10/10 Step 18007/20000
Param 10/10 Step 18008/20000
Param 10/10 Step 18009/20000
Param 10/10 Step 18010/20000
Param 10/10 Step 18011/20000
Param 10/10 Step 18012/20000
Param 10/10 Step 18013/20000
Param 10/10 Step 18014/20000
Param 10/10 Step 18015/20000
Param 10/10 Step 18016/20000
Param 10/10 Step 18017/20000
Param 10/10 Step 18018/20000
Param 10/10 Step 18019/20000
Param 10/10 Step 18020/20000
Param 10/10 Step 18021/20000
Param 10/10 Step 18022/20000
Param 10/10 Step 18023/20000
Param 10/10 Step 18024/20000
Param 10/10 Step 18025/20000
Param 10/10 Step 18026/20000
Param 10/10 Step 18027/20000
Param 10/10 Step 18028/20000
Param 10/10 Step 18029/20000
Param 10/10 Step 18030/20000
Param 10/10 Step 18031/20000
Param 10/10 Step 18032/20000
Param 10/10 Step 18033/20000
Param 10/10 Step 18034/20000
Param 10/10 Step 18035/20000
Param 10/10 Step 18036/20000
Param 10/10 Step 18037/20000
Param 10/10 Step 18038/20000
Param 10/10 Step 18039/20000
Param 10/10 Step 18040/20000
Param 10/10 Step 18041/20000
Param 10/10 Step 18042/20000
Param 10/10 Step 18043/20000
Param 10/10 Step 18044/20000
Param 10/10 Step 18045/20000
Param 10/10 Step 18046/20000
Param 10/10 Step 18047/20000
Param 10/10 Step 18048/20000
Param 10/10 Step 18049/20000
Param 10/10 Step 18050/20000
Param 10/10 Step 18051/20000
Param 10/10 Step 18052/20000
Param 10/10 Step 18053/20000
Param 10/10 Step 18054/20000
Param 10/10 Step 18055/20000
Param 10/10 Step 18056/20000
Param 10/10 Step 18057/20000
Param 10/10 Step 18058/20000
Param 10/10 Step 18059/20000
Param 10/10 Step 18060/20000
Param 10/10 Step 18061/20000
Param 10/10 Step 18062/20000
Param 10/10 Step 18063/20000
Param 10/10 Step 18064/20000
Param 10/10 Step 18065/20000
Param 10/10 Step 18066/20000
Param 10/10 Step 18067/20000
Param 10/10 Step 18068/20000
Param 10/10 Step 18069/20000
Param 10/10 Step 18070/20000
Param 10/10 Step 18071/20000
Param 10/10 Step 18072/20000
Param 10/10 Step 18073/20000
Param 10/10 Step 18074/20000
Param 10/10 Step 18075/20000
Param 10/10 Step 18076/20000
Param 10/10 Step 18077/20000
Param 10/10 Step 18078/20000
Param 10/10 Step 18079/20000
Param 10/10 Step 18080/20000
Param 10/10 Step 18081/20000
Param 10/10 Step 18082/20000
Param 10/10 Step 18083/20000
Param 10/10 Step 18084/20000
Param 10/10 Step 18085/20000
Param 10/10 Step 18086/20000
Param 10/10 Step 18087/20000
Param 10/10 Step 18088/20000
Param 10/10 Step 18089/20000
Param 10/10 Step 18090/20000
Param 10/10 Step 18091/20000
Param 10/10 Step 18092/20000
Param 10/10 Step 18093/20000
Param 10/10 Step 18094/20000
Param 10/10 Step 18095/20000
Param 10/10 Step 18096/20000
Param 10/10 Step 18097/20000
Param 10/10 Step 18098/20000
Param 10/10 Step 18099/20000
Param 10/10 Step 18100/20000
Param 10/10 Step 18101/20000
Param 10/10 Step 18102/20000
Param 10/10 Step 18103/20000
Param 10/10 Step 18104/20000
Param 10/10 Step 18105/20000
Param 10/10 Step 18106/20000
Param 10/10 Step 18107/20000
Param 10/10 Step 18108/20000
Param 10/10 Step 18109/20000
Param 10/10 Step 18110/20000
Param 10/10 Step 18111/20000
Param 10/10 Step 18112/20000
Param 10/10 Step 18113/20000
Param 10/10 Step 18114/20000
Param 10/10 Step 18115/20000
Param 10/10 Step 18116/20000
Param 10/10 Step 18117/20000
Param 10/10 Step 18118/20000
Param 10/10 Step 18119/20000
Param 10/10 Step 18120/20000
Param 10/10 Step 18121/20000
Param 10/10 Step 18122/20000
Param 10/10 Step 18123/20000
Param 10/10 Step 18124/20000
Param 10/10 Step 18125/20000
Param 10/10 Step 18126/20000
Param 10/10 Step 18127/20000
Param 10/10 Step 18128/20000
Param 10/10 Step 18129/20000
Param 10/10 Step 18130/20000
Param 10/10 Step 18131/20000
Param 10/10 Step 18132/20000
Param 10/10 Step 18133/20000
Param 10/10 Step 18134/20000
Param 10/10 Step 18135/20000
Param 10/10 Step 18136/20000
Param 10/10 Step 18137/20000
Param 10/10 Step 18138/20000
Param 10/10 Step 18139/20000
Param 10/10 Step 18140/20000
Param 10/10 Step 18141/20000
Param 10/10 Step 18142/20000
Param 10/10 Step 18143/20000
Param 10/10 Step 18144/20000
Param 10/10 Step 18145/20000
Param 10/10 Step 18146/20000
Param 10/10 Step 18147/20000
Param 10/10 Step 18148/20000
Param 10/10 Step 18149/20000
Param 10/10 Step 18150/20000
Param 10/10 Step 18151/20000
Param 10/10 Step 18152/20000
Param 10/10 Step 18153/20000
Param 10/10 Step 18154/20000
Param 10/10 Step 18155/20000
Param 10/10 Step 18156/20000
Param 10/10 Step 18157/20000
Param 10/10 Step 18158/20000
Param 10/10 Step 18159/20000
Param 10/10 Step 18160/20000
Param 10/10 Step 18161/20000
Param 10/10 Step 18162/20000
Param 10/10 Step 18163/20000
Param 10/10 Step 18164/20000
Param 10/10 Step 18165/20000
Param 10/10 Step 18166/20000
Param 10/10 Step 18167/20000
Param 10/10 Step 18168/20000
Param 10/10 Step 18169/20000
Param 10/10 Step 18170/20000
Param 10/10 Step 18171/20000
Param 10/10 Step 18172/20000
Param 10/10 Step 18173/20000
Param 10/10 Step 18174/20000
Param 10/10 Step 18175/20000
Param 10/10 Step 18176/20000
Param 10/10 Step 18177/20000
Param 10/10 Step 18178/20000
Param 10/10 Step 18179/20000
Param 10/10 Step 18180/20000
Param 10/10 Step 18181/20000
Param 10/10 Step 18182/20000
Param 10/10 Step 18183/20000
Param 10/10 Step 18184/20000
Param 10/10 Step 18185/20000
Param 10/10 Step 18186/20000
Param 10/10 Step 18187/20000
Param 10/10 Step 18188/20000
Param 10/10 Step 18189/20000
Param 10/10 Step 18190/20000
Param 10/10 Step 18191/20000
Param 10/10 Step 18192/20000
Param 10/10 Step 18193/20000
Param 10/10 Step 18194/20000
Param 10/10 Step 18195/20000
Param 10/10 Step 18196/20000
Param 10/10 Step 18197/20000
Param 10/10 Step 18198/20000
Param 10/10 Step 18199/20000
Param 10/10 Step 18200/20000
Param 10/10 Step 18201/20000
Param 10/10 Step 18202/20000
Param 10/10 Step 18203/20000
Param 10/10 Step 18204/20000
Param 10/10 Step 18205/20000
Param 10/10 Step 18206/20000
Param 10/10 Step 18207/20000
Param 10/10 Step 18208/20000
Param 10/10 Step 18209/20000
Param 10/10 Step 18210/20000
Param 10/10 Step 18211/20000
Param 10/10 Step 18212/20000
Param 10/10 Step 18213/20000
Param 10/10 Step 18214/20000
Param 10/10 Step 18215/20000
Param 10/10 Step 18216/20000
Param 10/10 Step 18217/20000
Param 10/10 Step 18218/20000
Param 10/10 Step 18219/20000
Param 10/10 Step 18220/20000
Param 10/10 Step 18221/20000
Param 10/10 Step 18222/20000
Param 10/10 Step 18223/20000
Param 10/10 Step 18224/20000
Param 10/10 Step 18225/20000
Param 10/10 Step 18226/20000
Param 10/10 Step 18227/20000
Param 10/10 Step 18228/20000
Param 10/10 Step 18229/20000
Param 10/10 Step 18230/20000
Param 10/10 Step 18231/20000
Param 10/10 Step 18232/20000
Param 10/10 Step 18233/20000
Param 10/10 Step 18234/20000
Param 10/10 Step 18235/20000
Param 10/10 Step 18236/20000
Param 10/10 Step 18237/20000
Param 10/10 Step 18238/20000
Param 10/10 Step 18239/20000
Param 10/10 Step 18240/20000
Param 10/10 Step 18241/20000
Param 10/10 Step 18242/20000
Param 10/10 Step 18243/20000
Param 10/10 Step 18244/20000
Param 10/10 Step 18245/20000
Param 10/10 Step 18246/20000
Param 10/10 Step 18247/20000
Param 10/10 Step 18248/20000
Param 10/10 Step 18249/20000
Param 10/10 Step 18250/20000
Param 10/10 Step 18251/20000
Param 10/10 Step 18252/20000
Param 10/10 Step 18253/20000
Param 10/10 Step 18254/20000
Param 10/10 Step 18255/20000
Param 10/10 Step 18256/20000
Param 10/10 Step 18257/20000
Param 10/10 Step 18258/20000
Param 10/10 Step 18259/20000
Param 10/10 Step 18260/20000
Param 10/10 Step 18261/20000
Param 10/10 Step 18262/20000
Param 10/10 Step 18263/20000
Param 10/10 Step 18264/20000
Param 10/10 Step 18265/20000
Param 10/10 Step 18266/20000
Param 10/10 Step 18267/20000
Param 10/10 Step 18268/20000
Param 10/10 Step 18269/20000
Param 10/10 Step 18270/20000
Param 10/10 Step 18271/20000
Param 10/10 Step 18272/20000
Param 10/10 Step 18273/20000
Param 10/10 Step 18274/20000
Param 10/10 Step 18275/20000
Param 10/10 Step 18276/20000
Param 10/10 Step 18277/20000
Param 10/10 Step 18278/20000
Param 10/10 Step 18279/20000
Param 10/10 Step 18280/20000
Param 10/10 Step 18281/20000
Param 10/10 Step 18282/20000
Param 10/10 Step 18283/20000
Param 10/10 Step 18284/20000
Param 10/10 Step 18285/20000
Param 10/10 Step 18286/20000
Param 10/10 Step 18287/20000
Param 10/10 Step 18288/20000
Param 10/10 Step 18289/20000
Param 10/10 Step 18290/20000
Param 10/10 Step 18291/20000
Param 10/10 Step 18292/20000
Param 10/10 Step 18293/20000
Param 10/10 Step 18294/20000
Param 10/10 Step 18295/20000
Param 10/10 Step 18296/20000
Param 10/10 Step 18297/20000
Param 10/10 Step 18298/20000
Param 10/10 Step 18299/20000
Param 10/10 Step 18300/20000
Param 10/10 Step 18301/20000
Param 10/10 Step 18302/20000
Param 10/10 Step 18303/20000
Param 10/10 Step 18304/20000
Param 10/10 Step 18305/20000
Param 10/10 Step 18306/20000
Param 10/10 Step 18307/20000
Param 10/10 Step 18308/20000
Param 10/10 Step 18309/20000
Param 10/10 Step 18310/20000
Param 10/10 Step 18311/20000
Param 10/10 Step 18312/20000
Param 10/10 Step 18313/20000
Param 10/10 Step 18314/20000
Param 10/10 Step 18315/20000
Param 10/10 Step 18316/20000
Param 10/10 Step 18317/20000
Param 10/10 Step 18318/20000
Param 10/10 Step 18319/20000
Param 10/10 Step 18320/20000
Param 10/10 Step 18321/20000
Param 10/10 Step 18322/20000
Param 10/10 Step 18323/20000
Param 10/10 Step 18324/20000
Param 10/10 Step 18325/20000
Param 10/10 Step 18326/20000
Param 10/10 Step 18327/20000
Param 10/10 Step 18328/20000
Param 10/10 Step 18329/20000
Param 10/10 Step 18330/20000
Param 10/10 Step 18331/20000
Param 10/10 Step 18332/20000
Param 10/10 Step 18333/20000
Param 10/10 Step 18334/20000
Param 10/10 Step 18335/20000
Param 10/10 Step 18336/20000
Param 10/10 Step 18337/20000
Param 10/10 Step 18338/20000
Param 10/10 Step 18339/20000
Param 10/10 Step 18340/20000
Param 10/10 Step 18341/20000
Param 10/10 Step 18342/20000
Param 10/10 Step 18343/20000
Param 10/10 Step 18344/20000
Param 10/10 Step 18345/20000
Param 10/10 Step 18346/20000
Param 10/10 Step 18347/20000
Param 10/10 Step 18348/20000
Param 10/10 Step 18349/20000
Param 10/10 Step 18350/20000
Param 10/10 Step 18351/20000
Param 10/10 Step 18352/20000
Param 10/10 Step 18353/20000
Param 10/10 Step 18354/20000
Param 10/10 Step 18355/20000
Param 10/10 Step 18356/20000
Param 10/10 Step 18357/20000
Param 10/10 Step 18358/20000
Param 10/10 Step 18359/20000
Param 10/10 Step 18360/20000
Param 10/10 Step 18361/20000
Param 10/10 Step 18362/20000
Param 10/10 Step 18363/20000
Param 10/10 Step 18364/20000
Param 10/10 Step 18365/20000
Param 10/10 Step 18366/20000
Param 10/10 Step 18367/20000
Param 10/10 Step 18368/20000
Param 10/10 Step 18369/20000
Param 10/10 Step 18370/20000
Param 10/10 Step 18371/20000
Param 10/10 Step 18372/20000
Param 10/10 Step 18373/20000
Param 10/10 Step 18374/20000
Param 10/10 Step 18375/20000
Param 10/10 Step 18376/20000
Param 10/10 Step 18377/20000
Param 10/10 Step 18378/20000
Param 10/10 Step 18379/20000
Param 10/10 Step 18380/20000
Param 10/10 Step 18381/20000
Param 10/10 Step 18382/20000
Param 10/10 Step 18383/20000
Param 10/10 Step 18384/20000
Param 10/10 Step 18385/20000
Param 10/10 Step 18386/20000
Param 10/10 Step 18387/20000
Param 10/10 Step 18388/20000
Param 10/10 Step 18389/20000
Param 10/10 Step 18390/20000
Param 10/10 Step 18391/20000
Param 10/10 Step 18392/20000
Param 10/10 Step 18393/20000
Param 10/10 Step 18394/20000
Param 10/10 Step 18395/20000
Param 10/10 Step 18396/20000
Param 10/10 Step 18397/20000
Param 10/10 Step 18398/20000
Param 10/10 Step 18399/20000
Param 10/10 Step 18400/20000
Param 10/10 Step 18401/20000
Param 10/10 Step 18402/20000
Param 10/10 Step 18403/20000
Param 10/10 Step 18404/20000
Param 10/10 Step 18405/20000
Param 10/10 Step 18406/20000
Param 10/10 Step 18407/20000
Param 10/10 Step 18408/20000
Param 10/10 Step 18409/20000
Param 10/10 Step 18410/20000
Param 10/10 Step 18411/20000
Param 10/10 Step 18412/20000
Param 10/10 Step 18413/20000
Param 10/10 Step 18414/20000
Param 10/10 Step 18415/20000
Param 10/10 Step 18416/20000
Param 10/10 Step 18417/20000
Param 10/10 Step 18418/20000
Param 10/10 Step 18419/20000
Param 10/10 Step 18420/20000
Param 10/10 Step 18421/20000
Param 10/10 Step 18422/20000
Param 10/10 Step 18423/20000
Param 10/10 Step 18424/20000
Param 10/10 Step 18425/20000
Param 10/10 Step 18426/20000
Param 10/10 Step 18427/20000
Param 10/10 Step 18428/20000
Param 10/10 Step 18429/20000
Param 10/10 Step 18430/20000
Param 10/10 Step 18431/20000
Param 10/10 Step 18432/20000
Param 10/10 Step 18433/20000
Param 10/10 Step 18434/20000
Param 10/10 Step 18435/20000
Param 10/10 Step 18436/20000
Param 10/10 Step 18437/20000
Param 10/10 Step 18438/20000
Param 10/10 Step 18439/20000
Param 10/10 Step 18440/20000
Param 10/10 Step 18441/20000
Param 10/10 Step 18442/20000
Param 10/10 Step 18443/20000
Param 10/10 Step 18444/20000
Param 10/10 Step 18445/20000
Param 10/10 Step 18446/20000
Param 10/10 Step 18447/20000
Param 10/10 Step 18448/20000
Param 10/10 Step 18449/20000
Param 10/10 Step 18450/20000
Param 10/10 Step 18451/20000
Param 10/10 Step 18452/20000
Param 10/10 Step 18453/20000
Param 10/10 Step 18454/20000
Param 10/10 Step 18455/20000
Param 10/10 Step 18456/20000
Param 10/10 Step 18457/20000
Param 10/10 Step 18458/20000
Param 10/10 Step 18459/20000
Param 10/10 Step 18460/20000
Param 10/10 Step 18461/20000
Param 10/10 Step 18462/20000
Param 10/10 Step 18463/20000
Param 10/10 Step 18464/20000
Param 10/10 Step 18465/20000
Param 10/10 Step 18466/20000
Param 10/10 Step 18467/20000
Param 10/10 Step 18468/20000
Param 10/10 Step 18469/20000
Param 10/10 Step 18470/20000
Param 10/10 Step 18471/20000
Param 10/10 Step 18472/20000
Param 10/10 Step 18473/20000
Param 10/10 Step 18474/20000
Param 10/10 Step 18475/20000
Param 10/10 Step 18476/20000
Param 10/10 Step 18477/20000
Param 10/10 Step 18478/20000
Param 10/10 Step 18479/20000
Param 10/10 Step 18480/20000
Param 10/10 Step 18481/20000
Param 10/10 Step 18482/20000
Param 10/10 Step 18483/20000
Param 10/10 Step 18484/20000
Param 10/10 Step 18485/20000
Param 10/10 Step 18486/20000
Param 10/10 Step 18487/20000
Param 10/10 Step 18488/20000
Param 10/10 Step 18489/20000
Param 10/10 Step 18490/20000
Param 10/10 Step 18491/20000
Param 10/10 Step 18492/20000
Param 10/10 Step 18493/20000
Param 10/10 Step 18494/20000
Param 10/10 Step 18495/20000
Param 10/10 Step 18496/20000
Param 10/10 Step 18497/20000
Param 10/10 Step 18498/20000
Param 10/10 Step 18499/20000
Param 10/10 Step 18500/20000
Param 10/10 Step 18501/20000
Param 10/10 Step 18502/20000
Param 10/10 Step 18503/20000
Param 10/10 Step 18504/20000
Param 10/10 Step 18505/20000
Param 10/10 Step 18506/20000
Param 10/10 Step 18507/20000
Param 10/10 Step 18508/20000
Param 10/10 Step 18509/20000
Param 10/10 Step 18510/20000
Param 10/10 Step 18511/20000
Param 10/10 Step 18512/20000
Param 10/10 Step 18513/20000
Param 10/10 Step 18514/20000
Param 10/10 Step 18515/20000
Param 10/10 Step 18516/20000
Param 10/10 Step 18517/20000
Param 10/10 Step 18518/20000
Param 10/10 Step 18519/20000
Param 10/10 Step 18520/20000
Param 10/10 Step 18521/20000
Param 10/10 Step 18522/20000
Param 10/10 Step 18523/20000
Param 10/10 Step 18524/20000
Param 10/10 Step 18525/20000
Param 10/10 Step 18526/20000
Param 10/10 Step 18527/20000
Param 10/10 Step 18528/20000
Param 10/10 Step 18529/20000
Param 10/10 Step 18530/20000
Param 10/10 Step 18531/20000
Param 10/10 Step 18532/20000
Param 10/10 Step 18533/20000
Param 10/10 Step 18534/20000
Param 10/10 Step 18535/20000
Param 10/10 Step 18536/20000
Param 10/10 Step 18537/20000
Param 10/10 Step 18538/20000
Param 10/10 Step 18539/20000
Param 10/10 Step 18540/20000
Param 10/10 Step 18541/20000
Param 10/10 Step 18542/20000
Param 10/10 Step 18543/20000
Param 10/10 Step 18544/20000
Param 10/10 Step 18545/20000
Param 10/10 Step 18546/20000
Param 10/10 Step 18547/20000
Param 10/10 Step 18548/20000
Param 10/10 Step 18549/20000
Param 10/10 Step 18550/20000
Param 10/10 Step 18551/20000
Param 10/10 Step 18552/20000
Param 10/10 Step 18553/20000
Param 10/10 Step 18554/20000
Param 10/10 Step 18555/20000
Param 10/10 Step 18556/20000
Param 10/10 Step 18557/20000
Param 10/10 Step 18558/20000
Param 10/10 Step 18559/20000
Param 10/10 Step 18560/20000
Param 10/10 Step 18561/20000
Param 10/10 Step 18562/20000
Param 10/10 Step 18563/20000
Param 10/10 Step 18564/20000
Param 10/10 Step 18565/20000
Param 10/10 Step 18566/20000
Param 10/10 Step 18567/20000
Param 10/10 Step 18568/20000
Param 10/10 Step 18569/20000
Param 10/10 Step 18570/20000
Param 10/10 Step 18571/20000
Param 10/10 Step 18572/20000
Param 10/10 Step 18573/20000
Param 10/10 Step 18574/20000
Param 10/10 Step 18575/20000
Param 10/10 Step 18576/20000
Param 10/10 Step 18577/20000
Param 10/10 Step 18578/20000
Param 10/10 Step 18579/20000
Param 10/10 Step 18580/20000
Param 10/10 Step 18581/20000
Param 10/10 Step 18582/20000
Param 10/10 Step 18583/20000
Param 10/10 Step 18584/20000
Param 10/10 Step 18585/20000
Param 10/10 Step 18586/20000
Param 10/10 Step 18587/20000
Param 10/10 Step 18588/20000
Param 10/10 Step 18589/20000
Param 10/10 Step 18590/20000
Param 10/10 Step 18591/20000
Param 10/10 Step 18592/20000
Param 10/10 Step 18593/20000
Param 10/10 Step 18594/20000
Param 10/10 Step 18595/20000
Param 10/10 Step 18596/20000
Param 10/10 Step 18597/20000
Param 10/10 Step 18598/20000
Param 10/10 Step 18599/20000
Param 10/10 Step 18600/20000
Param 10/10 Step 18601/20000
Param 10/10 Step 18602/20000
Param 10/10 Step 18603/20000
Param 10/10 Step 18604/20000
Param 10/10 Step 18605/20000
Param 10/10 Step 18606/20000
Param 10/10 Step 18607/20000
Param 10/10 Step 18608/20000
Param 10/10 Step 18609/20000
Param 10/10 Step 18610/20000
Param 10/10 Step 18611/20000
Param 10/10 Step 18612/20000
Param 10/10 Step 18613/20000
Param 10/10 Step 18614/20000
Param 10/10 Step 18615/20000
Param 10/10 Step 18616/20000
Param 10/10 Step 18617/20000
Param 10/10 Step 18618/20000
Param 10/10 Step 18619/20000
Param 10/10 Step 18620/20000
Param 10/10 Step 18621/20000
Param 10/10 Step 18622/20000
Param 10/10 Step 18623/20000
Param 10/10 Step 18624/20000
Param 10/10 Step 18625/20000
Param 10/10 Step 18626/20000
Param 10/10 Step 18627/20000
Param 10/10 Step 18628/20000
Param 10/10 Step 18629/20000
Param 10/10 Step 18630/20000
Param 10/10 Step 18631/20000
Param 10/10 Step 18632/20000
Param 10/10 Step 18633/20000
Param 10/10 Step 18634/20000
Param 10/10 Step 18635/20000
Param 10/10 Step 18636/20000
Param 10/10 Step 18637/20000
Param 10/10 Step 18638/20000
Param 10/10 Step 18639/20000
Param 10/10 Step 18640/20000
Param 10/10 Step 18641/20000
Param 10/10 Step 18642/20000
Param 10/10 Step 18643/20000
Param 10/10 Step 18644/20000
Param 10/10 Step 18645/20000
Param 10/10 Step 18646/20000
Param 10/10 Step 18647/20000
Param 10/10 Step 18648/20000
Param 10/10 Step 18649/20000
Param 10/10 Step 18650/20000
Param 10/10 Step 18651/20000
Param 10/10 Step 18652/20000
Param 10/10 Step 18653/20000
Param 10/10 Step 18654/20000
Param 10/10 Step 18655/20000
Param 10/10 Step 18656/20000
Param 10/10 Step 18657/20000
Param 10/10 Step 18658/20000
Param 10/10 Step 18659/20000
Param 10/10 Step 18660/20000
Param 10/10 Step 18661/20000
Param 10/10 Step 18662/20000
Param 10/10 Step 18663/20000
Param 10/10 Step 18664/20000
Param 10/10 Step 18665/20000
Param 10/10 Step 18666/20000
Param 10/10 Step 18667/20000
Param 10/10 Step 18668/20000
Param 10/10 Step 18669/20000
Param 10/10 Step 18670/20000
Param 10/10 Step 18671/20000
Param 10/10 Step 18672/20000
Param 10/10 Step 18673/20000
Param 10/10 Step 18674/20000
Param 10/10 Step 18675/20000
Param 10/10 Step 18676/20000
Param 10/10 Step 18677/20000
Param 10/10 Step 18678/20000
Param 10/10 Step 18679/20000
Param 10/10 Step 18680/20000
Param 10/10 Step 18681/20000
Param 10/10 Step 18682/20000
Param 10/10 Step 18683/20000
Param 10/10 Step 18684/20000
Param 10/10 Step 18685/20000
Param 10/10 Step 18686/20000
Param 10/10 Step 18687/20000
Param 10/10 Step 18688/20000
Param 10/10 Step 18689/20000
Param 10/10 Step 18690/20000
Param 10/10 Step 18691/20000
Param 10/10 Step 18692/20000
Param 10/10 Step 18693/20000
Param 10/10 Step 18694/20000
Param 10/10 Step 18695/20000
Param 10/10 Step 18696/20000
Param 10/10 Step 18697/20000
Param 10/10 Step 18698/20000
Param 10/10 Step 18699/20000
Param 10/10 Step 18700/20000
Param 10/10 Step 18701/20000
Param 10/10 Step 18702/20000
Param 10/10 Step 18703/20000
Param 10/10 Step 18704/20000
Param 10/10 Step 18705/20000
Param 10/10 Step 18706/20000
Param 10/10 Step 18707/20000
Param 10/10 Step 18708/20000
Param 10/10 Step 18709/20000
Param 10/10 Step 18710/20000
Param 10/10 Step 18711/20000
Param 10/10 Step 18712/20000
Param 10/10 Step 18713/20000
Param 10/10 Step 18714/20000
Param 10/10 Step 18715/20000
Param 10/10 Step 18716/20000
Param 10/10 Step 18717/20000
Param 10/10 Step 18718/20000
Param 10/10 Step 18719/20000
Param 10/10 Step 18720/20000
Param 10/10 Step 18721/20000
Param 10/10 Step 18722/20000
Param 10/10 Step 18723/20000
Param 10/10 Step 18724/20000
Param 10/10 Step 18725/20000
Param 10/10 Step 18726/20000
Param 10/10 Step 18727/20000
Param 10/10 Step 18728/20000
Param 10/10 Step 18729/20000
Param 10/10 Step 18730/20000
Param 10/10 Step 18731/20000
Param 10/10 Step 18732/20000
Param 10/10 Step 18733/20000
Param 10/10 Step 18734/20000
Param 10/10 Step 18735/20000
Param 10/10 Step 18736/20000
Param 10/10 Step 18737/20000
Param 10/10 Step 18738/20000
Param 10/10 Step 18739/20000
Param 10/10 Step 18740/20000
Param 10/10 Step 18741/20000
Param 10/10 Step 18742/20000
Param 10/10 Step 18743/20000
Param 10/10 Step 18744/20000
Param 10/10 Step 18745/20000
Param 10/10 Step 18746/20000
Param 10/10 Step 18747/20000
Param 10/10 Step 18748/20000
Param 10/10 Step 18749/20000
Param 10/10 Step 18750/20000
Param 10/10 Step 18751/20000
Param 10/10 Step 18752/20000
Param 10/10 Step 18753/20000
Param 10/10 Step 18754/20000
Param 10/10 Step 18755/20000
Param 10/10 Step 18756/20000
Param 10/10 Step 18757/20000
Param 10/10 Step 18758/20000
Param 10/10 Step 18759/20000
Param 10/10 Step 18760/20000
Param 10/10 Step 18761/20000
Param 10/10 Step 18762/20000
Param 10/10 Step 18763/20000
Param 10/10 Step 18764/20000
Param 10/10 Step 18765/20000
Param 10/10 Step 18766/20000
Param 10/10 Step 18767/20000
Param 10/10 Step 18768/20000
Param 10/10 Step 18769/20000
Param 10/10 Step 18770/20000
Param 10/10 Step 18771/20000
Param 10/10 Step 18772/20000
Param 10/10 Step 18773/20000
Param 10/10 Step 18774/20000
Param 10/10 Step 18775/20000
Param 10/10 Step 18776/20000
Param 10/10 Step 18777/20000
Param 10/10 Step 18778/20000
Param 10/10 Step 18779/20000
Param 10/10 Step 18780/20000
Param 10/10 Step 18781/20000
Param 10/10 Step 18782/20000
Param 10/10 Step 18783/20000
Param 10/10 Step 18784/20000
Param 10/10 Step 18785/20000
Param 10/10 Step 18786/20000
Param 10/10 Step 18787/20000
Param 10/10 Step 18788/20000
Param 10/10 Step 18789/20000
Param 10/10 Step 18790/20000
Param 10/10 Step 18791/20000
Param 10/10 Step 18792/20000
Param 10/10 Step 18793/20000
Param 10/10 Step 18794/20000
Param 10/10 Step 18795/20000
Param 10/10 Step 18796/20000
Param 10/10 Step 18797/20000
Param 10/10 Step 18798/20000
Param 10/10 Step 18799/20000
Param 10/10 Step 18800/20000
Param 10/10 Step 18801/20000
Param 10/10 Step 18802/20000
Param 10/10 Step 18803/20000
Param 10/10 Step 18804/20000
Param 10/10 Step 18805/20000
Param 10/10 Step 18806/20000
Param 10/10 Step 18807/20000
Param 10/10 Step 18808/20000
Param 10/10 Step 18809/20000
Param 10/10 Step 18810/20000
Param 10/10 Step 18811/20000
Param 10/10 Step 18812/20000
Param 10/10 Step 18813/20000
Param 10/10 Step 18814/20000
Param 10/10 Step 18815/20000
Param 10/10 Step 18816/20000
Param 10/10 Step 18817/20000
Param 10/10 Step 18818/20000
Param 10/10 Step 18819/20000
Param 10/10 Step 18820/20000
Param 10/10 Step 18821/20000
Param 10/10 Step 18822/20000
Param 10/10 Step 18823/20000
Param 10/10 Step 18824/20000
Param 10/10 Step 18825/20000
Param 10/10 Step 18826/20000
Param 10/10 Step 18827/20000
Param 10/10 Step 18828/20000
Param 10/10 Step 18829/20000
Param 10/10 Step 18830/20000
Param 10/10 Step 18831/20000
Param 10/10 Step 18832/20000
Param 10/10 Step 18833/20000
Param 10/10 Step 18834/20000
Param 10/10 Step 18835/20000
Param 10/10 Step 18836/20000
Param 10/10 Step 18837/20000
Param 10/10 Step 18838/20000
Param 10/10 Step 18839/20000
Param 10/10 Step 18840/20000
Param 10/10 Step 18841/20000
Param 10/10 Step 18842/20000
Param 10/10 Step 18843/20000
Param 10/10 Step 18844/20000
Param 10/10 Step 18845/20000
Param 10/10 Step 18846/20000
Param 10/10 Step 18847/20000
Param 10/10 Step 18848/20000
Param 10/10 Step 18849/20000
Param 10/10 Step 18850/20000
Param 10/10 Step 18851/20000
Param 10/10 Step 18852/20000
Param 10/10 Step 18853/20000
Param 10/10 Step 18854/20000
Param 10/10 Step 18855/20000
Param 10/10 Step 18856/20000
Param 10/10 Step 18857/20000
Param 10/10 Step 18858/20000
Param 10/10 Step 18859/20000
Param 10/10 Step 18860/20000
Param 10/10 Step 18861/20000
Param 10/10 Step 18862/20000
Param 10/10 Step 18863/20000
Param 10/10 Step 18864/20000
Param 10/10 Step 18865/20000
Param 10/10 Step 18866/20000
Param 10/10 Step 18867/20000
Param 10/10 Step 18868/20000
Param 10/10 Step 18869/20000
Param 10/10 Step 18870/20000
Param 10/10 Step 18871/20000
Param 10/10 Step 18872/20000
Param 10/10 Step 18873/20000
Param 10/10 Step 18874/20000
Param 10/10 Step 18875/20000
Param 10/10 Step 18876/20000
Param 10/10 Step 18877/20000
Param 10/10 Step 18878/20000
Param 10/10 Step 18879/20000
Param 10/10 Step 18880/20000
Param 10/10 Step 18881/20000
Param 10/10 Step 18882/20000
Param 10/10 Step 18883/20000
Param 10/10 Step 18884/20000
Param 10/10 Step 18885/20000
Param 10/10 Step 18886/20000
Param 10/10 Step 18887/20000
Param 10/10 Step 18888/20000
Param 10/10 Step 18889/20000
Param 10/10 Step 18890/20000
Param 10/10 Step 18891/20000
Param 10/10 Step 18892/20000
Param 10/10 Step 18893/20000
Param 10/10 Step 18894/20000
Param 10/10 Step 18895/20000
Param 10/10 Step 18896/20000
Param 10/10 Step 18897/20000
Param 10/10 Step 18898/20000
Param 10/10 Step 18899/20000
Param 10/10 Step 18900/20000
Param 10/10 Step 18901/20000
Param 10/10 Step 18902/20000
Param 10/10 Step 18903/20000
Param 10/10 Step 18904/20000
Param 10/10 Step 18905/20000
Param 10/10 Step 18906/20000
Param 10/10 Step 18907/20000
Param 10/10 Step 18908/20000
Param 10/10 Step 18909/20000
Param 10/10 Step 18910/20000
Param 10/10 Step 18911/20000
Param 10/10 Step 18912/20000
Param 10/10 Step 18913/20000
Param 10/10 Step 18914/20000
Param 10/10 Step 18915/20000
Param 10/10 Step 18916/20000
Param 10/10 Step 18917/20000
Param 10/10 Step 18918/20000
Param 10/10 Step 18919/20000
Param 10/10 Step 18920/20000
Param 10/10 Step 18921/20000
Param 10/10 Step 18922/20000
Param 10/10 Step 18923/20000
Param 10/10 Step 18924/20000
Param 10/10 Step 18925/20000
Param 10/10 Step 18926/20000
Param 10/10 Step 18927/20000
Param 10/10 Step 18928/20000
Param 10/10 Step 18929/20000
Param 10/10 Step 18930/20000
Param 10/10 Step 18931/20000
Param 10/10 Step 18932/20000
Param 10/10 Step 18933/20000
Param 10/10 Step 18934/20000
Param 10/10 Step 18935/20000
Param 10/10 Step 18936/20000
Param 10/10 Step 18937/20000
Param 10/10 Step 18938/20000
Param 10/10 Step 18939/20000
Param 10/10 Step 18940/20000
Param 10/10 Step 18941/20000
Param 10/10 Step 18942/20000
Param 10/10 Step 18943/20000
Param 10/10 Step 18944/20000
Param 10/10 Step 18945/20000
Param 10/10 Step 18946/20000
Param 10/10 Step 18947/20000
Param 10/10 Step 18948/20000
Param 10/10 Step 18949/20000
Param 10/10 Step 18950/20000
Param 10/10 Step 18951/20000
Param 10/10 Step 18952/20000
Param 10/10 Step 18953/20000
Param 10/10 Step 18954/20000
Param 10/10 Step 18955/20000
Param 10/10 Step 18956/20000
Param 10/10 Step 18957/20000
Param 10/10 Step 18958/20000
Param 10/10 Step 18959/20000
Param 10/10 Step 18960/20000
Param 10/10 Step 18961/20000
Param 10/10 Step 18962/20000
Param 10/10 Step 18963/20000
Param 10/10 Step 18964/20000
Param 10/10 Step 18965/20000
Param 10/10 Step 18966/20000
Param 10/10 Step 18967/20000
Param 10/10 Step 18968/20000
Param 10/10 Step 18969/20000
Param 10/10 Step 18970/20000
Param 10/10 Step 18971/20000
Param 10/10 Step 18972/20000
Param 10/10 Step 18973/20000
Param 10/10 Step 18974/20000
Param 10/10 Step 18975/20000
Param 10/10 Step 18976/20000
Param 10/10 Step 18977/20000
Param 10/10 Step 18978/20000
Param 10/10 Step 18979/20000
Param 10/10 Step 18980/20000
Param 10/10 Step 18981/20000
Param 10/10 Step 18982/20000
Param 10/10 Step 18983/20000
Param 10/10 Step 18984/20000
Param 10/10 Step 18985/20000
Param 10/10 Step 18986/20000
Param 10/10 Step 18987/20000
Param 10/10 Step 18988/20000
Param 10/10 Step 18989/20000
Param 10/10 Step 18990/20000
Param 10/10 Step 18991/20000
Param 10/10 Step 18992/20000
Param 10/10 Step 18993/20000
Param 10/10 Step 18994/20000
Param 10/10 Step 18995/20000
Param 10/10 Step 18996/20000
Param 10/10 Step 18997/20000
Param 10/10 Step 18998/20000
Param 10/10 Step 18999/20000
Param 10/10 Step 19000/20000
Param 10/10 Step 19001/20000
Param 10/10 Step 19002/20000
Param 10/10 Step 19003/20000
Param 10/10 Step 19004/20000
Param 10/10 Step 19005/20000
Param 10/10 Step 19006/20000
Param 10/10 Step 19007/20000
Param 10/10 Step 19008/20000
Param 10/10 Step 19009/20000
Param 10/10 Step 19010/20000
Param 10/10 Step 19011/20000
Param 10/10 Step 19012/20000
Param 10/10 Step 19013/20000
Param 10/10 Step 19014/20000
Param 10/10 Step 19015/20000
Param 10/10 Step 19016/20000
Param 10/10 Step 19017/20000
Param 10/10 Step 19018/20000
Param 10/10 Step 19019/20000
Param 10/10 Step 19020/20000
Param 10/10 Step 19021/20000
Param 10/10 Step 19022/20000
Param 10/10 Step 19023/20000
Param 10/10 Step 19024/20000
Param 10/10 Step 19025/20000
Param 10/10 Step 19026/20000
Param 10/10 Step 19027/20000
Param 10/10 Step 19028/20000
Param 10/10 Step 19029/20000
Param 10/10 Step 19030/20000
Param 10/10 Step 19031/20000
Param 10/10 Step 19032/20000
Param 10/10 Step 19033/20000
Param 10/10 Step 19034/20000
Param 10/10 Step 19035/20000
Param 10/10 Step 19036/20000
Param 10/10 Step 19037/20000
Param 10/10 Step 19038/20000
Param 10/10 Step 19039/20000
Param 10/10 Step 19040/20000
Param 10/10 Step 19041/20000
Param 10/10 Step 19042/20000
Param 10/10 Step 19043/20000
Param 10/10 Step 19044/20000
Param 10/10 Step 19045/20000
Param 10/10 Step 19046/20000
Param 10/10 Step 19047/20000
Param 10/10 Step 19048/20000
Param 10/10 Step 19049/20000
Param 10/10 Step 19050/20000
Param 10/10 Step 19051/20000
Param 10/10 Step 19052/20000
Param 10/10 Step 19053/20000
Param 10/10 Step 19054/20000
Param 10/10 Step 19055/20000
Param 10/10 Step 19056/20000
Param 10/10 Step 19057/20000
Param 10/10 Step 19058/20000
Param 10/10 Step 19059/20000
Param 10/10 Step 19060/20000
Param 10/10 Step 19061/20000
Param 10/10 Step 19062/20000
Param 10/10 Step 19063/20000
Param 10/10 Step 19064/20000
Param 10/10 Step 19065/20000
Param 10/10 Step 19066/20000
Param 10/10 Step 19067/20000
Param 10/10 Step 19068/20000
Param 10/10 Step 19069/20000
Param 10/10 Step 19070/20000
Param 10/10 Step 19071/20000
Param 10/10 Step 19072/20000
Param 10/10 Step 19073/20000
Param 10/10 Step 19074/20000
Param 10/10 Step 19075/20000
Param 10/10 Step 19076/20000
Param 10/10 Step 19077/20000
Param 10/10 Step 19078/20000
Param 10/10 Step 19079/20000
Param 10/10 Step 19080/20000
Param 10/10 Step 19081/20000
Param 10/10 Step 19082/20000
Param 10/10 Step 19083/20000
Param 10/10 Step 19084/20000
Param 10/10 Step 19085/20000
Param 10/10 Step 19086/20000
Param 10/10 Step 19087/20000
Param 10/10 Step 19088/20000
Param 10/10 Step 19089/20000
Param 10/10 Step 19090/20000
Param 10/10 Step 19091/20000
Param 10/10 Step 19092/20000
Param 10/10 Step 19093/20000
Param 10/10 Step 19094/20000
Param 10/10 Step 19095/20000
Param 10/10 Step 19096/20000
Param 10/10 Step 19097/20000
Param 10/10 Step 19098/20000
Param 10/10 Step 19099/20000
Param 10/10 Step 19100/20000
Param 10/10 Step 19101/20000
Param 10/10 Step 19102/20000
Param 10/10 Step 19103/20000
Param 10/10 Step 19104/20000
Param 10/10 Step 19105/20000
Param 10/10 Step 19106/20000
Param 10/10 Step 19107/20000
Param 10/10 Step 19108/20000
Param 10/10 Step 19109/20000
Param 10/10 Step 19110/20000
Param 10/10 Step 19111/20000
Param 10/10 Step 19112/20000
Param 10/10 Step 19113/20000
Param 10/10 Step 19114/20000
Param 10/10 Step 19115/20000
Param 10/10 Step 19116/20000
Param 10/10 Step 19117/20000
Param 10/10 Step 19118/20000
Param 10/10 Step 19119/20000
Param 10/10 Step 19120/20000
Param 10/10 Step 19121/20000
Param 10/10 Step 19122/20000
Param 10/10 Step 19123/20000
Param 10/10 Step 19124/20000
Param 10/10 Step 19125/20000
Param 10/10 Step 19126/20000
Param 10/10 Step 19127/20000
Param 10/10 Step 19128/20000
Param 10/10 Step 19129/20000
Param 10/10 Step 19130/20000
Param 10/10 Step 19131/20000
Param 10/10 Step 19132/20000
Param 10/10 Step 19133/20000
Param 10/10 Step 19134/20000
Param 10/10 Step 19135/20000
Param 10/10 Step 19136/20000
Param 10/10 Step 19137/20000
Param 10/10 Step 19138/20000
Param 10/10 Step 19139/20000
Param 10/10 Step 19140/20000
Param 10/10 Step 19141/20000
Param 10/10 Step 19142/20000
Param 10/10 Step 19143/20000
Param 10/10 Step 19144/20000
Param 10/10 Step 19145/20000
Param 10/10 Step 19146/20000
Param 10/10 Step 19147/20000
Param 10/10 Step 19148/20000
Param 10/10 Step 19149/20000
Param 10/10 Step 19150/20000
Param 10/10 Step 19151/20000
Param 10/10 Step 19152/20000
Param 10/10 Step 19153/20000
Param 10/10 Step 19154/20000
Param 10/10 Step 19155/20000
Param 10/10 Step 19156/20000
Param 10/10 Step 19157/20000
Param 10/10 Step 19158/20000
Param 10/10 Step 19159/20000
Param 10/10 Step 19160/20000
Param 10/10 Step 19161/20000
Param 10/10 Step 19162/20000
Param 10/10 Step 19163/20000
Param 10/10 Step 19164/20000
Param 10/10 Step 19165/20000
Param 10/10 Step 19166/20000
Param 10/10 Step 19167/20000
Param 10/10 Step 19168/20000
Param 10/10 Step 19169/20000
Param 10/10 Step 19170/20000
Param 10/10 Step 19171/20000
Param 10/10 Step 19172/20000
Param 10/10 Step 19173/20000
Param 10/10 Step 19174/20000
Param 10/10 Step 19175/20000
Param 10/10 Step 19176/20000
Param 10/10 Step 19177/20000
Param 10/10 Step 19178/20000
Param 10/10 Step 19179/20000
Param 10/10 Step 19180/20000
Param 10/10 Step 19181/20000
Param 10/10 Step 19182/20000
Param 10/10 Step 19183/20000
Param 10/10 Step 19184/20000
Param 10/10 Step 19185/20000
Param 10/10 Step 19186/20000
Param 10/10 Step 19187/20000
Param 10/10 Step 19188/20000
Param 10/10 Step 19189/20000
Param 10/10 Step 19190/20000
Param 10/10 Step 19191/20000
Param 10/10 Step 19192/20000
Param 10/10 Step 19193/20000
Param 10/10 Step 19194/20000
Param 10/10 Step 19195/20000
Param 10/10 Step 19196/20000
Param 10/10 Step 19197/20000
Param 10/10 Step 19198/20000
Param 10/10 Step 19199/20000
Param 10/10 Step 19200/20000
Param 10/10 Step 19201/20000
Param 10/10 Step 19202/20000
Param 10/10 Step 19203/20000
Param 10/10 Step 19204/20000
Param 10/10 Step 19205/20000
Param 10/10 Step 19206/20000
Param 10/10 Step 19207/20000
Param 10/10 Step 19208/20000
Param 10/10 Step 19209/20000
Param 10/10 Step 19210/20000
Param 10/10 Step 19211/20000
Param 10/10 Step 19212/20000
Param 10/10 Step 19213/20000
Param 10/10 Step 19214/20000
Param 10/10 Step 19215/20000
Param 10/10 Step 19216/20000
Param 10/10 Step 19217/20000
Param 10/10 Step 19218/20000
Param 10/10 Step 19219/20000
Param 10/10 Step 19220/20000
Param 10/10 Step 19221/20000
Param 10/10 Step 19222/20000
Param 10/10 Step 19223/20000
Param 10/10 Step 19224/20000
Param 10/10 Step 19225/20000
Param 10/10 Step 19226/20000
Param 10/10 Step 19227/20000
Param 10/10 Step 19228/20000
Param 10/10 Step 19229/20000
Param 10/10 Step 19230/20000
Param 10/10 Step 19231/20000
Param 10/10 Step 19232/20000
Param 10/10 Step 19233/20000
Param 10/10 Step 19234/20000
Param 10/10 Step 19235/20000
Param 10/10 Step 19236/20000
Param 10/10 Step 19237/20000
Param 10/10 Step 19238/20000
Param 10/10 Step 19239/20000
Param 10/10 Step 19240/20000
Param 10/10 Step 19241/20000
Param 10/10 Step 19242/20000
Param 10/10 Step 19243/20000
Param 10/10 Step 19244/20000
Param 10/10 Step 19245/20000
Param 10/10 Step 19246/20000
Param 10/10 Step 19247/20000
Param 10/10 Step 19248/20000
Param 10/10 Step 19249/20000
Param 10/10 Step 19250/20000
Param 10/10 Step 19251/20000
Param 10/10 Step 19252/20000
Param 10/10 Step 19253/20000
Param 10/10 Step 19254/20000
Param 10/10 Step 19255/20000
Param 10/10 Step 19256/20000
Param 10/10 Step 19257/20000
Param 10/10 Step 19258/20000
Param 10/10 Step 19259/20000
Param 10/10 Step 19260/20000
Param 10/10 Step 19261/20000
Param 10/10 Step 19262/20000
Param 10/10 Step 19263/20000
Param 10/10 Step 19264/20000
Param 10/10 Step 19265/20000
Param 10/10 Step 19266/20000
Param 10/10 Step 19267/20000
Param 10/10 Step 19268/20000
Param 10/10 Step 19269/20000
Param 10/10 Step 19270/20000
Param 10/10 Step 19271/20000
Param 10/10 Step 19272/20000
Param 10/10 Step 19273/20000
Param 10/10 Step 19274/20000
Param 10/10 Step 19275/20000
Param 10/10 Step 19276/20000
Param 10/10 Step 19277/20000
Param 10/10 Step 19278/20000
Param 10/10 Step 19279/20000
Param 10/10 Step 19280/20000
Param 10/10 Step 19281/20000
Param 10/10 Step 19282/20000
Param 10/10 Step 19283/20000
Param 10/10 Step 19284/20000
Param 10/10 Step 19285/20000
Param 10/10 Step 19286/20000
Param 10/10 Step 19287/20000
Param 10/10 Step 19288/20000
Param 10/10 Step 19289/20000
Param 10/10 Step 19290/20000
Param 10/10 Step 19291/20000
Param 10/10 Step 19292/20000
Param 10/10 Step 19293/20000
Param 10/10 Step 19294/20000
Param 10/10 Step 19295/20000
Param 10/10 Step 19296/20000
Param 10/10 Step 19297/20000
Param 10/10 Step 19298/20000
Param 10/10 Step 19299/20000
Param 10/10 Step 19300/20000
Param 10/10 Step 19301/20000
Param 10/10 Step 19302/20000
Param 10/10 Step 19303/20000
Param 10/10 Step 19304/20000
Param 10/10 Step 19305/20000
Param 10/10 Step 19306/20000
Param 10/10 Step 19307/20000
Param 10/10 Step 19308/20000
Param 10/10 Step 19309/20000
Param 10/10 Step 19310/20000
Param 10/10 Step 19311/20000
Param 10/10 Step 19312/20000
Param 10/10 Step 19313/20000
Param 10/10 Step 19314/20000
Param 10/10 Step 19315/20000
Param 10/10 Step 19316/20000
Param 10/10 Step 19317/20000
Param 10/10 Step 19318/20000
Param 10/10 Step 19319/20000
Param 10/10 Step 19320/20000
Param 10/10 Step 19321/20000
Param 10/10 Step 19322/20000
Param 10/10 Step 19323/20000
Param 10/10 Step 19324/20000
Param 10/10 Step 19325/20000
Param 10/10 Step 19326/20000
Param 10/10 Step 19327/20000
Param 10/10 Step 19328/20000
Param 10/10 Step 19329/20000
Param 10/10 Step 19330/20000
Param 10/10 Step 19331/20000
Param 10/10 Step 19332/20000
Param 10/10 Step 19333/20000
Param 10/10 Step 19334/20000
Param 10/10 Step 19335/20000
Param 10/10 Step 19336/20000
Param 10/10 Step 19337/20000
Param 10/10 Step 19338/20000
Param 10/10 Step 19339/20000
Param 10/10 Step 19340/20000
Param 10/10 Step 19341/20000
Param 10/10 Step 19342/20000
Param 10/10 Step 19343/20000
Param 10/10 Step 19344/20000
Param 10/10 Step 19345/20000
Param 10/10 Step 19346/20000
Param 10/10 Step 19347/20000
Param 10/10 Step 19348/20000
Param 10/10 Step 19349/20000
Param 10/10 Step 19350/20000
Param 10/10 Step 19351/20000
Param 10/10 Step 19352/20000
Param 10/10 Step 19353/20000
Param 10/10 Step 19354/20000
Param 10/10 Step 19355/20000
Param 10/10 Step 19356/20000
Param 10/10 Step 19357/20000
Param 10/10 Step 19358/20000
Param 10/10 Step 19359/20000
Param 10/10 Step 19360/20000
Param 10/10 Step 19361/20000
Param 10/10 Step 19362/20000
Param 10/10 Step 19363/20000
Param 10/10 Step 19364/20000
Param 10/10 Step 19365/20000
Param 10/10 Step 19366/20000
Param 10/10 Step 19367/20000
Param 10/10 Step 19368/20000
Param 10/10 Step 19369/20000
Param 10/10 Step 19370/20000
Param 10/10 Step 19371/20000
Param 10/10 Step 19372/20000
Param 10/10 Step 19373/20000
Param 10/10 Step 19374/20000
Param 10/10 Step 19375/20000
Param 10/10 Step 19376/20000
Param 10/10 Step 19377/20000
Param 10/10 Step 19378/20000
Param 10/10 Step 19379/20000
Param 10/10 Step 19380/20000
Param 10/10 Step 19381/20000
Param 10/10 Step 19382/20000
Param 10/10 Step 19383/20000
Param 10/10 Step 19384/20000
Param 10/10 Step 19385/20000
Param 10/10 Step 19386/20000
Param 10/10 Step 19387/20000
Param 10/10 Step 19388/20000
Param 10/10 Step 19389/20000
Param 10/10 Step 19390/20000
Param 10/10 Step 19391/20000
Param 10/10 Step 19392/20000
Param 10/10 Step 19393/20000
Param 10/10 Step 19394/20000
Param 10/10 Step 19395/20000
Param 10/10 Step 19396/20000
Param 10/10 Step 19397/20000
Param 10/10 Step 19398/20000
Param 10/10 Step 19399/20000
Param 10/10 Step 19400/20000
Param 10/10 Step 19401/20000
Param 10/10 Step 19402/20000
Param 10/10 Step 19403/20000
Param 10/10 Step 19404/20000
Param 10/10 Step 19405/20000
Param 10/10 Step 19406/20000
Param 10/10 Step 19407/20000
Param 10/10 Step 19408/20000
Param 10/10 Step 19409/20000
Param 10/10 Step 19410/20000
Param 10/10 Step 19411/20000
Param 10/10 Step 19412/20000
Param 10/10 Step 19413/20000
Param 10/10 Step 19414/20000
Param 10/10 Step 19415/20000
Param 10/10 Step 19416/20000
Param 10/10 Step 19417/20000
Param 10/10 Step 19418/20000
Param 10/10 Step 19419/20000
Param 10/10 Step 19420/20000
Param 10/10 Step 19421/20000
Param 10/10 Step 19422/20000
Param 10/10 Step 19423/20000
Param 10/10 Step 19424/20000
Param 10/10 Step 19425/20000
Param 10/10 Step 19426/20000
Param 10/10 Step 19427/20000
Param 10/10 Step 19428/20000
Param 10/10 Step 19429/20000
Param 10/10 Step 19430/20000
Param 10/10 Step 19431/20000
Param 10/10 Step 19432/20000
Param 10/10 Step 19433/20000
Param 10/10 Step 19434/20000
Param 10/10 Step 19435/20000
Param 10/10 Step 19436/20000
Param 10/10 Step 19437/20000
Param 10/10 Step 19438/20000
Param 10/10 Step 19439/20000
Param 10/10 Step 19440/20000
Param 10/10 Step 19441/20000
Param 10/10 Step 19442/20000
Param 10/10 Step 19443/20000
Param 10/10 Step 19444/20000
Param 10/10 Step 19445/20000
Param 10/10 Step 19446/20000
Param 10/10 Step 19447/20000
Param 10/10 Step 19448/20000
Param 10/10 Step 19449/20000
Param 10/10 Step 19450/20000
Param 10/10 Step 19451/20000
Param 10/10 Step 19452/20000
Param 10/10 Step 19453/20000
Param 10/10 Step 19454/20000
Param 10/10 Step 19455/20000
Param 10/10 Step 19456/20000
Param 10/10 Step 19457/20000
Param 10/10 Step 19458/20000
Param 10/10 Step 19459/20000
Param 10/10 Step 19460/20000
Param 10/10 Step 19461/20000
Param 10/10 Step 19462/20000
Param 10/10 Step 19463/20000
Param 10/10 Step 19464/20000
Param 10/10 Step 19465/20000
Param 10/10 Step 19466/20000
Param 10/10 Step 19467/20000
Param 10/10 Step 19468/20000
Param 10/10 Step 19469/20000
Param 10/10 Step 19470/20000
Param 10/10 Step 19471/20000
Param 10/10 Step 19472/20000
Param 10/10 Step 19473/20000
Param 10/10 Step 19474/20000
Param 10/10 Step 19475/20000
Param 10/10 Step 19476/20000
Param 10/10 Step 19477/20000
Param 10/10 Step 19478/20000
Param 10/10 Step 19479/20000
Param 10/10 Step 19480/20000
Param 10/10 Step 19481/20000
Param 10/10 Step 19482/20000
Param 10/10 Step 19483/20000
Param 10/10 Step 19484/20000
Param 10/10 Step 19485/20000
Param 10/10 Step 19486/20000
Param 10/10 Step 19487/20000
Param 10/10 Step 19488/20000
Param 10/10 Step 19489/20000
Param 10/10 Step 19490/20000
Param 10/10 Step 19491/20000
Param 10/10 Step 19492/20000
Param 10/10 Step 19493/20000
Param 10/10 Step 19494/20000
Param 10/10 Step 19495/20000
Param 10/10 Step 19496/20000
Param 10/10 Step 19497/20000
Param 10/10 Step 19498/20000
Param 10/10 Step 19499/20000
Param 10/10 Step 19500/20000
Param 10/10 Step 19501/20000
Param 10/10 Step 19502/20000
Param 10/10 Step 19503/20000
Param 10/10 Step 19504/20000
Param 10/10 Step 19505/20000
Param 10/10 Step 19506/20000
Param 10/10 Step 19507/20000
Param 10/10 Step 19508/20000
Param 10/10 Step 19509/20000
Param 10/10 Step 19510/20000
Param 10/10 Step 19511/20000
Param 10/10 Step 19512/20000
Param 10/10 Step 19513/20000
Param 10/10 Step 19514/20000
Param 10/10 Step 19515/20000
Param 10/10 Step 19516/20000
Param 10/10 Step 19517/20000
Param 10/10 Step 19518/20000
Param 10/10 Step 19519/20000
Param 10/10 Step 19520/20000
Param 10/10 Step 19521/20000
Param 10/10 Step 19522/20000
Param 10/10 Step 19523/20000
Param 10/10 Step 19524/20000
Param 10/10 Step 19525/20000
Param 10/10 Step 19526/20000
Param 10/10 Step 19527/20000
Param 10/10 Step 19528/20000
Param 10/10 Step 19529/20000
Param 10/10 Step 19530/20000
Param 10/10 Step 19531/20000
Param 10/10 Step 19532/20000
Param 10/10 Step 19533/20000
Param 10/10 Step 19534/20000
Param 10/10 Step 19535/20000
Param 10/10 Step 19536/20000
Param 10/10 Step 19537/20000
Param 10/10 Step 19538/20000
Param 10/10 Step 19539/20000
Param 10/10 Step 19540/20000
Param 10/10 Step 19541/20000
Param 10/10 Step 19542/20000
Param 10/10 Step 19543/20000
Param 10/10 Step 19544/20000
Param 10/10 Step 19545/20000
Param 10/10 Step 19546/20000
Param 10/10 Step 19547/20000
Param 10/10 Step 19548/20000
Param 10/10 Step 19549/20000
Param 10/10 Step 19550/20000
Param 10/10 Step 19551/20000
Param 10/10 Step 19552/20000
Param 10/10 Step 19553/20000
Param 10/10 Step 19554/20000
Param 10/10 Step 19555/20000
Param 10/10 Step 19556/20000
Param 10/10 Step 19557/20000
Param 10/10 Step 19558/20000
Param 10/10 Step 19559/20000
Param 10/10 Step 19560/20000
Param 10/10 Step 19561/20000
Param 10/10 Step 19562/20000
Param 10/10 Step 19563/20000
Param 10/10 Step 19564/20000
Param 10/10 Step 19565/20000
Param 10/10 Step 19566/20000
Param 10/10 Step 19567/20000
Param 10/10 Step 19568/20000
Param 10/10 Step 19569/20000
Param 10/10 Step 19570/20000
Param 10/10 Step 19571/20000
Param 10/10 Step 19572/20000
Param 10/10 Step 19573/20000
Param 10/10 Step 19574/20000
Param 10/10 Step 19575/20000
Param 10/10 Step 19576/20000
Param 10/10 Step 19577/20000
Param 10/10 Step 19578/20000
Param 10/10 Step 19579/20000
Param 10/10 Step 19580/20000
Param 10/10 Step 19581/20000
Param 10/10 Step 19582/20000
Param 10/10 Step 19583/20000
Param 10/10 Step 19584/20000
Param 10/10 Step 19585/20000
Param 10/10 Step 19586/20000
Param 10/10 Step 19587/20000
Param 10/10 Step 19588/20000
Param 10/10 Step 19589/20000
Param 10/10 Step 19590/20000
Param 10/10 Step 19591/20000
Param 10/10 Step 19592/20000
Param 10/10 Step 19593/20000
Param 10/10 Step 19594/20000
Param 10/10 Step 19595/20000
Param 10/10 Step 19596/20000
Param 10/10 Step 19597/20000
Param 10/10 Step 19598/20000
Param 10/10 Step 19599/20000
Param 10/10 Step 19600/20000
Param 10/10 Step 19601/20000
Param 10/10 Step 19602/20000
Param 10/10 Step 19603/20000
Param 10/10 Step 19604/20000
Param 10/10 Step 19605/20000
Param 10/10 Step 19606/20000
Param 10/10 Step 19607/20000
Param 10/10 Step 19608/20000
Param 10/10 Step 19609/20000
Param 10/10 Step 19610/20000
Param 10/10 Step 19611/20000
Param 10/10 Step 19612/20000
Param 10/10 Step 19613/20000
Param 10/10 Step 19614/20000
Param 10/10 Step 19615/20000
Param 10/10 Step 19616/20000
Param 10/10 Step 19617/20000
Param 10/10 Step 19618/20000
Param 10/10 Step 19619/20000
Param 10/10 Step 19620/20000
Param 10/10 Step 19621/20000
Param 10/10 Step 19622/20000
Param 10/10 Step 19623/20000
Param 10/10 Step 19624/20000
Param 10/10 Step 19625/20000
Param 10/10 Step 19626/20000
Param 10/10 Step 19627/20000
Param 10/10 Step 19628/20000
Param 10/10 Step 19629/20000
Param 10/10 Step 19630/20000
Param 10/10 Step 19631/20000
Param 10/10 Step 19632/20000
Param 10/10 Step 19633/20000
Param 10/10 Step 19634/20000
Param 10/10 Step 19635/20000
Param 10/10 Step 19636/20000
Param 10/10 Step 19637/20000
Param 10/10 Step 19638/20000
Param 10/10 Step 19639/20000
Param 10/10 Step 19640/20000
Param 10/10 Step 19641/20000
Param 10/10 Step 19642/20000
Param 10/10 Step 19643/20000
Param 10/10 Step 19644/20000
Param 10/10 Step 19645/20000
Param 10/10 Step 19646/20000
Param 10/10 Step 19647/20000
Param 10/10 Step 19648/20000
Param 10/10 Step 19649/20000
Param 10/10 Step 19650/20000
Param 10/10 Step 19651/20000
Param 10/10 Step 19652/20000
Param 10/10 Step 19653/20000
Param 10/10 Step 19654/20000
Param 10/10 Step 19655/20000
Param 10/10 Step 19656/20000
Param 10/10 Step 19657/20000
Param 10/10 Step 19658/20000
Param 10/10 Step 19659/20000
Param 10/10 Step 19660/20000
Param 10/10 Step 19661/20000
Param 10/10 Step 19662/20000
Param 10/10 Step 19663/20000
Param 10/10 Step 19664/20000
Param 10/10 Step 19665/20000
Param 10/10 Step 19666/20000
Param 10/10 Step 19667/20000
Param 10/10 Step 19668/20000
Param 10/10 Step 19669/20000
Param 10/10 Step 19670/20000
Param 10/10 Step 19671/20000
Param 10/10 Step 19672/20000
Param 10/10 Step 19673/20000
Param 10/10 Step 19674/20000
Param 10/10 Step 19675/20000
Param 10/10 Step 19676/20000
Param 10/10 Step 19677/20000
Param 10/10 Step 19678/20000
Param 10/10 Step 19679/20000
Param 10/10 Step 19680/20000
Param 10/10 Step 19681/20000
Param 10/10 Step 19682/20000
Param 10/10 Step 19683/20000
Param 10/10 Step 19684/20000
Param 10/10 Step 19685/20000
Param 10/10 Step 19686/20000
Param 10/10 Step 19687/20000
Param 10/10 Step 19688/20000
Param 10/10 Step 19689/20000
Param 10/10 Step 19690/20000
Param 10/10 Step 19691/20000
Param 10/10 Step 19692/20000
Param 10/10 Step 19693/20000
Param 10/10 Step 19694/20000
Param 10/10 Step 19695/20000
Param 10/10 Step 19696/20000
Param 10/10 Step 19697/20000
Param 10/10 Step 19698/20000
Param 10/10 Step 19699/20000
Param 10/10 Step 19700/20000
Param 10/10 Step 19701/20000
Param 10/10 Step 19702/20000
Param 10/10 Step 19703/20000
Param 10/10 Step 19704/20000
Param 10/10 Step 19705/20000
Param 10/10 Step 19706/20000
Param 10/10 Step 19707/20000
Param 10/10 Step 19708/20000
Param 10/10 Step 19709/20000
Param 10/10 Step 19710/20000
Param 10/10 Step 19711/20000
Param 10/10 Step 19712/20000
Param 10/10 Step 19713/20000
Param 10/10 Step 19714/20000
Param 10/10 Step 19715/20000
Param 10/10 Step 19716/20000
Param 10/10 Step 19717/20000
Param 10/10 Step 19718/20000
Param 10/10 Step 19719/20000
Param 10/10 Step 19720/20000
Param 10/10 Step 19721/20000
Param 10/10 Step 19722/20000
Param 10/10 Step 19723/20000
Param 10/10 Step 19724/20000
Param 10/10 Step 19725/20000
Param 10/10 Step 19726/20000
Param 10/10 Step 19727/20000
Param 10/10 Step 19728/20000
Param 10/10 Step 19729/20000
Param 10/10 Step 19730/20000
Param 10/10 Step 19731/20000
Param 10/10 Step 19732/20000
Param 10/10 Step 19733/20000
Param 10/10 Step 19734/20000
Param 10/10 Step 19735/20000
Param 10/10 Step 19736/20000
Param 10/10 Step 19737/20000
Param 10/10 Step 19738/20000
Param 10/10 Step 19739/20000
Param 10/10 Step 19740/20000
Param 10/10 Step 19741/20000
Param 10/10 Step 19742/20000
Param 10/10 Step 19743/20000
Param 10/10 Step 19744/20000
Param 10/10 Step 19745/20000
Param 10/10 Step 19746/20000
Param 10/10 Step 19747/20000
Param 10/10 Step 19748/20000
Param 10/10 Step 19749/20000
Param 10/10 Step 19750/20000
Param 10/10 Step 19751/20000
Param 10/10 Step 19752/20000
Param 10/10 Step 19753/20000
Param 10/10 Step 19754/20000
Param 10/10 Step 19755/20000
Param 10/10 Step 19756/20000
Param 10/10 Step 19757/20000
Param 10/10 Step 19758/20000
Param 10/10 Step 19759/20000
Param 10/10 Step 19760/20000
Param 10/10 Step 19761/20000
Param 10/10 Step 19762/20000
Param 10/10 Step 19763/20000
Param 10/10 Step 19764/20000
Param 10/10 Step 19765/20000
Param 10/10 Step 19766/20000
Param 10/10 Step 19767/20000
Param 10/10 Step 19768/20000
Param 10/10 Step 19769/20000
Param 10/10 Step 19770/20000
Param 10/10 Step 19771/20000
Param 10/10 Step 19772/20000
Param 10/10 Step 19773/20000
Param 10/10 Step 19774/20000
Param 10/10 Step 19775/20000
Param 10/10 Step 19776/20000
Param 10/10 Step 19777/20000
Param 10/10 Step 19778/20000
Param 10/10 Step 19779/20000
Param 10/10 Step 19780/20000
Param 10/10 Step 19781/20000
Param 10/10 Step 19782/20000
Param 10/10 Step 19783/20000
Param 10/10 Step 19784/20000
Param 10/10 Step 19785/20000
Param 10/10 Step 19786/20000
Param 10/10 Step 19787/20000
Param 10/10 Step 19788/20000
Param 10/10 Step 19789/20000
Param 10/10 Step 19790/20000
Param 10/10 Step 19791/20000
Param 10/10 Step 19792/20000
Param 10/10 Step 19793/20000
Param 10/10 Step 19794/20000
Param 10/10 Step 19795/20000
Param 10/10 Step 19796/20000
Param 10/10 Step 19797/20000
Param 10/10 Step 19798/20000
Param 10/10 Step 19799/20000
Param 10/10 Step 19800/20000
Param 10/10 Step 19801/20000
Param 10/10 Step 19802/20000
Param 10/10 Step 19803/20000
Param 10/10 Step 19804/20000
Param 10/10 Step 19805/20000
Param 10/10 Step 19806/20000
Param 10/10 Step 19807/20000
Param 10/10 Step 19808/20000
Param 10/10 Step 19809/20000
Param 10/10 Step 19810/20000
Param 10/10 Step 19811/20000
Param 10/10 Step 19812/20000
Param 10/10 Step 19813/20000
Param 10/10 Step 19814/20000
Param 10/10 Step 19815/20000
Param 10/10 Step 19816/20000
Param 10/10 Step 19817/20000
Param 10/10 Step 19818/20000
Param 10/10 Step 19819/20000
Param 10/10 Step 19820/20000
Param 10/10 Step 19821/20000
Param 10/10 Step 19822/20000
Param 10/10 Step 19823/20000
Param 10/10 Step 19824/20000
Param 10/10 Step 19825/20000
Param 10/10 Step 19826/20000
Param 10/10 Step 19827/20000
Param 10/10 Step 19828/20000
Param 10/10 Step 19829/20000
Param 10/10 Step 19830/20000
Param 10/10 Step 19831/20000
Param 10/10 Step 19832/20000
Param 10/10 Step 19833/20000
Param 10/10 Step 19834/20000
Param 10/10 Step 19835/20000
Param 10/10 Step 19836/20000
Param 10/10 Step 19837/20000
Param 10/10 Step 19838/20000
Param 10/10 Step 19839/20000
Param 10/10 Step 19840/20000
Param 10/10 Step 19841/20000
Param 10/10 Step 19842/20000
Param 10/10 Step 19843/20000
Param 10/10 Step 19844/20000
Param 10/10 Step 19845/20000
Param 10/10 Step 19846/20000
Param 10/10 Step 19847/20000
Param 10/10 Step 19848/20000
Param 10/10 Step 19849/20000
Param 10/10 Step 19850/20000
Param 10/10 Step 19851/20000
Param 10/10 Step 19852/20000
Param 10/10 Step 19853/20000
Param 10/10 Step 19854/20000
Param 10/10 Step 19855/20000
Param 10/10 Step 19856/20000
Param 10/10 Step 19857/20000
Param 10/10 Step 19858/20000
Param 10/10 Step 19859/20000
Param 10/10 Step 19860/20000
Param 10/10 Step 19861/20000
Param 10/10 Step 19862/20000
Param 10/10 Step 19863/20000
Param 10/10 Step 19864/20000
Param 10/10 Step 19865/20000
Param 10/10 Step 19866/20000
Param 10/10 Step 19867/20000
Param 10/10 Step 19868/20000
Param 10/10 Step 19869/20000
Param 10/10 Step 19870/20000
Param 10/10 Step 19871/20000
Param 10/10 Step 19872/20000
Param 10/10 Step 19873/20000
Param 10/10 Step 19874/20000
Param 10/10 Step 19875/20000
Param 10/10 Step 19876/20000
Param 10/10 Step 19877/20000
Param 10/10 Step 19878/20000
Param 10/10 Step 19879/20000
Param 10/10 Step 19880/20000
Param 10/10 Step 19881/20000
Param 10/10 Step 19882/20000
Param 10/10 Step 19883/20000
Param 10/10 Step 19884/20000
Param 10/10 Step 19885/20000
Param 10/10 Step 19886/20000
Param 10/10 Step 19887/20000
Param 10/10 Step 19888/20000
Param 10/10 Step 19889/20000
Param 10/10 Step 19890/20000
Param 10/10 Step 19891/20000
Param 10/10 Step 19892/20000
Param 10/10 Step 19893/20000
Param 10/10 Step 19894/20000
Param 10/10 Step 19895/20000
Param 10/10 Step 19896/20000
Param 10/10 Step 19897/20000
Param 10/10 Step 19898/20000
Param 10/10 Step 19899/20000
Param 10/10 Step 19900/20000
Param 10/10 Step 19901/20000
Param 10/10 Step 19902/20000
Param 10/10 Step 19903/20000
Param 10/10 Step 19904/20000
Param 10/10 Step 19905/20000
Param 10/10 Step 19906/20000
Param 10/10 Step 19907/20000
Param 10/10 Step 19908/20000
Param 10/10 Step 19909/20000
Param 10/10 Step 19910/20000
Param 10/10 Step 19911/20000
Param 10/10 Step 19912/20000
Param 10/10 Step 19913/20000
Param 10/10 Step 19914/20000
Param 10/10 Step 19915/20000
Param 10/10 Step 19916/20000
Param 10/10 Step 19917/20000
Param 10/10 Step 19918/20000
Param 10/10 Step 19919/20000
Param 10/10 Step 19920/20000
Param 10/10 Step 19921/20000
Param 10/10 Step 19922/20000
Param 10/10 Step 19923/20000
Param 10/10 Step 19924/20000
Param 10/10 Step 19925/20000
Param 10/10 Step 19926/20000
Param 10/10 Step 19927/20000
Param 10/10 Step 19928/20000
Param 10/10 Step 19929/20000
Param 10/10 Step 19930/20000
Param 10/10 Step 19931/20000
Param 10/10 Step 19932/20000
Param 10/10 Step 19933/20000
Param 10/10 Step 19934/20000
Param 10/10 Step 19935/20000
Param 10/10 Step 19936/20000
Param 10/10 Step 19937/20000
Param 10/10 Step 19938/20000
Param 10/10 Step 19939/20000
Param 10/10 Step 19940/20000
Param 10/10 Step 19941/20000
Param 10/10 Step 19942/20000
Param 10/10 Step 19943/20000
Param 10/10 Step 19944/20000
Param 10/10 Step 19945/20000
Param 10/10 Step 19946/20000
Param 10/10 Step 19947/20000
Param 10/10 Step 19948/20000
Param 10/10 Step 19949/20000
Param 10/10 Step 19950/20000
Param 10/10 Step 19951/20000
Param 10/10 Step 19952/20000
Param 10/10 Step 19953/20000
Param 10/10 Step 19954/20000
Param 10/10 Step 19955/20000
Param 10/10 Step 19956/20000
Param 10/10 Step 19957/20000
Param 10/10 Step 19958/20000
Param 10/10 Step 19959/20000
Param 10/10 Step 19960/20000
Param 10/10 Step 19961/20000
Param 10/10 Step 19962/20000
Param 10/10 Step 19963/20000
Param 10/10 Step 19964/20000
Param 10/10 Step 19965/20000
Param 10/10 Step 19966/20000
Param 10/10 Step 19967/20000
Param 10/10 Step 19968/20000
Param 10/10 Step 19969/20000
Param 10/10 Step 19970/20000
Param 10/10 Step 19971/20000
Param 10/10 Step 19972/20000
Param 10/10 Step 19973/20000
Param 10/10 Step 19974/20000
Param 10/10 Step 19975/20000
Param 10/10 Step 19976/20000
Param 10/10 Step 19977/20000
Param 10/10 Step 19978/20000
Param 10/10 Step 19979/20000
Param 10/10 Step 19980/20000
Param 10/10 Step 19981/20000
Param 10/10 Step 19982/20000
Param 10/10 Step 19983/20000
Param 10/10 Step 19984/20000
Param 10/10 Step 19985/20000
Param 10/10 Step 19986/20000
Param 10/10 Step 19987/20000
Param 10/10 Step 19988/20000
Param 10/10 Step 19989/20000
Param 10/10 Step 19990/20000
Param 10/10 Step 19991/20000
Param 10/10 Step 19992/20000
Param 10/10 Step 19993/20000
Param 10/10 Step 19994/20000
Param 10/10 Step 19995/20000
Param 10/10 Step 19996/20000
Param 10/10 Step 19997/20000
Param 10/10 Step 19998/20000
Param 10/10 Step 19999/20000
Param 10/10 Step 20000/20000
|
8 Deep Learning/2 CNN/CNN.ipynb | ###Markdown
1 - Building the CNN Importing the Keras libraries and packages
###Code
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
###Output
Using TensorFlow backend.
###Markdown
Build CNN
###Code
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
#no of feature detector 32
#dimention of the feature detector Matrix(3,3)
#input Image are color so input shape (64,64,3) #Images are 64x64 pixels(Because we are working on CPU)
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
###Output
_____no_output_____
###Markdown
2 - Fitting the CNN to the images
###Code
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('E:\\Edu\\Data Science and ML\\Machinelearningaz\\Datasets\\Part 8 - Deep Learning\\Section 40 - Convolutional Neural Networks (CNN)\\dataset\\training_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('E:\\Edu\\Data Science and ML\\Machinelearningaz\\Datasets\\Part 8 - Deep Learning\\Section 40 - Convolutional Neural Networks (CNN)\\dataset\\test_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
classifier.fit_generator(training_set,
steps_per_epoch = 8000,
epochs = 1,
validation_data = test_set,
validation_steps = 2000)#Make epochs as 25
###Output
WARNING:tensorflow:From C:\Users\Jakkani\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Epoch 1/1
5107/8000 [==================>...........] - ETA: 52:27 - loss: 0.4338 - acc: 0.7877
###Markdown
3 - Making new predictions
###Code
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('E:\\Edu\\Data Science and ML\\Machinelearningaz\\Datasets\\Part 8 - Deep Learning\\Section 40 - Convolutional Neural Networks (CNN)\\dataset\\single_prediction\\cat_or_dog_1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
print(prediction)
###Output
_____no_output_____ |
WRF/GIS_&_Datasets/API_access_to_Copernicus.ipynb | ###Markdown
ProjectX 2020 UofT AI Competition - File metadata| Date created | Title | Type | Domain | Version |License / confidentiality| --- | --- | --- | --- | --- | --- || 10.09.20 | Copernicus data access API | Example | GIS datasets | 1.0 | For internal use only, contains credentials | A simple example notebook to test access to the datasets. For a later use, jp2 images should be associated to a geopandas dataframe, otherwise they are difficult to work with. API access to Copernicus' data Installation of sentinelsat and rasterIO
###Code
!pip3 install sentinelsat
!pip3 install rasterIO
###Output
Requirement already satisfied: sentinelsat in /usr/local/lib/python3.6/dist-packages (0.14)
Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sentinelsat) (7.1.2)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from sentinelsat) (1.15.0)
Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from sentinelsat) (2.23.0)
Requirement already satisfied: html2text in /usr/local/lib/python3.6/dist-packages (from sentinelsat) (2020.1.16)
Requirement already satisfied: geojson>=2 in /usr/local/lib/python3.6/dist-packages (from sentinelsat) (2.5.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from sentinelsat) (4.41.1)
Requirement already satisfied: geomet in /usr/local/lib/python3.6/dist-packages (from sentinelsat) (0.2.1.post1)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->sentinelsat) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->sentinelsat) (2020.6.20)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->sentinelsat) (1.24.3)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->sentinelsat) (2.10)
Requirement already satisfied: geopandas in /usr/local/lib/python3.6/dist-packages (0.8.1)
Requirement already satisfied: pandas>=0.23.0 in /usr/local/lib/python3.6/dist-packages (from geopandas) (1.0.5)
Requirement already satisfied: pyproj>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from geopandas) (2.6.1.post1)
Requirement already satisfied: shapely in /usr/local/lib/python3.6/dist-packages (from geopandas) (1.7.1)
Requirement already satisfied: fiona in /usr/local/lib/python3.6/dist-packages (from geopandas) (1.8.16)
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.0->geopandas) (2.8.1)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.0->geopandas) (2018.9)
Requirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.0->geopandas) (1.18.5)
Requirement already satisfied: click-plugins>=1.0 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (1.1.1)
Requirement already satisfied: munch in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (2.5.0)
Requirement already satisfied: six>=1.7 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (1.15.0)
Requirement already satisfied: cligj>=0.5 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (0.5.0)
Requirement already satisfied: attrs>=17 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (20.1.0)
Requirement already satisfied: click<8,>=4.0 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (7.1.2)
Requirement already satisfied: rasterIO in /usr/local/lib/python3.6/dist-packages (1.1.5)
Requirement already satisfied: attrs in /usr/local/lib/python3.6/dist-packages (from rasterIO) (20.1.0)
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from rasterIO) (1.18.5)
Requirement already satisfied: click<8,>=4.0 in /usr/local/lib/python3.6/dist-packages (from rasterIO) (7.1.2)
Requirement already satisfied: click-plugins in /usr/local/lib/python3.6/dist-packages (from rasterIO) (1.1.1)
Requirement already satisfied: affine in /usr/local/lib/python3.6/dist-packages (from rasterIO) (2.3.0)
Requirement already satisfied: cligj>=0.5 in /usr/local/lib/python3.6/dist-packages (from rasterIO) (0.5.0)
Requirement already satisfied: snuggs>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from rasterIO) (1.4.7)
Requirement already satisfied: pyparsing>=2.1.6 in /usr/local/lib/python3.6/dist-packages (from snuggs>=1.4.1->rasterIO) (2.4.7)
###Markdown
Access and download
###Code
from sentinelsat import SentinelAPI
#Initializing the API with credentials
#(people from MLJC and ProjectX2020 Team are authorized to use my account!)
user = 'vpagliarino'
password = 'copaccess2020valerio'
api = SentinelAPI(user, password, 'https://scihub.copernicus.eu/dhus')
#Downloading data by key obtained at https://scihub.copernicus.eu/dhus/#/home
res = api.download("d66a1f73-f2f5-4e11-95fd-2f85ff9ab722")
#Unzipping the archive
import zipfile
with zipfile.ZipFile(res['path'], 'r') as zip_ref:
zip_ref.extractall('./')
#Filtering all files (including subfolders) ending with given extension
a = []
import os
i = 0
for root, dirs, files in os.walk("./"):
for file in files:
if file.endswith(".jp2"):
print(i, ") ", os.path.join(root, file))
i=i+1
a.append(os.path.join(root, file))
import rasterio
import numpy as np
arrs = []
filenum = 25 #Indice corripondente all'elenco ^^
with rasterio.open(a[filenum]) as f:
arrs.append(f.read(1))
data = np.array(arrs, dtype=arrs[0].dtype)
data
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1,1, figsize=(12,12))
ax.matshow(data[0])
###Output
_____no_output_____ |
notebooks/cirrus-ngs/ChiPSeqPipeline.ipynb | ###Markdown
ChIPSeq Pipeline Be sure to install paramiko and scp with pip before using this notebook 1. Configure AWS key pair, data location on S3 and the project information This cell only contains information that you, the user, should input. String Fields**s3_input_files_address**: This is an s3 path to where your input fastq files are found. This shouldn't be the path to the actual fastq files, just to the directory containing all of them. All fastq files must be in the same s3 bucket.**s3_output_files_address**: This is an s3 path to where you would like the outputs from your project to be uploaded. This will only be the root directory, please see the README for information about exactly how outputs are structured**design_file**: This is a path to your design file for this project. Please see the README for the format specification for the design files. **your_cluster_name**: This is the name given to your cluster when it was created using cfncluster. **private_key**: The path to your private key needed to access your cluster.**project_name**: Name of your project. There should be no whitespace.**workflow**: The workflow you want to run for this project. For the ChIPSeq pipeline the only possible workflow is "homer".**genome**: The name of the reference you want to use for your project. Currently only "hg19" and "mm10" are supported here.**style**: This will always be either "factor" or "histone" depending on your purposes. The "factor" style is more fitting for transcription factor analysis while the "histone" style is intended for histone analysis. More details can be found [here](http://homer.ucsd.edu/homer/ngs/peaks.html) analysis_stepsThis is a set of strings that contains the steps you would like to run. The order of the steps does not matter.posible homer steps: "fastqc", "trim", "align", "multiqc", "make_tag_directory", "make_UCSC_file", "find_peaks", "annotate_peaks", "pos2bed", "find_motifs_genome"
###Code
import os
import sys
sys.path.append("../../src/cirrus_ngs")
from cfnCluster import CFNClusterManager, ConnectionManager
from util import PipelineManager
from util import DesignFileLoader
#s3 addresses for input files and output files
s3_input_files_address = ""
s3_output_files_address = ""
## CFNCluster name
your_cluster_name = ""
## The private key pair for accessing cluster.
private_key = ""
## Project information
project_name = ""
#options: homer
workflow = "homer"
#options: hg19, mm10
genome = "hg19"
#options: factor, histone
style = "histone"
## If delete cfncluster after job is done.
delete_cfncluster= False
##order does not matter
##can be fastqc, trim, bowtie, multiqc, make_tag_directory, make_UCSC_file,
#find_peaks, annotate_peaks, pos2bed, find_motifs_genome
analysis_steps = {
"fastqc"
,"trim"
,"align"
,"multiqc"
,"make_tag_directory"
,"make_UCSC_file"
,"find_peaks"
,"annotate_peaks"
,"pos2bed"
,"find_motifs_genome"
}
#path to chipseq design file
#examples in cirrus_root/data/cirrus-ngs/
design_file = ""
print("variables set")
###Output
variables set
###Markdown
2. Create CFNCluster Following cell connects to your cluster. Run before step 3.
###Code
## Create a new cluster
master_ip_address = CFNClusterManager.create_cfn_cluster(cluster_name=your_cluster_name)
ssh_client = ConnectionManager.connect_master(hostname=master_ip_address,
username="ec2-user",
private_key_file=private_key)
###Output
cluster mustafa8 does exist.
warning: There is a newer version 1.4.2 of cfncluster available.
Status: CREATE_COMPLETE
Status: CREATE_COMPLETE
MasterServer: RUNNING
MasterServer: RUNNING
Output:"MasterPublicIP"="34.218.52.146"
Output:"MasterPrivateIP"="172.31.47.153"
Output:"GangliaPublicURL"="http://34.218.52.146/ganglia/"
Output:"GangliaPrivateURL"="http://172.31.47.153/ganglia/"
connecting
connected
###Markdown
3. Run the pipeline This cell actually executes your pipeline. Make sure that steps 1 and 2 have been completed before running.
###Code
sample_list, group_list, pairs_list = DesignFileLoader.load_design_file(design_file)
PipelineManager.execute("ChiPSeq", ssh_client, project_name, workflow, analysis_steps, s3_input_files_address,
sample_list, group_list, s3_output_files_address, genome, style, pairs_list)
###Output
[['chipseq_sample1_chip.fastq.gz'], ['chipseq_sample1_input.fastq.gz'], ['chipseq_sample2_chip.fastq.gz'], ['chipseq_sample2_input.fastq.gz']]
['groupA', 'groupA', 'groupB', 'groupB']
{'chipseq_sample1_chip': 'chipseq_sample1_input', 'chipseq_sample2_chip': 'chipseq_sample2_input'}
making the yaml file...
copying yaml file to remote master node...
histone_output_check.yaml
/shared/workspace/Pipelines/yaml_files/ChiPSeq/homer
executing pipeline...
Executing nohup bash /shared/workspace/Pipelines/scripts/run.sh /shared/workspace/Pipelines/yaml_files/ChiPSeq/homer/histone_output_check.yaml /shared/workspace/logs/ChiPSeq/homer/histone_output_check ChiPSeq_homer
###Markdown
4. Check status of pipeline This allows you to check the status of your pipeline. You can specify a step or set the step variable to "all". If you specify a step it should be one that is in your analysis_steps set. You can toggle how verbose the status checking is by setting the verbose flag (at the end of the second line) to False.
###Code
step = "all" #can be any step in analysis_steps or "all"
PipelineManager.check_status(ssh_client, step, "ChiPSeq", workflow, project_name, analysis_steps,verbose=True)
###Output
checking status of jobs...
Your project will go through the following steps:
fastqc, trim, align, make_tag_directory, make_UCSC_file, find_peaks, annotate_peaks, pos2bed, find_motifs_genome
The fastqc step calls the fastqc.sh script on the cluster
The fastqc step has finished running without failure
The trim step calls the trim.sh script on the cluster
The trim step has finished running without failure
The align step calls the bowtie.sh script on the cluster
The align step has finished running without failure
The make_tag_directory step calls the make_tag_directory.sh script on the cluster
The make_tag_directory step has finished running without failure
The make_UCSC_file step calls the make_UCSC_file.sh script on the cluster
The make_UCSC_file step has finished running without failure
The find_peaks step calls the findpeaks.sh script on the cluster
The find_peaks step has finished running without failure
The annotate_peaks step calls the annotate_peaks.sh script on the cluster
The annotate_peaks step has finished running without failure
The pos2bed step calls the pos2bed.sh script on the cluster
The pos2bed step has finished running without failure
The find_motifs_genome step calls the find_motifs_genome.sh script on the cluster
The find_motifs_genome step has finished running without failure
Your pipeline has finished
###Markdown
If your pipeline is finished run this cell just in case there's some processes still running.This is only relevant if you plan on doing another run on the same cluster afterwards.
###Code
PipelineManager.stop_pipeline(ssh_client)
###Output
_____no_output_____
###Markdown
5. Display MultiQC report Note: Run the cells below after the multiqc step is done
###Code
# Download the multiqc html file to local
notebook_dir = os.getcwd().split("notebooks")[0] + "data/"
!aws s3 cp $s3_output_files_address/$project_name/$workflow/multiqc_report.html $notebook_dir
from IPython.display import IFrame
IFrame(os.path.relpath("{}multiqc_report.html".format(notebook_dir)), width="100%", height=1000)
###Output
_____no_output_____ |
learntools/ml_insights/nbs/ex2_perm_importance.ipynb | ###Markdown
Exercises IntroYou will think about and calculate permutation importance with a sample of data from the [Taxi Fare Prediction](https://www.kaggle.com/c/new-york-city-taxi-fare-prediction) competition.We won't focus on data exploration or model building for now. You can just run the cell below to - Load the data- Divide the data into training and validation- Build a model that predicts taxi fares- Print a few rows for you to review
###Code
# Loading data, dividing, modeling and EDA below
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
data = pd.read_csv('../input/new-york-city-taxi-fare-prediction/train.csv', nrows=50000)
# Remove data with extreme outlier coordinates or negative fares
data = data.query('pickup_latitude > 40.7 and pickup_latitude < 40.8 and ' +
'dropoff_latitude > 40.7 and dropoff_latitude < 40.8 and ' +
'pickup_longitude > -74 and pickup_longitude < -73.9 and ' +
'dropoff_longitude > -74 and dropoff_longitude < -73.9 and ' +
'fare_amount > 0'
)
y = data.fare_amount
base_features = ['pickup_longitude',
'pickup_latitude',
'dropoff_longitude',
'dropoff_latitude',
'passenger_count']
X = data[base_features]
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
first_model = RandomForestRegressor(n_estimators=30, random_state=1).fit(train_X, train_y)
# Environment Set-Up for feedback system.
import sys
sys.path.append('../input/ml-insights-tools')
from learntools.core import binder
binder.bind(globals())
from ex2 import *
print("Setup Complete")
# show data
print("Data sample:")
data.head()
###Output
_____no_output_____
###Markdown
The following two cells may also be useful to understand the values in the training data:
###Code
train_X.describe()
train_y.describe()
###Output
_____no_output_____
###Markdown
Question 1The first model uses the following features- pickup_longitude- pickup_latitude- dropoff_longitude- dropoff_latitude- passenger_countBefore running any code... which variables seem potentially useful for predicting taxi fares? Do you think permutation importance will necessarily identify these features as important?Once you've thought about it, run `q_1.solution()` below to see how you might think about this before running the code.
###Code
# q_1.solution()
###Output
_____no_output_____
###Markdown
Question 2Create a `PermutationImportance` object called `perm` to show the importances from `first_model`. Fit it with the appropriate data and show the weights.For your convenience, the code from the tutorial has been copied into a comment in this code cell.
###Code
# import eli5
# from eli5.sklearn import PermutationImportance
# Make a small change to the code below to use in this problem.
# perm = PermutationImportance(my_model, random_state=1).fit(val_X, val_y)
q_2.check()
# uncomment the following line to visualize your results
# eli5.show_weights(perm, feature_names = val_X.columns.tolist())
###Output
_____no_output_____
###Markdown
Uncomment the lines below for a hint or to see the solution.
###Code
# q_2.hint()
# q_2.solution()
###Output
_____no_output_____
###Markdown
Question 3Before seeing these results, we might have expected each of the 4 directional features to be equally important.But, on average, the latitude features matter more than the longititude features. Can you come up with any hypotheses for this?After you've thought about it, check here for some possible explanations:
###Code
# q_3.solution()
###Output
_____no_output_____
###Markdown
Question 4Without detailed knowledge of New York City, it's difficult to rule out most hypotheses about why latitude features matter more than longitude.A good next step is to disentangle the effect of being in certain parts of the city from the effect of total distance traveled. The code below creates new features for longitudinal and latitudinal distance. It then builds a model that adds these new features to those you already had.Fill in two lines of code to calculate and show the importance weights with this new set of features. As usual, you can uncomment lines below to check your code, see a hint or get the solution.
###Code
# create new features
data['abs_lon_change'] = abs(data.dropoff_longitude - data.pickup_longitude)
data['abs_lat_change'] = abs(data.dropoff_latitude - data.pickup_latitude)
features_2 = ['pickup_longitude',
'pickup_latitude',
'dropoff_longitude',
'dropoff_latitude',
'abs_lat_change',
'abs_lon_change']
X = data[features_2]
new_train_X, new_val_X, new_train_y, new_val_y = train_test_split(X, y, random_state=1)
second_model = RandomForestRegressor(n_estimators=30, random_state=1).fit(new_train_X, new_train_y)
# Create a PermutationImportance object on second_model and fit it to new_val_X and new_val_y
# Use a random_state of 1 for reproducible results that match the expected solution.
perm2 = _
# show the weights for the permutation importance you just calculated
_
q_4.check()
###Output
_____no_output_____
###Markdown
How would you interpret these importance scores? Distance traveled seems far more important than any location effects. But the location still affects model predictions, and dropoff location now matters slightly more than pickup location. Do you have any hypotheses for why this might be? The techniques used later in the course will help us dive into this more.
###Code
# q_4.solution()
###Output
_____no_output_____
###Markdown
Question 5A colleague observes that the values for `abs_lon_change` and `abs_lat_change` are pretty small (all values are between -0.1 and 0.1), whereas other variables have larger values. Do you think this could explain why those coordinates had larger permutation importance values in this case? Consider an alternative where you created and used a feature that was 100X as large for these features, and used that larger feature for training and importance calculations. Would this change the outputted permutaiton importance values?Why or why not?After you have thought about your answer, either try this experiment or look up the answer in the cell below
###Code
# q_5.solution()
###Output
_____no_output_____
###Markdown
Question 6You've seen that the feature importance for latitudinal distance is greater than the importance of longitudinal distance. From this, can we conclude whether travelling a fixed latitudinal distance tends to be more expensive than traveling the same longitudinal distance?Why or why not? Check your answer below.
###Code
# q_6.solution()
###Output
_____no_output_____ |
notebooks/machine-learning/MATPLOTLIB_03_Simple_Scatter_Plots.ipynb | ###Markdown
Simple Scatter Plots Another commonly used plot type is the simple scatter plot, a close cousin of the line plot.Instead of points being joined by line segments, here the points are represented individually with a dot, circle, or other shape.We’ll start by setting up the notebook for plotting and importing the functions we will use:
###Code
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
###Output
_____no_output_____
###Markdown
Scatter Plots with ``plt.plot``In the previous section we looked at ``plt.plot``/``ax.plot`` to produce line plots.It turns out that this same function can produce scatter plots as well:
###Code
x = np.linspace(0, 10, 30)
y = np.sin(x)
plt.plot(x, y, 'o', color='black');
###Output
_____no_output_____
###Markdown
The third argument in the function call is a character that represents the type of symbol used for the plotting. Just as you can specify options such as ``'-'``, ``'--'`` to control the line style, the marker style has its own set of short string codes. The full list of available symbols can be seen in the documentation of ``plt.plot``, or in Matplotlib's online documentation. Most of the possibilities are fairly intuitive, and we'll show a number of the more common ones here:
###Code
rng = np.random.RandomState(0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
plt.plot(rng.rand(5), rng.rand(5), marker,
label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8);
###Output
_____no_output_____
###Markdown
For even more possibilities, these character codes can be used together with line and color codes to plot points along with a line connecting them:
###Code
plt.plot(x, y, '-ok');
###Output
_____no_output_____
###Markdown
Additional keyword arguments to ``plt.plot`` specify a wide range of properties of the lines and markers:
###Code
plt.plot(x, y, '-p', color='gray',
markersize=15, linewidth=4,
markerfacecolor='white',
markeredgecolor='gray',
markeredgewidth=2)
plt.ylim(-1.2, 1.2);
###Output
_____no_output_____
###Markdown
This type of flexibility in the ``plt.plot`` function allows for a wide variety of possible visualization options.For a full description of the options available, refer to the ``plt.plot`` documentation. Scatter Plots with ``plt.scatter``A second, more powerful method of creating scatter plots is the ``plt.scatter`` function, which can be used very similarly to the ``plt.plot`` function:
###Code
plt.scatter(x, y, marker='o');
###Output
_____no_output_____
###Markdown
The primary difference of ``plt.scatter`` from ``plt.plot`` is that it can be used to create scatter plots where the properties of each individual point (size, face color, edge color, etc.) can be individually controlled or mapped to data.Let's show this by creating a random scatter plot with points of many colors and sizes.In order to better see the overlapping results, we'll also use the ``alpha`` keyword to adjust the transparency level:
###Code
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
cmap='viridis')
plt.colorbar(); # show color scale
###Output
_____no_output_____
###Markdown
Notice that the color argument is automatically mapped to a color scale (shown here by the ``colorbar()`` command), and that the size argument is given in pixels.In this way, the color and size of points can be used to convey information in the visualization, in order to visualize multidimensional data.For example, we might use the Iris data from Scikit-Learn, where each sample is one of three types of flowers that has had the size of its petals and sepals carefully measured:
###Code
from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data.T
plt.scatter(features[0], features[1], alpha=0.2,
s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1]);
###Output
_____no_output_____ |
S06Pandas/E01SFSalariesExercise.ipynb | ###Markdown
___ ___ SF Salaries Exercise Welcome to a quick exercise for you to practice your pandas skills! We will be using the [SF Salaries Dataset](https://www.kaggle.com/kaggle/sf-salaries) from Kaggle! Just follow along and complete the tasks outlined in bold below. The tasks will get harder and harder as you go along. ** Import pandas as pd.**
###Code
import pandas as pd
import numpy as np
import warnings # to remove the warning message during data import
warnings.filterwarnings('ignore') # suppress all warnings
###Output
_____no_output_____
###Markdown
** Read Salaries.csv as a dataframe called sal.**
###Code
sal = pd.read_csv('Salaries.csv', na_values='Not Provided')
###Output
_____no_output_____
###Markdown
** Check the head of the DataFrame. **
###Code
sal.head()
###Output
_____no_output_____
###Markdown
** Use the .info() method to find out how many entries there are.**
###Code
sal.info()
###Output
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 148654 entries, 0 to 148653
Data columns (total 13 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Id 148654 non-null int64
1 EmployeeName 148652 non-null object
2 JobTitle 148654 non-null object
3 BasePay 148045 non-null float64
4 OvertimePay 148650 non-null float64
5 OtherPay 148650 non-null float64
6 Benefits 112491 non-null float64
7 TotalPay 148654 non-null float64
8 TotalPayBenefits 148654 non-null float64
9 Year 148654 non-null int64
10 Notes 0 non-null float64
11 Agency 148654 non-null object
12 Status 38119 non-null object
dtypes: float64(7), int64(2), object(4)
memory usage: 14.7+ MB
###Markdown
**What is the average BasePay ?**
###Code
sal['BasePay'].mean()
###Output
_____no_output_____
###Markdown
** What is the highest amount of OvertimePay in the dataset ? **
###Code
sal['OvertimePay'].max()
###Output
_____no_output_____
###Markdown
** What is the job title of JOSEPH DRISCOLL ? Note: Use all caps, otherwise you may get an answer that doesn't match up (there is also a lowercase Joseph Driscoll). **
###Code
sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['JobTitle']
###Output
_____no_output_____
###Markdown
** How much does JOSEPH DRISCOLL make (including benefits)? **
###Code
sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['TotalPayBenefits']
###Output
_____no_output_____
###Markdown
** What is the name of highest paid person (including benefits)?**
###Code
sal[sal['TotalPay'] == sal['TotalPay'].max()]
###Output
_____no_output_____
###Markdown
** What is the name of lowest paid person (including benefits)? Do you notice something strange about how much he or she is paid?**
###Code
sal[sal['TotalPay'] == sal['TotalPay'].min()]
###Output
_____no_output_____
###Markdown
** What was the average (mean) BasePay of all employees per year? (2011-2014) ? **
###Code
sal.groupby('Year').mean()['BasePay']
###Output
_____no_output_____
###Markdown
** How many unique job titles are there? **
###Code
sal['JobTitle'].nunique()
###Output
_____no_output_____
###Markdown
** What are the top 5 most common jobs? **
###Code
sal['JobTitle'].value_counts().sort_values(ascending=False)[:5]
###Output
_____no_output_____
###Markdown
** How many Job Titles were represented by only one person in 2013? (e.g. Job Titles with only one occurence in 2013?) **
###Code
year2013 = sal[sal['Year']==2013]
year2013.groupby('JobTitle').count()
###Output
_____no_output_____ |
doc/1-DS1000E-Waveforms.ipynb | ###Markdown
Parsing DS1000E Rigol Waveforms**Scott Prahl****Feb 2020**
###Code
import sys
import numpy as np
import matplotlib.pyplot as plt
try:
import RigolWFM.wfm as rigol
except:
print("***** You need to install the module to read Rigol files first *****")
print("***** Execute the following line in a new cell, then retry *****")
print()
print("!{sys.executable} -m pip install RigolWFM")
###Output
_____no_output_____
###Markdown
IntroductionThis notebook illustrates shows how to extract signals from a `.wfm` file created by a the Rigol DS1000E scope. It also validates that the process works by comparing with `.csv` and screenshots.Two different `.wfm` files are examined one for the DS1052E scope and one for the DS1102E scope. The accompanying `.csv` files seem to have t=0 in the zero in the center of the waveform. The list of Rigol scopes that should produce the same file format are:
###Code
print(rigol.DS1000E_scopes[7:])
###Output
['DS1102E', 'DS1052E', 'DS1102D', 'DS1052D']
###Markdown
DS1052E Look at a screen shotStart with a `.wfm` file from a Rigol DS1052E scope. It should look something like this Look at the data in the `.csv` fileFirst let's look at plot of the data from the corresponding `.csv` file.
###Code
csv_filename_52 = "https://github.com/scottprahl/RigolWFM/raw/master/wfm/DS1052E.csv"
csv_data = np.genfromtxt(csv_filename_52, delimiter=',', skip_header=2).T
plt.subplot(211)
plt.plot(csv_data[0]*1e6,csv_data[1], color='green')
plt.title("DS1052E from .csv file")
plt.ylabel("Volts (V)")
plt.xlim(-0.6,0.6)
plt.xticks([])
plt.subplot(212)
plt.plot(csv_data[0]*1e6,csv_data[2], color='red')
plt.xlabel("Time (µs)")
plt.ylabel("Volts (V)")
plt.xlim(-0.6,0.6)
plt.show()
###Output
_____no_output_____
###Markdown
Now for the `.wfm` dataFirst a textual description.
###Code
# raw=true is needed because this is a binary file
wfm_url = "https://github.com/scottprahl/RigolWFM/raw/master/wfm/DS1052E.wfm" + "?raw=true"
w = rigol.Wfm.from_url(wfm_url, kind='1000E')
description = w.describe()
print(description)
ch = w.channels[0]
plt.subplot(211)
plt.plot(ch.times*1e6, ch.volts, color='green')
plt.title("DS1052E from .wfm file")
plt.ylabel("Volts (V)")
plt.xlim(-0.6,0.6)
plt.xticks([])
ch = w.channels[0]
plt.subplot(212)
plt.plot(ch.times*1e6, ch.volts, color='red')
plt.xlabel("Time (µs)")
plt.ylabel("Volts (V)")
plt.xlim(-0.6,0.6)
plt.show()
###Output
_____no_output_____
###Markdown
DS1102E First the `.csv` dataThis file only has one active channel. Let's look at what the accompanying `.csv` data looks like.
###Code
csv_filename = "https://github.com/scottprahl/RigolWFM/raw/master/wfm/DS1102E-B.csv"
my_data = np.genfromtxt(csv_filename, delimiter=',', skip_header=2).T
plt.plot(my_data[0]*1e6, my_data[1])
plt.xlabel("Time (µs)")
plt.ylabel("Volts (V)")
plt.title("DS1102E-B with a single trace")
plt.show()
###Output
_____no_output_____
###Markdown
Now for the `wfm` dataFirst let's have look at the description of the internal file structure. We see that only channel 1 has been enabled.
###Code
# raw=true is needed because this is a binary file
wfm_url = "https://github.com/scottprahl/RigolWFM/raw/master/wfm/DS1102E-B.wfm" + "?raw=true"
w = rigol.Wfm.from_url(wfm_url, kind='DS1102E')
description = w.describe()
print(description)
ch = w.channels[0]
plt.plot(ch.times*1e6,ch.volts, color='green')
plt.title("DS1102E")
plt.ylabel("Volts (V)")
plt.xlabel("Time (µs)")
plt.ylabel("Volts (V)")
plt.xlim(-6,6)
plt.show()
###Output
_____no_output_____ |
utf-8''Small_talk_classification.ipynb | ###Markdown
Preprocessing of the text data
###Code
# remove special characters, numbers, punctuations
data['message_pre'] = data['message'].str.replace("[^a-zA-Z#]", " ")
data.head()
data['message_pre']=data['message_pre'].apply(lambda x: x.split(' '))
data.head()
from nltk.stem.porter import *
stemmer = PorterStemmer()
data['message_pre']=data['message_pre'].apply(lambda x: [stemmer.stem(i) for i in x])
data.head()
data['message_pre']=data['message_pre'].apply(lambda x: ' '.join(x))
data.head()
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(max_df=0.90, min_df=2, max_features=1000, stop_words='english')
# TF-IDF feature matrix
tfidf = tfidf_vectorizer.fit_transform(data['message_pre'])
tfidf.shape
tfidf.shape[0]*0.80,tfidf.shape[0]*0.20
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
# splitting data into training and validation set
xtrain_bow, xvalid_bow, ytrain, yvalid = train_test_split(tfidf, data['label'], random_state=42, test_size=0.2)
xtrain_bow.shape, ytrain.shape
xvalid_bow.shape,yvalid.shape
lreg = LogisticRegression()
lreg.fit(xtrain_bow, ytrain)
prediction = lreg.predict_proba(xvalid_bow)
prediction_int = prediction[:,1] >= 0.5
prediction_int = prediction_int.astype(np.int)
f1_score(yvalid, prediction_int)
###Output
_____no_output_____
###Markdown
Accuracy varying with threshold0.8685258964143426 - 0.40.8619169510807736 -0.30.8694170133841295 -0.5
###Code
yvalid.value_counts()
pd.Series(prediction_int).value_counts()
from sklearn.metrics import confusion_matrix
confusion_matrix(yvalid, prediction_int)
###Output
_____no_output_____ |
locust_stretch_receptor.ipynb | ###Markdown
###Code
print("Test")
###Output
Test
|
02-Syntax-and-Semantics/Assignment-01.ipynb | ###Markdown
This exercise is to test your understanding of Python basics.Answer the questions and complete the tasks outlined below; use the specific method described if applicable. In order to get complete points on your homework assigment you have to a) answer the multiple choice questions on the course site, and b) provide rationale for your answers. Both your answer and rationale will be graded. Question 1 & 2**What is 9 to the power of 7?**
###Code
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 3 & 4**What is the quotient and remainder of 453634/32?**
###Code
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 5 & 6Write a statement to check whether `a` is a multiple of 7 and within the range of [1000, 1800) or (0, 300]. **What is the outcome of `a = 833`?**Note: (0, 300] represents a range from 0 to 300, where 0 is not included in the range, but 300 is.
###Code
a = 833
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 7**Given this nested list, what indexing yields to the word "hello"?**Hint: write a one-line python code that extracts the word "hello" from the given list.
###Code
lst = [[5,88,10,[100,200,{'target':[1,2,3,'hello']}],23,11],1,71,2,[3,4],'bye']
print(lst)
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 8 & 9Using a list comprehension, create a new list that is a subset of `L1`, which contains only the even numbers from `L1`. This list comprehension should convert the members of the new list into absolute values (using `abs()` function). Call this new list `L2`.**What is the sum of all of the elements of `L2`?** Hint: Use `sum(L2)` to get the sum of all the elements.
###Code
L1 = [64, 34, 112, 91, 62, 40, 117, 80, 96, 34, 48, -9, -33,
99, 16, 118, -51, 60, 115, 4, -10, 82, -7, 77, -33, -40,
77, 90, -9, 52, -44, 25, -43, 85, -37, 92, 25, -45, 3,
103, 22, 39, -52, 74, -54, -76, -10, 5, -54, 95, -59, -2,
110, 63, -53, 113, -143, 18, 49, -20, 81, -67, 1, 38, -24,
57, -11, -69, -66, -67, -68, -16, 64, -34, 52, -37, -7, -40,
11, -3, 76, 91, -57, -48, -10, -16, 14, 13, -65]
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 10 & 11Write a function that receives a list of integer numbers and returns a list of numbers that are multiples of 4. Call this function `mult4_filter()`.**Given the list L3 below, how many elements does the outcome of mult4_filter(L3) have?**Hint: use `len(mult4_filter(L3))` to get the number of elements.
###Code
L3 = [15, 11, 1, 3, 13, 3, 14, 16, 17, 17, 6, 18, 10, 19, 8, 1, 18,
17, 14, 1, 5, 2, 13, 0, 1, 13, 16, 8, 5, 11, 12, 8, 17, 14,
10, 18, 17, 16, 3, 7, 8, 15, 18, 7, 10, 5, 7, 16, 6, 5, 12]
# Your answer goes here
len(mult4_filter(L3))
###Output
_____no_output_____
###Markdown
Assignment 1This assignment is to test your understanding of Python basics.Answer the questions and complete the tasks outlined below; use the specific method described, if applicable. In order to get complete points on your homework assigment you have to a) complete this notebook, b) based on your results answer the multiple choice questions on QoestromTools. **Important note:** make sure you spend some time to review the basics of python notebooks under the folder `00-Python-Basics` in course repo or [A Whirlwind Tour of Python](https://www.oreilly.com/programming/free/files/a-whirlwind-tour-of-python.pdf). Question 1**What is 9 to the power of 7? (provide simple python code other than recursive multiplications)**
###Code
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 2**What is the quotient and remainder of 453634/34?**
###Code
# Your answer goes here
print('Quotient of 453634/34:')
print('Remainder of 453634/34:')
###Output
Quotient of 453634/34:
Remainder of 453634/34:
###Markdown
Question 3Write a statement to check whether `a` is a multiple of 7 and within the range of [1000, 1800) or (0, 300]. **What is the outcome of `a = 833`?**Note: (0, 300] represents a range from 0 to 300, where 0 is not included in the range, but 300 is.
###Code
a = 833
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 4**Given this nested list, what indexing yields to the word "hello"?**
###Code
lst = [[5,[100,200,{'target':[1,2,3,'hello']}],23,11],1,71,2,[3,4],'bye']
print(lst)
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 5Using a list comprehension, create a new list out of the list `L1`, which contains only the even numbers from `L1`, and converts them into absolute values (using `abs()` function). Call this new list `L2`.**What is the sum of all of the elements of `L2`?** Hint: Use `sum(L2)` to get the sum of all the elements.
###Code
L1 = [64, 34, 112, 91, 62, 40, 117, 80, 96, 34, 48, -9, -33,
99, 16, 118, -51, 60, 115, 4, -10, 82, -7, 77, -33, -40,
77, 90, -9, 52, -44, 25, -43, 28, -37, 92, 25, -45, 3,
103, 22, 39, -52, 74, -54, -76, -10, 5, -54, 95, -59, -2,
110, 63, -53, 113, -43, 18, 49, -20, 81, -67, 1, 38, -24,
57, -11, -69, -66, -67, -68, -16, 64, -34, 52, -37, -7, -40,
11, -3, 76, 91, -57, -48, -10, -16, 14, 13, -65]
# Your answer goes here
###Output
_____no_output_____
###Markdown
Question 6Write a function that receives a list of integer numbers and returns a list of numbers that are multiples of 4. Call this function `mult4_filter()`. Note that, multiples of a number could include negative numbers as well as zero.**Given the list `L3` below how many elements the outcome of `mult4_filter(L3)` has?**Hint: use `len(mult4_filter(L3))` to get the number of elements.
###Code
L3 = [15, 11, 1, 3, 13, 3, 14, 16, 17, 17, 6, 18, 10, 19, 8, 1, 18,
17, 14, 1, 5, 2, 13, 0, 1, 13, 16, 8, 5, 11, 12, 8, 17, 14,
10, 18, 17, 16, 3, 7, 8, 15, 18, 7, 10, 5, 7, 16, 6, 5]
# Your answer goes here
def mult4_filter(L):
# Your code goes here
return
###Output
_____no_output_____ |
Analysis of variance (ANOVA).ipynb | ###Markdown
T-tests with Iris
###Code
df = pd.read_csv('https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv')
df
s = df[df['species'] == 'setosa']
r = df[df['species'] == 'versicolor']
a = df[df['species'] == 'virginica']
print(stats.ttest_ind(s['petal_length'], r['petal_length']))
print(stats.ttest_ind(s['petal_length'], a['petal_length']))
print(stats.ttest_ind(r['petal_length'], a['petal_length']))
print(stats.ttest_ind(s['petal_width'], r['petal_width']))
print(stats.ttest_ind(s['petal_width'], a['petal_width']))
print(stats.ttest_ind(r['petal_width'], a['petal_width']))
print(stats.ttest_ind(s['sepal_length'], r['sepal_length']))
print(stats.ttest_ind(s['sepal_length'], a['sepal_length']))
print(stats.ttest_ind(r['sepal_length'], a['sepal_length']))
print(stats.ttest_ind(s['sepal_width'], r['sepal_width']))
print(stats.ttest_ind(s['sepal_width'], a['sepal_width']))
print(stats.ttest_ind(r['sepal_width'], a['sepal_width']))
###Output
Ttest_indResult(statistic=-39.46866259397272, pvalue=5.717463758170621e-62)
Ttest_indResult(statistic=-49.965703359355636, pvalue=1.5641224158883576e-71)
Ttest_indResult(statistic=-12.603779441384985, pvalue=3.1788195478061495e-22)
Ttest_indResult(statistic=-34.01237858829048, pvalue=4.589080615710866e-56)
Ttest_indResult(statistic=-42.738229672411165, pvalue=3.582719502316063e-65)
Ttest_indResult(statistic=-14.625367047410148, pvalue=2.2304090710248333e-26)
Ttest_indResult(statistic=-10.52098626754911, pvalue=8.985235037487079e-18)
Ttest_indResult(statistic=-15.386195820079404, pvalue=6.892546060674059e-28)
Ttest_indResult(statistic=-5.629165259719801, pvalue=1.7248563024547942e-07)
Ttest_indResult(statistic=9.282772555558111, pvalue=4.362239016010214e-15)
Ttest_indResult(statistic=6.289384996672061, pvalue=8.916634067006443e-09)
Ttest_indResult(statistic=-3.2057607502218186, pvalue=0.0018191004238894803)
###Markdown
Problems with t-testsSome links about the main problem we encounter with t-testing. Website: Multiple t tests and Type I errorhttp://grants.hhp.coe.uh.edu/doconnor/PEP6305/Multiple%20t%20tests.htmWebpage about multiple t tests and Type I errors. Wikipedia: Multiple Comparisons Problemhttps://en.wikipedia.org/wiki/Multiple_comparisons_problemWikipedia page about the multiple comparisons problem.
###Code
plt.hist(r['sepal_length'], label='Versicolor Sepal Length')
plt.hist(a['sepal_length'], label='Virginica Sepal Length')
plt.legend()
plt.show()
stats.f_oneway(s['petal_length'], r['petal_length'], a['petal_length'])
plt.hist(s['petal_length'], label='Setosa Petal Length')
plt.hist(r['petal_length'], label='Versicolor Petal Length')
plt.hist(a['petal_length'], label='Virginica Petal Length')
plt.legend()
plt.show()
###Output
_____no_output_____ |
SIR_model/SIR_Model.ipynb | ###Markdown
S-I-R modelSystem of differential equations:$$\begin{equation} \left\{ \begin{array}{lll} \frac{dS}{dt} = -\frac{\beta SI}{N} \\ \frac{dI}{dt} = \frac{\beta SI}{N} - \gamma I \\ \frac{dR}{dt} = \gamma I \end{array} \right.\end{equation}$$Where $S = $ number of susceptible people $I = $ number of currently infected people $R = $ number of people that have recovered or died from the disease $N =$ "population size" $\beta =$ "infection rate" $\gamma =$ "recovery rate" (This should also include deaths)
###Code
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Pull population and initial conditions from dataN = PopulationS0 = population - total cases I0 = total cases - deaths - recovered R0 = deaths + recovered
###Code
# Total population, N
N = country_population
deaths = country_deaths
#recovered = total_confirmed_cases - deaths
# Initial conditions
R0 = recovered + deaths
I0 = total_confirmed_cases - R0
S0 = N - I0 - R0 #note that S0 is also our upper limit
###Output
_____no_output_____
###Markdown
Estimate parameters from Ryan's model
###Code
# Contact rate, beta, and mean recovery rate, gamma, (in 1/days)
beta = 0.2
gamma = 1./14 #assume 14days is the recovery time
# A grid of time points (in days)
t = np.linspace(0, 160, 160)
# The SIR model differential equations
def deriv(y, t, N, beta, gamma):
S, I, R = y #initial conditions
#model = system of differential equations
dSdt = -beta * S * I / N
dIdt = beta * S * I / N - gamma * I
dRdt = gamma * I
return dSdt, dIdt, dRdt
# Initial conditions vector
y0 = S0, I0, R0
# Integrate the SIR equations over the time grid, t
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, I, R = ret.T
###Output
_____no_output_____
###Markdown
Plot
###Code
# Plot the data on three separate curves for S(t), I(t) and R(t)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)
ax.plot(t, S/N, 'b', alpha=0.5, lw=2, label='Susceptible')
ax.plot(t, I/N, 'r', alpha=0.5, lw=2, label='Infected')
ax.plot(t, R/N, 'g', alpha=0.5, lw=2, label='Recovered with immunity')
ax.set_xlabel('Time /days')
ax.set_ylabel('Number (1000s)')
ax.set_ylim(0,1.2)
ax.yaxis.set_tick_params(length=0)
ax.xaxis.set_tick_params(length=0)
ax.grid(b=True, which='major', c='w', lw=2, ls='-')
legend = ax.legend()
legend.get_frame().set_alpha(0.5)
for spine in ('top', 'right', 'bottom', 'left'):
ax.spines[spine].set_visible(False)
plt.show()
###Output
_____no_output_____
###Markdown
Example
###Code
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Total population, N.
N = 10000
# Initial number of infected and recovered individuals, I0 and R0.
I0, R0 = 50, 20
# Everyone else, S0, is susceptible to infection initially.
S0 = N - I0 - R0
# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).
beta, gamma = 0.2, 1./14
# A grid of time points (in days)
t = np.linspace(0, 160, 160)
# The SIR model differential equations.
def deriv(y, t, N, beta, gamma):
S, I, R = y
dSdt = -beta * S * I / N
dIdt = beta * S * I / N - gamma * I
dRdt = gamma * I
return dSdt, dIdt, dRdt
# Initial conditions vector
y0 = S0, I0, R0
# Integrate the SIR equations over the time grid, t.
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, I, R = ret.T
# Plot the data on three separate curves for S(t), I(t) and R(t)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)
ax.plot(t, S/10000, 'b', alpha=0.5, lw=2, label='Susceptible')
ax.plot(t, I/10000, 'r', alpha=0.5, lw=2, label='Infected')
ax.plot(t, R/10000, 'g', alpha=0.5, lw=2, label='Recovered with immunity')
ax.set_xlabel('Time /days')
ax.set_ylabel('Number (10000s)')
ax.set_ylim(0,1.2)
ax.yaxis.set_tick_params(length=0)
ax.xaxis.set_tick_params(length=0)
ax.grid(b=True, which='major', c='w', lw=2, ls='-')
legend = ax.legend()
legend.get_frame().set_alpha(0.5)
for spine in ('top', 'right', 'bottom', 'left'):
ax.spines[spine].set_visible(False)
plt.show()
###Output
_____no_output_____ |
examples/2020-11-07 NumpyNet Image Classification.ipynb | ###Markdown
Perceptron
###Code
C=NumPyNetBackProp({
'input':num_features, # number of features
'output':(num_classes,'linear'), # number of classes
'cost':'mse',
})
C.fit(data_train.vectors,data_train.targets)
print(("On Training Set:",C.percent_correct(data_train.vectors,data_train.targets)))
print(("On Test Set:",C.percent_correct(data_test.vectors,data_test.targets)))
figure(figsize=(16,4))
for i,t in enumerate(data_train.target_names):
subplot(2,10,i+1)
vector=random_vector(data_train,t)
image.vector_to_image(vector,(8,8))
axis('off')
subplot(2,10,i+11)
image.vector_to_image(C.weights[0][:,i],(8,8))
axis('off')
###Output
_____no_output_____
###Markdown
Backprop
###Code
C=NumPyNetBackProp({
'input':num_features, # number of features
'hidden':[(12,'logistic'),],
'output':(num_classes,'logistic'), # number of classes
'cost':'mse',
})
C.fit(data_train.vectors,data_train.targets,epochs=5000)
print(("On Training Set:",C.percent_correct(data_train.vectors,data_train.targets)))
print(("On Test Set:",C.percent_correct(data_test.vectors,data_test.targets)))
weights_ih=C.weights[0]
weights_hy=C.weights[-1]
weights_ih.shape
for i in range(weights_ih.shape[1]):
subplot(3,4,i+1)
image.vector_to_image(weights_ih[:,i],(8,8))
axis('off')
###Output
_____no_output_____
###Markdown
Convolutional Neural Net
###Code
images=image.load_images('data/digits')
num_classes=len(images.target_names)
images.data=[_/255.0 for _ in images.data]
C=NumPyNetImageNN(
Convolutional_layer(size=3, filters=32, stride=1, pad=True, activation='Relu'),
BatchNorm_layer(),
Maxpool_layer(size=2, stride=1, padding=True),
Connected_layer(outputs=100, activation='Relu'),
BatchNorm_layer(),
Connected_layer(outputs=num_classes, activation='Linear'),
Softmax_layer(spatial=True, groups=1, temperature=1.),
)
images_train,images_test=image.split(images,verbose=False)
summary(images_train)
summary(images_test)
C.fit(images_train,epochs=10,batch=128)
print("On Training Set:",C.percent_correct(images_train))
print("On Test Set:",C.percent_correct(images_test))
###Output
On Training Set: 100.0
On Test Set: 99.72602739726028
|
exo2.1.ipynb | ###Markdown
2.1
###Code
# The sequence we want to analyze
seq = 'GACAGACUCCAUGCACGUGGGUAUCUGUC'
def complement_base(base,material='DNA'):
"""Returns the Watson-Crick complement of a base."""
if base in 'Aa':
if material == 'DNA':
return 'T'
elif material == 'RNA':
return 'U'
elif base in 'TtUu':
return 'A'
elif base in 'Gg':
return 'C'
else:
return 'G'
def reverse_complement(base,material ='DNA'):
reversed_seq= seq[-1::-1]
rev_seq= ''
for base in reversed_seq:
rev_seq+=complement_base(base, material=material)
return rev_seq
reverse_complement(seq,material='DNA')
def display_complements(seq):
"""Print sequence above its reverse complement."""
#compute the reverse_complement
rev_comp=reverse_complement(seq)
#print template
reversed_seq= seq[-1::-1]
print(reversed_seq)
#print base pairs
for base in seq:
print('|', end='')
#print reverse complement
print()
for base in rev_comp:
print(base,end ='')
# Print final newline character
print()
display_complements(seq)
def reverse_complement_without(seq,material='RNA'):
#change easier consise response
seq_=seq.lower()
print(seq_)
seq_1= seq_.replace('u','A')
print(seq_1)
seq_2=seq_1.replace('a','T')
print(seq_2)
seq_3=seq_2.replace('g','C')
seq_4=seq_3.replace('c','G')
rev_seq=seq_4[-1::-1]
return rev_seq
reverse_complement_without(seq,material='DNA')
###Output
gacagacuccaugcacguggguaucuguc
gacagacAccaAgcacgAgggAaAcAgAc
gTcTgTcAccTAgcTcgAgggATAcAgAc
###Markdown
longest common substring
###Code
def longest_common_substring(seq1,seq2):
""" find the longest common substring between sequences """
shorter=seq1
longer=seq2
#initialize my longest substring
long_substring=''
#switch if seq1 is longer
if len(shorter)> len(longer):
shorter,longer= longer,shorter
# i will go from 0 to len(shorter)-1
for i, _ in enumerate(shorter):
#for k: -i:so not out of range and +1 bc the end is not inclusive
for k in range(0,len(shorter)-i+1):
if shorter[i:i+k] in longer:
#temporary variable to store substring
temp= shorter[i:i+k]
#compare my temporary with my longest substring stored if longer change longest substring by value of temp
if len(long_substring) < len(temp):
long_substring=temp
return long_substring
seq1='atatc'
seq2='atatca'
#l=len(seq1)
#print(l)
longest_common_substring(seq1,seq2)
longest_common_substring('ATGC', 'ATGCA')
longest_common_substring('GATGCCATGCA', 'ATGCC')
longest_common_substring('ACGTGGAAAGCCA', 'GTACACACGTTTTGAGAGACAC')
###Output
_____no_output_____
###Markdown
2.3
###Code
#(): base pair , .=unpair
pairing='(((....)))'
def equal_parenthese(parenthese):
nb_left=0
nb_right=0
for i,n in enumerate(pairing):
if n == "(":
nb_left+=1
elif n==")":
nb_right+=1
if nb_left == nb_right:
return True
else:
return False
equal_parenthese(pairing)
def right_pair(parent):
length_seq = len(parent)
first_temp=range(0,length_seq//2)
beginning=list(first_temp)
right_pairing=True
#print(beginning)
end_temp=range(length_seq-1,length_seq//2-1,-1)
end=list(end_temp)
#print(end)
for i,k in zip(beginning,end):
#print(parent[i])
if parent[i] == "(" and parent[k]== ".":
right_pairing=False
if parent[i] == "." and parent[k]== ")":
right_pairing=False
return right_pairing
def dotparent_to_bp(parent):
dot_paren=[]
length_seq = len(parent)
first_temp=range(0,length_seq//2)
beginning=list(first_temp)
right_pairing=True
#print(beginning)
end_temp=range(length_seq-1,length_seq//2-1,-1)
end=list(end_temp)
#print(end)
for i,k in zip(beginning,end):
#print(i,k)
#print(parent[i])
if parent[i] == "(" and parent[k]== ")":
dot_paren.append((i,k))
return tuple(dot_paren)
base_pair=dotparent_to_bp(pairing)
base_pair
def min_hairpinlength(pairing,base_pairs):
#length_pairing=len(pairing)
#length_base_pair=len(base_pairs)
valid=True
last_objet= len(base_pairs)-1
hairpin_length=base_pairs[last_objet][1]-base_pairs[last_objet][0]-1
#print(hairpin_length)
if hairpin_length< 4:
valid=False
print("is not a valid hairpinloop")
else:
print("it is a valid hairpinlopp")
return valid
min_hairpinlength(pairing,base_pair)
def rna_ss_validator(seq, sec_struc, wobble=True):
seq_length=len(seq)
first_temp=range(0,seq_length//2)
beginning=list(first_temp)
validator=True
#print(beginning)
#end_temp=range(seq_length-1,seq_length//2-1,-1)
seq_complementary =True
#end=list(end_temp)
equal_paren = equal_parenthese(sec_struc)
base_pair= dotparent_to_bp(sec_struc)
first_base=0
second_base=1
for i,_ in enumerate(base_pair) :
if seq[base_pair[i][first_base]] in "A":
if seq[base_pair[i][second_base]] != "U":
#print("a")
seq_complementary=False
break
if seq[base_pair[i][first_base]] in "T":
if wobble ==False and seq[base_pair[i][second_base]] != "A":
#print("b")
seq_complementary=False
break
elif wobble == True and seq[base_pair[i][second_base]] != "A" and seq[base_pair[i][second_base]] != "G":
#print("c")
seq_complementary=False
break
if seq[base_pair[i][first_base]] in "G":
if wobble ==False and seq[base_pair[i][second_base]] != "C":
#print("d")
seq_complementary=False
break
elif wobble == True and seq[base_pair[i][second_base]] != "C" and seq[base_pair[i][second_base]] != "U":
#print("e")
seq_complementary=False
break
if seq[base_pair[i][first_base]] in "C":
if seq[base_pair[i][second_base]] != "G":
#print("f")
seq_complementary=False
break
equal_paren = equal_parenthese(sec_struc)
base_pair= dotparent_to_bp(sec_struc)
valid_hairpin = min_hairpinlength(sec_struc,base_pair)
right_pair_=right_pair(sec_struc)
print(seq_complementary,equal_paren,valid_hairpin,right_pair_)
if seq_complementary==True and equal_paren ==True and valid_hairpin==True and right_pair_== True :
validator=True
else:
validator=False
return validator
rna_ss_validator('GCAUCUAUGC', '(((....)))')
rna_ss_validator('GCAUCUAUGU', '(((....)))')
rna_ss_validator('GCAUCUAUGU', '(.(....).)')
rna_ss_validator('GCAUCUACGC', '(((....)))')
rna_ss_validator('GCAUCUAUGU', '(((....)))', wobble=False)
rna_ss_validator('GCAUCUAUGU', '(.(....)).')
rna_ss_validator('GCCCUUGGCA', '(.((..))).')
###Output
3 3
[0, 1, 2, 3, 4]
[9, 8, 7, 6, 5]
3 3
[0, 1, 2, 3, 4]
[9, 8, 7, 6, 5]
2
is not a valid hairpinloop
[0, 1, 2, 3, 4]
[9, 8, 7, 6, 5]
True True False False
|
RK2/Locus3D_Cusps.ipynb | ###Markdown
Computation of line of cusps in conjugate locus
###Code
N = 3600*4
ds = 0.005/4
XA = jnp.zeros((N,6)) #XA[0] is used to determine the sign in first step
XA=ops.index_update(XA,ops.index[0],jnp.array([ 2.240636 , 0.07177964, -1.8682609 , 0.02421978, 0.9988454 , 0.04148885]))
XA=ops.index_update(XA,ops.index[1],jnp.array([ 2.2415023 , 0.07161319, -1.8673766 , 0.02420091, 0.9988479 , 0.0414399 ]))
cuspCondi = lambda xa: cuspCond(l3.endptChart,xa,ds)
for j in tqdm(range(1,N)):
XA = ops.index_update(XA,ops.index[j+1],ContFun(XA[j-1],XA[j],cuspCondi,ds))
CuspMonitor = jnp.array(list(map(cuspCondi,XA)))
firstVal=0
eVal=N
plt.plot(range(firstVal,eVal),jnp.max(jnp.abs(CuspMonitor[firstVal:eVal]),1))
DCondi = lambda p: DCond(l3.endptChart,p)
SWCondi = lambda Xa: SWCond(l3.endptChart,Xa)
D2Monitor=jnp.array(list(map(DCondi,XA[:,:3])))
SWMonitor=jnp.array(list(map(SWCondi,XA)))
fig=plt.figure()
ax=fig.add_subplot(projection='3d')
ax.plot(XA[firstVal:,0],XA[firstVal:,1],XA[firstVal:,2])
ax.set_xlabel('x0')
ax.set_ylabel('x1')
ax.set_zlabel('x2')
vals=list(map(l3.endptChart,XA[firstVal:,:3]))
Vals=jnp.array(vals)
f2 = plt.figure()
a2=f2.add_subplot(projection='3d')
a2.plot(Vals[:,0],Vals[:,1],Vals[:,2])
a2.set_xlabel('x0')
a2.set_ylabel('x1')
a2.set_zlabel('x2')
scipy.io.savemat('./Data/CuspLine_Umbilics.mat', dict(cuspsP=XA[firstVal:,:3], cusps = Vals )) # Matlab export
# Plot condition for swallowtail bifurcation along line of cusps
fVal = firstVal
eV = N
plt.plot(jnp.linspace(fVal,eV,eV-fVal),SWMonitor[fVal:eV],'-')
###Output
_____no_output_____
###Markdown
Location of hyperbolic umbilic bifurcations
###Code
# Plot condition for D series along line of cusps
plt.plot(range(firstVal,N),D2Monitor[firstVal:])
UPre= [XA[20],XA[3000],XA[7000],XA[10000]]
CuspAndDCondi = lambda xa: CuspAndDCond(l3.endptChart,xa,ds)
for j in range(0,len(UPre)):
UPre=ops.index_update(UPre,ops.index[j],optimize.fsolve(CuspAndDCondi,UPre[j],fprime=jacfwd(CuspAndDCondi)))
# Check that optimization has worked
list(map(CuspAndDCondi,UPre))
# location of umbilic bifurcations on locus in chart
U = list(map(l3.endptChart,jnp.array(UPre)[:,:3]))
U
for k in range(0,4):
ax.plot(UPre[k,0],UPre[k,1],UPre[k,2],'*')
fig
for k in range(0,4):
a2.plot(U[k][0],U[k][1],U[k][2],'*')
f2
scipy.io.savemat('./Data/LocationUmbilics.mat', dict(UmbilicLocation=U,UmbilicLocationPreimage=jnp.array(UPre)[:,:3]))
###Output
_____no_output_____
###Markdown
Computation of another cusp line
###Code
3*ds
N = 5000
ds = 0.00375
XA = jnp.zeros((N,6))
XA=ops.index_update(XA,ops.index[0],jnp.array([ 0.26437107, -1.9292977 , -2.2943342 , -0.9988839 ,-0.04062794, -0.02408788]))
XA=ops.index_update(XA,ops.index[1],jnp.array([ 0.26437593, -1.9303379 , -2.2936416 , -0.9988835 ,-0.04064594, -0.02407573]))
for j in tqdm(range(1,N)):
XA = ops.index_update(XA,ops.index[j+1],ContFun(XA[j-1],XA[j],cuspCondi,ds))
CuspMonitorCircle = jnp.array(list(map(cuspCondi,XA)))
firstVal=0
eVal=N
plt.plot(range(firstVal,eVal),jnp.max(jnp.abs(CuspMonitorCircle[firstVal:eVal]),1))
firstVal=0
fig=plt.figure()
ax=fig.add_subplot(projection='3d')
ax.plot(XA[firstVal:,0],XA[firstVal:,1],XA[firstVal:,2])
ax.set_xlabel('x0')
ax.set_ylabel('x1')
ax.set_zlabel('x2')
vals=list(map(l3.endptChart,XA[firstVal:,:3]))
Vals=jnp.array(vals)
f2 = plt.figure()
a2=f2.add_subplot(projection='3d')
a2.plot(Vals[:,0],Vals[:,1],Vals[:,2])
a2.set_xlabel('x0')
a2.set_ylabel('x1')
a2.set_zlabel('x2')
scipy.io.savemat('./Data/CuspLine_Circle.mat', dict(cuspsP=XA[firstVal:,:3], cusps = Vals )) # Matlab export
###Output
_____no_output_____ |
Complete-Python-Bootcamp-master/Lists.ipynb | ###Markdown
ListsEarlier when discussing strings we introduced the concept of a *sequence* in Python. Lists can be thought of the most general version of a *sequence* in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!In this section we will learn about: 1.) Creating lists 2.) Indexing and Slicing Lists 3.) Basic List Methods 4.) Nesting Lists 5.) Introduction to List ComprehensionsLists are constructed with brackets [] and commas separating every element in the list.Let's go ahead and see how we can construct lists!
###Code
# Assign a list to an variable named my_list
my_list = [1,2,3]
###Output
_____no_output_____
###Markdown
We just created a list of integers, but lists can actually hold different object types. For example:
###Code
my_list = ['A string',23,100.232,'o']
###Output
_____no_output_____
###Markdown
Just like strings, the len() function will tell you how many items are in the sequence of the list.
###Code
len(my_list)
###Output
_____no_output_____
###Markdown
Indexing and SlicingIndexing and slicing works just like in strings. Let's make a new list to remind ourselves of how this works:
###Code
my_list = ['one','two','three',4,5]
# Grab element at index 0
my_list[0]
# Grab index 1 and everything past it
my_list[1:]
# Grab everything UP TO index 3
my_list[:3]
###Output
_____no_output_____
###Markdown
We can also use + to concatenate lists, just like we did for strings.
###Code
my_list + ['new item']
###Output
_____no_output_____
###Markdown
Note: This doesn't actually change the original list!
###Code
my_list
###Output
_____no_output_____
###Markdown
You would have to reassign the list to make the change permanent.
###Code
# Reassign
my_list = my_list + ['add new item permanently']
my_list
###Output
_____no_output_____
###Markdown
We can also use the * for a duplication method similar to strings:
###Code
# Make the list double
my_list * 2
# Again doubling not permanent
my_list
###Output
_____no_output_____
###Markdown
Basic List MethodsIf you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python however, tend to be more flexible than arrays in other languages for a two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).Let's go ahead and explore some more special methods for lists:
###Code
# Create a new list
l = [1,2,3]
###Output
_____no_output_____
###Markdown
Use the **append** method to permanently add an item to the end of a list:
###Code
# Append
l.append('append me!')
# Show
l
###Output
_____no_output_____
###Markdown
Use **pop** to "pop off" an item from the list. By default pop takes off the last index, but you can also specify which index to pop off. Let's see an example:
###Code
# Pop off the 0 indexed item
l.pop(0)
# Show
l
# Assign the popped element, remember default popped index is -1
popped_item = l.pop()
popped_item
# Show remaining list
l
###Output
_____no_output_____
###Markdown
It should also be noted that lists indexing will return an error if there is no element at that index. For example:
###Code
l[100]
###Output
_____no_output_____
###Markdown
We can use the **sort** method and the **reverse** methods to also effect your lists:
###Code
new_list = ['a','e','x','b','c']
#Show
new_list
# Use reverse to reverse order (this is permanent!)
new_list.reverse()
new_list
# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()
new_list
###Output
_____no_output_____
###Markdown
Nesting ListsA great feature of of Python data structures is that they support *nesting*. This means we can have data structures within data structures. For example: A list inside a list.Let's see how this works!
###Code
# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]
# Show
matrix
###Output
_____no_output_____
###Markdown
Now we can again use indexing to grab elements, but now there are two levels for the index. The items in the matrix object, and then the items inside that list!
###Code
# Grab first item in matrix object
matrix[0]
# Grab first item of the first item in the matrix object
matrix[0][0]
###Output
_____no_output_____
###Markdown
List ComprehensionsPython has an advanced feature called list comprehensions. They allow for quick construction of lists. To fully understand list comprehensions we need to understand for loops. So don't worry if you don't completely understand this section, and feel free to just skip it since we will return to this topic later.But in case you want to know now, here are a few examples!
###Code
# Build a list comprehension by deconstructing a for loop within a []
first_col = [row[0] for row in matrix]
first_col
###Output
_____no_output_____ |
Module1_Python_Functions.ipynb | ###Markdown
Module 1 Tutorial There are numerous open-source libraries, collections of functions, that have been developed in Python that we will make use of in this course.The first one is called NumPy and you can find the documentation [here](https://numpy.org/). It is one of the most widely-used libraries for scientific computating in python. The second library we will use will be a module from Scipy, called scipy.stats ([scipy.stats documentation](https://docs.scipy.org/doc/scipy/reference/stats.html)), and the third is a library for handling database-like structures called Pandas for which you can find the documentation at this link: [Pandas documentation](https://pandas.pydata.org/docs/user_guide/index.html). Finally, we will use a plotting/visualisation tool called Matplotlib ([Matplotlib documentation](https://matplotlib.org/)).We import the libraries with the following statement:
###Code
import numpy
from scipy import stats
import pandas
from matplotlib import pyplot
###Output
_____no_output_____
###Markdown
As one of the main ideas in module 1 was visualising and exploring data, let's begin with showing code to visualise our data.First, we need to have some data to work with. We will load in two datasets, one containing continuous data and one containing discrete data.
###Code
continuous_data = pandas.read_csv(
r'https://raw.githubusercontent.com/imheidimarais/Engineering-Statistics/master/data/Normal_Data.csv'
)
discrete_data = pandas.read_csv(
r'https://raw.githubusercontent.com/imheidimarais/Engineering-Statistics/master/data/Discrete_Data.csv'
)
###Output
_____no_output_____
###Markdown
We can investigate the sizes of our datasets:
###Code
print(f"Size of continuous data: {continuous_data.shape[0]} rows, {continuous_data.shape[1]} column(s).")
print(f"Size of discrete data: {discrete_data.shape[0]} rows, {discrete_data.shape[1]} column(s).")
###Output
Size of continuous data: 50 rows, 1 column(s).
Size of discrete data: 50 rows, 1 column(s).
###Markdown
So we see that we are working with a single sample, containing 50 values of the variable, in both cases. The first type of visualisation tool that was discussed was the histogram. We can construct a histogram several different ways. We will use the built-in histogram function that comes with pandas DataFrames ([pandas histogram documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.hist.html)). Because we have a single column we do not have to do much, but we will specify the column that we want to plot as the 0th column (the first and only column in the DataFrame) for the sake of completeness.Note that from here on in the code we will never reference our sample via the column names, we will use the column number in order to make the code more general and easier to use with different datasets that you may want to test it on.
###Code
fig = pyplot.Figure(figsize=(5, 5))
ax1 = fig.add_subplot(1, 1, 1)
discrete_data.hist(column=discrete_data.columns[0], ax=ax1)
ax1.set(
xlabel='$x$',
ylabel='Frequency'
)
fig # this just displays the figure in the cell output
###Output
_____no_output_____
###Markdown
You can see it is very simple to let the plotting libraries select the number of bins desired in the histogram and perform the calculations. However, we see there are gaps in the plot due to the automatic selection of the bins. If we were interested in selecting the bins ourselves, perhaps in a specific problem we know something about our data, we could do that. Let's look at the discrete data:
###Code
unique_values = pandas.unique(discrete_data[discrete_data.columns[0]])
print(f"The unique values found in the DataFrame are: {unique_values}")
###Output
The unique values found in the DataFrame are: [4. 1. 3. 2. 5. 6.]
###Markdown
So in this case we could specify our bins manually according to the values we have in our data. We use the range function which takes a start point, a stop point, and an increment size. The stop point is not included in the range.
###Code
bins = list(range(1, 8, 1)) # this will change based on your dataset
print(f"The bounds of the bins are: {bins}")
fig = pyplot.Figure(figsize=(5, 5))
ax1 = fig.add_subplot(1, 1, 1)
discrete_data.hist(column=discrete_data.columns[0], bins=bins, ax=ax1)
ax1.set(
xlabel='$x$',
ylabel='Frequency'
)
fig
###Output
The bounds of the bins are: [1, 2, 3, 4, 5, 6, 7]
###Markdown
We can see that our data is divided nicely now according to the values that we have. However, for the continuous data we cannot so easily specify precise bounds for the bins, only how many we would like to have. For example:
###Code
number_bins1 = 10
number_bins2 = 20
fig = pyplot.Figure(figsize=(12, 4))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
continuous_data.hist(column=continuous_data.columns[0], bins=number_bins1, ax=ax1)
continuous_data.hist(column=continuous_data.columns[0], bins=number_bins2, ax=ax2)
ax1.set(
xlabel='$x$',
ylabel='Frequency'
)
ax2.set(
xlabel='$x$',
ylabel='Frequency'
)
fig
###Output
_____no_output_____
###Markdown
Here we see the effect of changing the number of bins on the appearance of the histogram.The second type of visualisation tool that was discussed was the index plot. We do this with the pandas plot function, and specify a scatter type, while plotting against the index ([pandas plot documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html)).
###Code
fig = pyplot.Figure(figsize=(12, 4))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
continuous_data.reset_index().plot(x='index', y=continuous_data.columns[0], kind='scatter', ax=ax1)
discrete_data.reset_index().plot(x='index', y=discrete_data.columns[0], kind='scatter', ax=ax2)
ax1.set(
xlabel='Index',
ylabel='$x$'
)
ax2.set(
xlabel='Index',
ylabel='$x$'
)
fig
###Output
_____no_output_____
###Markdown
Because of the way the data is stored in the DataFrame we must use 'reset_index()' before plotting to generate the index column to plot against. But above you can see the index plots for the continuous data (left) and the discrete data (right). Admittedly it is a bit more useful for the continuous data as we get a better idea of the mean and spread of the data.Moving on to the boxplots, this is again done quite simply with pandas ([pandas boxplot documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.boxplot.html)):
###Code
fig = pyplot.Figure(figsize=(12, 4))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
continuous_data.boxplot(column=continuous_data.columns[0], ax=ax1)
discrete_data.boxplot(column=discrete_data.columns[0], ax=ax2)
ax1.set(
xlabel='Sample',
ylabel='$x$'
)
ax2.set(
xlabel='Sample',
ylabel='$x$'
)
fig
###Output
_____no_output_____
###Markdown
On the left we see the continuous data, and on the right the discrete. Neither of these datasets contain suspected outliers.Finally we must look at the empirical cumulative distribution function. This requires a little bit more thought than the other figures we have produced so far..
###Code
continuous_data_sorted = continuous_data.sort_values(by=continuous_data.columns[0], ascending=True) #sort the data by x-value
ecdf = [n/continuous_data_sorted.shape[0] for n in range(1, continuous_data_sorted.shape[0]+1)]
# In the above line we calculate the proportion of values equal or less than the given x for contiuous data.
continuous_data_sorted['ecdf'] = numpy.array(ecdf)
discrete_data_ecdf = discrete_data.value_counts(sort=False, ascending=True, normalize=True).cumsum()
discrete_data_ecdf = discrete_data_ecdf.reset_index(drop=True).to_frame()
unique_values = numpy.unique(discrete_data[discrete_data.columns[0]])
discrete_data_ecdf['Unique Values'] = unique_values
fig = pyplot.Figure(figsize=(12, 4))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
continuous_data_sorted.plot(x=continuous_data_sorted.columns[0], y='ecdf', kind='scatter', ax=ax1)
discrete_data_ecdf.plot(x='Unique Values', y=discrete_data_ecdf.columns[0], kind='scatter', ax=ax2)
ax1.set(
xlabel='$x$',
ylabel='ecdf'
)
ax2.set(
xlabel='$x$',
ylabel='ecdf'
)
fig
###Output
_____no_output_____
###Markdown
The block of code above may appear a bit convoluted, which it is in an attempt to write code that is more general and can be applied to unkown datasets. Just remember the principle of what is being plotted in an ecdf; the fraction of observations equal to, or less than, the given x value, versus the x value. This means the plots should always start with a y value above zero, and end with a y value of exactly one. Next to discuss is the statistics that we can calculate from our sample data. We could obtain the mean, and variance individually, or we could use a built in pandas function called describe. We see this for the continuous data below:
###Code
descriptive_statistics_continous_data = continuous_data.describe()
print(descriptive_statistics_continous_data)
###Output
X
count 50.000000
mean 3.443760
std 5.887546
min -8.280000
25% -0.247500
50% 3.210000
75% 7.022500
max 15.500000
###Markdown
What we see returned is the sample size, the mean of our sample, the standard deviation, the minumum, maximum, and different percentiles. We can access the different information from each column by name or by index:
###Code
print(descriptive_statistics_continous_data[continuous_data.columns[0]]["mean"])
print(descriptive_statistics_continous_data[continuous_data.columns[0]][1])
###Output
3.44376
3.44376
###Markdown
We can also calculate the standard error using the scipy stats function.
###Code
standard_error_continuous_data = stats.sem(continuous_data[continuous_data.columns[0]])
print(f"standard error: {standard_error_continuous_data}")
###Output
standard error: 0.8326246965800991
###Markdown
For a sanity check, we can compute the values ourselves to confirm the libraries are using the equations we expect:
###Code
n = continuous_data[continuous_data.columns[0]].shape[0] # the sample size
mean = (1/n)*continuous_data[continuous_data.columns[0]].sum()
variance = (1/(n-1))*((continuous_data[continuous_data.columns[0]] - mean)**2).sum()
standard_deviation = numpy.sqrt(variance)
standard_error = standard_deviation/numpy.sqrt(n)
print(f"Sample Size: {n}")
print(f"Sample Mean: {mean}")
print(f"Sample Variance: {variance}, Sample Standard Deviation: {standard_deviation}")
print(f"Standard Error: {standard_error}")
###Output
Sample Size: 50
Sample Mean: 3.4437600000000006
Sample Variance: 34.663194267755095, Sample Standard Deviation: 5.887545691351796
Standard Error: 0.832624696580099
###Markdown
There is one final thing you may be interested in doing, generating normally distributed data that has the same mean and variance as your sample, to compare the distributions. There is a simple way to do this using numpy. First, we create a random generator. Then, specifying the mean, standard deviation, and the number of observations we desire, we can generate this normally distributed data.
###Code
rng = numpy.random.default_rng()
normally_distributed_data = rng.normal(loc=mean, scale=standard_deviation, size=100)
normally_distributed_data = pandas.DataFrame(normally_distributed_data)
number_bins = 20
fig = pyplot.Figure(figsize=(12, 4))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
continuous_data.hist(column=continuous_data.columns[0], bins=number_bins, density=True, ax=ax1)
normally_distributed_data.hist(column=normally_distributed_data.columns[0], bins=number_bins, density=True, ax=ax2)
xrange1 = (continuous_data[continuous_data.columns[0]].min(), continuous_data[continuous_data.columns[0]].max())
normal_pdf_xs = numpy.linspace(xrange1[0], xrange1[1], 100)
normal_pdf_ys = stats.norm.pdf(normal_pdf_xs, loc=mean, scale=standard_deviation)
ax1.plot(normal_pdf_xs, normal_pdf_ys, c="orange")
ax2.plot(normal_pdf_xs, normal_pdf_ys, c="orange")
ax1.set(
xlabel='$x$',
ylabel='Frequency'
)
ax2.set(
xlabel='$x$',
ylabel='Frequency'
)
fig
###Output
_____no_output_____ |
Calibrations/Calibration.ipynb | ###Markdown
Models Calibration Kirill Zakharov2022
###Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as stats
from scipy.integrate import quad
from scipy.fft import fft, ifft
from scipy.interpolate import interp1d
from functools import partial
from scipy.optimize import minimize, fsolve
import tqdm
import yfinance as yf
%matplotlib inline
plt.style.use('ggplot')
sns.set_palette('mako')
sns.set_style('darkgrid')
aapl = yf.Ticker('AAPL')
apple_option = aapl.option_chain('2022-03-25').calls
apple_option.head()
apple_option.shape
# apple_option.to_csv('Apple_Option.csv')
apple_strikes = apple_option.strike
apple_prices = apple_option.lastPrice
def CallPutOptionPriceCOS(cf, CP, s0, r, tau, K, N, L):
# L - size of truncation domain (typ.:L=8 or L=10)
# reshape K to a column vector
K = np.array(K).reshape([len(K),1])
i = complex(0.0,1.0)
x0 = np.log(s0 / K)
# truncation domain
a = 0.0 - L * np.sqrt(tau)
b = 0.0 + L * np.sqrt(tau)
k = np.linspace(0,N-1,N).reshape([N,1])
u = k * np.pi / (b - a);
H_k = Hk_Coefficients(CP,a,b,k)
mat = np.exp(i * np.outer((x0 - a) , u))
temp = cf(u) * H_k
temp[0] = 0.5 * temp[0]
value = np.exp(-r * tau) * K * np.real(mat.dot(temp))
return value
def Hk_Coefficients(CP, a, b, k):
if str(CP).lower() == "c" or str(CP).lower()=="1":
c = 0.0
d = b
coef = Chi_Psi(a, b, c, d, k)
Chi_k = coef["chi"]
Psi_k = coef["psi"]
if a < b and b < 0.0:
H_k = np.zeros([len(k),1])
else:
H_k = 2.0 / (b - a) * (Chi_k - Psi_k)
elif str(CP).lower()=="p" or str(CP).lower()=="-1":
c = a
d = 0.0
coef = Chi_Psi(a, b, c, d, k)
Chi_k = coef["chi"]
Psi_k = coef["psi"]
H_k = 2.0 / (b - a) * (- Chi_k + Psi_k)
return H_k
def Chi_Psi(a, b, c, d, k):
psi = np.sin(k * np.pi * (d - a) / (b - a)) - np.sin(k * np.pi * (c - a)/(b - a))
psi[1:] = psi[1:] * (b - a) / (k[1:] * np.pi)
psi[0] = d - c
chi = 1.0 / (1.0 + np.power((k * np.pi / (b - a)) , 2.0))
expr1 = np.cos(k * np.pi * (d - a)/(b - a)) * np.exp(d) - np.cos(k * np.pi
* (c - a) / (b - a)) * np.exp(c)
expr2 = k * np.pi / (b - a) * np.sin(k * np.pi *
(d - a) / (b - a)) - k * np.pi / (b - a) * np.sin(k
* np.pi * (c - a) / (b - a)) * np.exp(c)
chi = chi * (expr1 + expr2)
value = {"chi":chi,"psi":psi }
return value
CP = 'c'
s0 = 164.7
r = 0.05
# K = [80, 90, 110, 130, 135, 140]
N = 2**8
L = 10
tau = 1
sigma = 0.2
# cf = lambda u: np.exp((r - 0.5 * sigma**2)* 1j * u * tau - 0.5 * sigma**2 * u**2 * tau)
# option_price_cos = CallPutOptionPriceCOS(cf, CP, s0, r, tau, K, N, L)
prices = apple_prices
strikes = apple_strikes
def ChFHestonModel(r, tau, kappa, gamma, vbar, v0, rho):
i = complex(0.0, 1.0)
D1 = lambda u: np.sqrt(np.power(kappa-gamma*rho*i*u, 2)+(u**2 + i*u) * gamma**2)
g = lambda u: (kappa-gamma*rho*i*u-D1(u))/(kappa-gamma*rho*i*u + D1(u))
C = lambda u: (1.0-np.exp(-D1(u)*tau))/(gamma**2 * (1.0-g(u)*np.exp(-D1(u)*tau)))\
*(kappa-gamma*rho*i*u-D1(u))
# Note that we exclude the term -r*tau, as the discounting is performed in the COS method
A = lambda u: r * i*u *tau + kappa*vbar*tau/gamma/gamma *(kappa-gamma*rho*i*u-D1(u))\
- 2*kappa*vbar/gamma/gamma * np.log((1.0-g(u)*np.exp(-D1(u)*tau))/(1.0-g(u)))
cf = lambda u: np.exp(A(u) + C(u)*v0)
return cf
v0 = 0.04
def error_fBS(x, prices, strikes):
cf = lambda u: np.exp((x[0] - 0.5 * x[1]**2)* 1j * u * tau - 0.5 * x[1]**2 * u**2 * tau)
price_calib = CallPutOptionPriceCOS(cf, CP, s0, x[0], tau, strikes, N, L).T[0]
return np.mean((price_calib - prices)**2)
def error_fHM(x, prices, strikes):
cf = ChFHestonModel(x[0], 1, x[1], x[2], x[3], v0, x[4])
price_calib = CallPutOptionPriceCOS(cf, CP, s0, x[0], tau, strikes, N, L).T[0]
return np.mean((price_calib - prices)**2)
#r, sigma
init_vals = [0.1, 0.4]
bounds = ((0.01, 0.1), (-1, 1))
params_BS = minimize(error_fBS, x0=init_vals, args=(prices, strikes), bounds=bounds, tol=1e-10, options={"maxiter": 10000})
params_BS
#r, kappa, gamma, vbar, rho
init_vals = [0.05, 0.4, 0.8, 0.04, -0.8]
bounds = ((0.01, 0.05), (0, 1), (1e-4, 1), (0, 1), (-1, 1))
params_HM = minimize(error_fHM, x0=init_vals, args=(prices, strikes), bounds=bounds, tol=1e-10, options={"maxiter": 10000})
params_HM
r_BS = params_BS.x[0]
sigma_BS = params_BS.x[1]
r_HM, kappa, gamma, vbar, rho = params_HM.x
cf_BS = lambda u: np.exp((r_BS - 0.5 * sigma**2)* 1j * u * tau - 0.5 * sigma_BS**2 * u**2 * tau)
cf_HM = ChFHestonModel(r_HM, tau, kappa, gamma, vbar, v0, rho)
option_price_cos_BS = CallPutOptionPriceCOS(cf_BS, CP, s0, r_BS, tau, strikes, N, L)
option_price_cos_HM = CallPutOptionPriceCOS(cf_HM, CP, s0, r_HM, tau, strikes, N, L)
plt.subplots(figsize=(10, 5), dpi=100)
plt.plot(strikes, prices, label='Initial')
plt.plot(strikes, option_price_cos_BS.T[0], '--', color='red', label='COS Method BS')
plt.plot(strikes, option_price_cos_HM.T[0], '--', color='green', label='COS Method Heston')
plt.title('Option Pricing', fontsize=16)
plt.xlabel('Strikes', fontsize=14)
plt.ylabel('Values', fontsize=14)
plt.legend()
plt.show()
# nvda = yf.Ticker('NVDA')
# nvda_option = nvda.option_chain('2022-03-11').calls
# nvda_option.head()
# nvda_option.to_csv('NVDA_option.csv', header=True)
nvda_option = pd.read_csv('NVDA_option.csv')
nvda_option.head()
nvda_strikes = nvda_option.strike
nvda_prices = nvda_option.lastPrice
v0 = 0.03
s0 = 229.
#r, kappa, gamma, vbar, rho
init_vals = [0.05, 0.4, 0.8, 0.04, -0.8]
bounds = ((0.01, 0.05), (0, 1), (1e-4, 1), (0, 1), (-1, 1))
params_HM = minimize(error_fHM, x0=init_vals, args=(nvda_prices, nvda_strikes), bounds=bounds, tol=1e-10, options={"maxiter": 10000})
params_HM
r_HM, kappa, gamma, vbar, rho = params_HM.x
option_price_cos_HM_nvda = CallPutOptionPriceCOS(ChFHestonModel(r_HM, tau, kappa, gamma, vbar, v0, rho), CP, s0, r_HM, tau, nvda_strikes, N, L)
def CIR_exact(numberPaths, kappa, gamma, vbar, s, t, v_s):
if vbar != 0:
delta = 4.0 * kappa * vbar/gamma**2
else:
delta = 4.0 * kappa * v0/gamma**2
c = gamma**2/(4.0*kappa) * (1 - np.exp(-kappa * (t-s)))
kappaBar = 4 * kappa * v_s * np.exp(-kappa * (t-s))/(gamma**2 * (1 - np.exp(-kappa * (t-s))))
return c * np.random.noncentral_chisquare(delta, kappaBar, numberPaths)
def heston_almost_exact_solution(numberPaths, N, s0, v0, T, kappa, gamma, vbar, rho, r):
X = np.zeros([numberPaths, N + 1])
S = np.zeros([numberPaths, N + 1])
V = np.zeros([numberPaths, N + 1])
time = np.zeros(N + 1)
Zx = np.random.normal(0, 1, [numberPaths, N])
X[:, 0] = np.log(s0)
V[:, 0] = v0
dt = T/float(N)
for t in range(N):
V[:, t+1] = CIR_exact(numberPaths, kappa, gamma, vbar, 0, dt, V[:, t])
X[:, t+1] = X[:, t] + (r - vbar*kappa*rho/gamma) * dt + ((kappa*rho/gamma - 0.5) * dt - rho/gamma) * V[:, t] +\
rho/gamma * V[:, t+1] + np.sqrt((1-rho**2) * dt * V[:, t]) * Zx[:, t]
time[t+1] = time[t] + dt
S = np.exp(X)
return time, S, V
def EUOptionPriceFromMCPathsGeneralized(CP,S,K,T,r):
# S is a vector of Monte Carlo samples at T
result = np.zeros([len(K),1])
if CP == 'c' or CP == 1:
for (idx,k) in enumerate(K):
result[idx] = np.exp(-r*T)*np.mean(np.maximum(S-k,0.0))
elif CP == 'p' or CP == -1:
for (idx,k) in enumerate(K):
result[idx] = np.exp(-r*T)*np.mean(np.maximum(k-S,0.0))
return result.T[0]
numberPaths = 500
N = 500
T = 1
heston_aes = heston_almost_exact_solution(numberPaths, N, s0, v0, T, kappa, gamma, vbar, rho, r_HM)
plt.subplots(figsize=(10, 5), dpi=100)
plt.plot(nvda_strikes, nvda_prices, label='Initial')
plt.plot(nvda_strikes, option_price_cos_HM_nvda.T[0], '--', color='green', label='COS Method Heston')
plt.plot(nvda_strikes, EUOptionPriceFromMCPathsGeneralized('c', heston_aes[1][:, -1], nvda_strikes, T, r_HM),\
'.', color='red', label='AES Heston')
plt.title('Option Pricing', fontsize=16)
plt.xlabel('Strikes', fontsize=14)
plt.ylabel('Values', fontsize=14)
plt.legend()
plt.show()
###Output
_____no_output_____ |
scratch/lesson_3/numpy/mean_normalization_and_data_separation_20190502.ipynb | ###Markdown
Mean NormalizationIn machine learning we use large amounts of data to train our models. Some machine learning algorithms may require that the data is *normalized* in order to work correctly. The idea of normalization, also known as *feature scaling*, is to ensure that all the data is on a similar scale, *i.e.* that all the data takes on a similar range of values. For example, we might have a dataset that has values between 0 and 5,000. By normalizing the data we can make the range of values be between 0 and 1.In this lab, you will be performing a different kind of feature scaling known as *mean normalization*. Mean normalization will scale the data, but instead of making the values be between 0 and 1, it will distribute the values evenly in some small interval around zero. For example, if we have a dataset that has values between 0 and 5,000, after mean normalization the range of values will be distributed in some small range around 0, for example between -3 to 3. Because the range of values are distributed evenly around zero, this guarantees that the average (mean) of all elements will be zero. Therefore, when you perform *mean normalization* your data will not only be scaled but it will also have an average of zero. To Do:You will start by importing NumPy and creating a rank 2 ndarray of random integers between 0 and 5,000 (inclusive) with 1000 rows and 20 columns. This array will simulate a dataset with a wide range of values. Fill in the code below
###Code
# import NumPy into Python
import numpy as np
# Create a 1000 x 20 ndarray with random integers in the half-open interval [0, 5001).
X = np.random.randint(0, 5001, size=(1000,20))
# print the shape of X
print(X.shape)
###Output
(1000, 20)
###Markdown
Now that you created the array we will mean normalize it. We will perform mean normalization using the following equation:$\mbox{Norm_Col}_i = \frac{\mbox{Col}_i - \mu_i}{\sigma_i}$where $\mbox{Col}_i$ is the $i$th column of $X$, $\mu_i$ is average of the values in the $i$th column of $X$, and $\sigma_i$ is the standard deviation of the values in the $i$th column of $X$. In other words, mean normalization is performed by subtracting from each column of $X$ the average of its values, and then by dividing by the standard deviation of its values. In the space below, you will first calculate the average and standard deviation of each column of $X$.
###Code
# Average of the values in each column of X
ave_cols = X.mean(axis=0)
# Standard Deviation of the values in each column of X
std_cols = X.std(axis=0)
###Output
[2533.006 2533.073 2490.807 2557.737 2492.688 2523.516 2424.221 2418.348
2493.341 2521.206 2450.577 2573.019 2506.343 2476.748 2441.666 2499.222
2471.062 2573.115 2502.855 2485.702]
(20,)
[1451.44650537 1447.0401721 1436.50202845 1438.5362136 1467.2019168
1479.48875215 1437.46100892 1432.1886478 1483.66278538 1454.13328191
1445.89513523 1437.13688445 1453.35032437 1451.82074737 1438.31863801
1456.15745602 1500.08420169 1427.28976307 1427.65253125 1434.0926104 ]
(20,)
###Markdown
If you have done the above calculations correctly, then `ave_cols` and `std_cols`, should both be vectors with shape `(20,)` since $X$ has 20 columns. You can verify this by filling the code below:
###Code
# Print the shape of ave_cols
print(ave_cols.shape)
# Print the shape of std_cols
print(std_cols.shape)
###Output
(20,)
(20,)
###Markdown
You can now take advantage of Broadcasting to calculate the mean normalized version of $X$ in just one line of code using the equation above. Fill in the code below
###Code
# Mean normalize X
X_norm = (X - ave_cols)/std_cols
###Output
_____no_output_____
###Markdown
If you have performed the mean normalization correctly, then the average of all the elements in $X_{\tiny{\mbox{norm}}}$ should be close to zero, and they should be evenly distributed in some small interval around zero. You can verify this by filing the code below:
###Code
# Print the average of all the values of X_norm
print(X_norm.mean())
# Print the average of the minimum value in each column of X_norm
print(X_norm.min(axis=0).mean())
# Print the average of the maximum value in each column of X_norm
print(X_norm.max(axis=0).mean())
###Output
-1.9539925233402756e-18
-1.7200111012914197
1.7219776323079479
###Markdown
You should note that since $X$ was created using random integers, the above values will vary. Data SeparationAfter the data has been mean normalized, it is customary in machine learnig to split our dataset into three sets:1. A Training Set2. A Cross Validation Set3. A Test SetThe dataset is usually divided such that the Training Set contains 60% of the data, the Cross Validation Set contains 20% of the data, and the Test Set contains 20% of the data. In this part of the lab you will separate `X_norm` into a Training Set, Cross Validation Set, and a Test Set. Each data set will contain rows of `X_norm` chosen at random, making sure that we don't pick the same row twice. This will guarantee that all the rows of `X_norm` are chosen and randomly distributed among the three new sets.You will start by creating a rank 1 ndarray that contains a random permutation of the row indices of `X_norm`. You can do this by using the `np.random.permutation()` function. The `np.random.permutation(N)` function creates a random permutation of integers from 0 to `N - 1`. Let's see an example:
###Code
# We create a random permutation of integers 0 to 4
np.random.permutation(5)
###Output
_____no_output_____
###Markdown
To DoIn the space below create a rank 1 ndarray that contains a random permutation of the row indices of `X_norm`. You can do this in one line of code by extracting the number of rows of `X_norm` using the `shape` attribute and then passing it to the `np.random.permutation()` function. Remember the `shape` attribute returns a tuple with two numbers in the form `(rows,columns)`.
###Code
# Create a rank 1 ndarray that contains a random permutation of the row indices of `X_norm`
row_indices = np.random.permutation(X_norm.shape[0])
###Output
999 0
###Markdown
Now you can create the three datasets using the `row_indices` ndarray to select the rows that will go into each dataset. Rememeber that the Training Set contains 60% of the data, the Cross Validation Set contains 20% of the data, and the Test Set contains 20% of the data. Each set requires just one line of code to create. Fill in the code below
###Code
# Make any necessary calculations.
# You can save your calculations into variables to use later.
training_cutoff = X_norm.shape[0] * .6
cross_val_cutoff = training_cutoff + X_norm.shape[0] * .2
text_cutoff = cross_val_cutoff + X_norm.shape[0] * .2
print(training_cutoff, cross_val_cutoff, text_cutoff)
# Create a Training Set
X_train = X_norm[row_indices < training_cutoff]
# Create a Cross Validation Set
X_crossVal = X_norm[(training_cutoff <= row_indices) & (row_indices < cross_val_cutoff)]
# Create a Test Set
X_test = X_norm[(cross_val_cutoff <= row_indices) & (row_indices < text_cutoff)]
###Output
600.0 800.0 1000.0
###Markdown
If you performed the above calculations correctly, then `X_tain` should have 600 rows and 20 columns, `X_crossVal` should have 200 rows and 20 columns, and `X_test` should have 200 rows and 20 columns. You can verify this by filling the code below:
###Code
# Print the shape of X_train
print(X_train.shape)
# Print the shape of X_crossVal
print(X_crossVal.shape)
# Print the shape of X_test
print(X_test.shape)
###Output
(600, 20)
(200, 20)
(200, 20)
|
trainings/feature_hashing/feature_hashing.ipynb | ###Markdown
Feature Hashing: Dimension Reduction in NLPIn Machine Learning, feature hashing (aka hashing trick) is a technique to encode categorical features. In general it is used as a dimension-reduction technique, and it has gained a lot of popularity within the Machine Learning community in the last few years, especially in the NLP domain.Feature hashing doesn't require too many parameters to use (usually only dimension of the reduced parameter space), and in this training we will try and explain how the technique works, and what the trade-offs are in choosing this parameter.Most of this training was based on [this blog post](https://booking.ai/dont-be-tricked-by-the-hashing-trick-192a6aae3087). HashingA hashing function is the basis of this trick, and a good hashing function is defined as follows:> A hashing function is some function $h$ from one space (in NLP, tokens) to another space (in general, integer indices) with the following properties:> 1. **Deterministic:** Tokens are always mapped to the same index.> 2. **Uniform:** A large set of tokens should be uniformly distributed over the index range.> 3. **Fixed Range:** The size of the output set of indices should be fixed.There are many different ways of creating a hashing function with the following properties, so we aren't stuck with a specific function. The best one usually depends on the use-case, but you can find lots of examples [here](https://www.wikiwand.com/en/Hash_function). Feature Hashing in Document ClassificationFor now we will focus on one application of this technique, but you should know that it is applied to many other cases, usually as a way of reducing the size of a bag-of-words representation. See the image below for an illustration.For this example we will use a commonly used dataset from kaggle.
###Code
import pandas as pd
import re
%matplotlib inline
news_df = pd.read_csv("/home/ec2-user/data/uci-news-aggregator.csv")
news_df = news_df[['TITLE', 'CATEGORY']]
news_df['TITLE'][1]
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import CountVectorizer
hasher = HashingVectorizer(strip_accents='ascii', # translates weird characters
analyzer='word',
stop_words='english',
norm=None, # This can be used to norm document vectors
alternate_sign=False, # Trick used with hashing to improve it
n_features=10) # Size of hashing dimension
hashed_features = hasher.transform(news_df['TITLE'])
print(hasher.transform(["hello world", "change"]))
###Output
(0, 1) 1.0
(0, 9) 1.0
(1, 7) 1.0
###Markdown
Here we see the hashing function in action. It takes each word of the input list of strings (the features of the document), and creates a vector of length $n$, where the indices of the output of the hashing function are set to 1. Calculating the number of collisionsLets calculate the number of collisions we are getting as we reduce the size of our hashing layer. We expect to see an increase, but how much will it increase?First we'll get a list of unique tokens. We'll grab the preprocessing function from the `HashingVectorizer` (which is called `build_analyzer`), to make sure we use the same function.
###Code
preprocessor = hasher.build_analyzer()
preprocessor(news_df['TITLE'][1])
###Output
_____no_output_____
###Markdown
Great, it's doing what we want! It's always a good idea to check stuff like this for yourself. Now lets use this to create a list of unique tokens.
###Code
print(hasher.transform([news_df['TITLE'][1]]))
import matplotlib.pyplot as plt
unique_tokens = list(set.union(*[set(preprocessor(d)) for d in news_df['TITLE']]))
def calc_collisions(word_list, hash_dim):
hasher = HashingVectorizer(strip_accents='ascii',
analyzer='word',
stop_words='english',
norm=None,
binary=True,
alternate_sign=False,
n_features=hash_dim)
hashed_features = hasher.transform(word_list)
summed_features = hashed_features.sum(axis=0)
col_count = summed_features[summed_features > 0] - 1
return col_count.sum()
plot_data = list()
for n in range(1001000,0, -10000):
col = calc_collisions(unique_tokens, hash_dim=n)
plot_data.append([n,100*col/len(unique_tokens)])
plt.plot([x[0] for x in plot_data], [x[1] for x in plot_data])
plt.xlim(1100000,-1000)
plt.xlabel("Hash Dimension")
plt.ylabel("% Collisions")
plt.show()
###Output
_____no_output_____
###Markdown
As we can see, the number of collisions grows exponentially as we approach a hash dimension of 0. Often a kind of elbow rule is used to determine the hash dimension.With this increase of collisions in mind, it would be interesting to know how this impacts the predictive power of machine-learning models. Hash collisions might not be so bad? Lets try and figure it out ourselves!> *Warning, this takes a long time, so run at your own risk!*
###Code
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
def run_classification(df, hash_dim):
train,test = train_test_split(df, test_size=0.3)
X_train = train['TITLE']
X_test = test['TITLE']
y_train = train['CATEGORY']
y_test = test['CATEGORY']
pipeline = Pipeline(steps=[
('hasher', HashingVectorizer(strip_accents='ascii',
analyzer='word',
stop_words='english',
norm=None,
binary=True,
alternate_sign=False,
n_features=hash_dim)),
('log_reg', LogisticRegression())
])
pipeline.fit(X_train, y_train)
return accuracy_score(y_test, pipeline.predict(X_test))
df = news_df[:]
le = LabelEncoder()
df['CATEGORY'] = le.fit_transform(df['CATEGORY'])
# Seems to be an error with calculating total unique words
plot_data = list()
for n in [2**n for n in range(10,30)]:
col = calc_collisions(df['TITLE'], hash_dim=n)
acc = run_classification(df, hash_dim=n)
plot_data.append([n, col, acc])
###Output
_____no_output_____
###Markdown
For this calculation, we only took a sample of 10,000 documents to speed up the calculation, and we only look at the lower hash dimensions.The takeaway from this is that you can **seriously** reduce your dimensionality without losing much predictive power.
###Code
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel("Hash Dimension")
ax1.set_ylabel('% Collisions', color=color)
ax1.plot([x[0] for x in plot_data], [x[1] for x in plot_data], color=color,
label='Collisions')
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:blue'
ax2.set_ylabel('Classifier Accuracy', color=color)
ax2.plot([x[0] for x in plot_data], [x[2] for x in plot_data], color=color,
label='Classifier Accuracy')
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.xlim(110000,0)
plt.show()
###Output
_____no_output_____ |
01 - Graphics.ipynb | ###Markdown
Graphics Import
###Code
import numpy as np
import pandas as pd
# matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
%matplotlib inline
# seaborn
import seaborn as sns
###Output
_____no_output_____
###Markdown
Scatter plot
###Code
soccer_data_clean.plot.scatter(x='yellowCards', y='regulatedYellowCards');
###Output
_____no_output_____
###Markdown
Histogram
###Code
rater_distinct_values = soccer_data_clean['rater'].value_counts(dropna=False, sort=False).plot(kind='bar')
rater_distinct_values.set_ylabel('Number of rates')
rater_distinct_values.set_xlabel('Rate values')
rater_distinct_values.set_title('Number of rates by values')
###Output
_____no_output_____
###Markdown
Pie chart
###Code
colorSkin = pd.cut(soccer_data_all_features['rater'], [0, 51, 101], labels=['light skin', 'dark skin'], right=False)
colorSkin.value_counts().plot(kind='pie', figsize=(6, 6))
###Output
_____no_output_____ |
examples/contracted_shapelet_transform.ipynb | ###Markdown
Univariate Example: GunPoint
###Code
# Load datasets
dataset = "GunPoint"
train_x, train_y = load_from_tsfile_to_dataframe("../sktime/datasets/data/"+dataset+"/"+dataset+"_TRAIN.ts")
test_x, test_y = load_from_tsfile_to_dataframe("../sktime/datasets/data/"+dataset+"/"+dataset+"_TRAIN.ts")
# Create Contracted Shapelet Transform with time limit of 1 monute:
st = ContractedShapeletTransform(
random_state=0,
verbose=0,
time_limit_in_mins=1,
num_candidates_to_sample_per_case=5,
max_shapelets_to_store_per_class=1000,
remove_self_similar=True
)
# Fit the transform
start_time = time.time()
shapelets = st.fit(train_x, train_y)
end_time = time.time()
print("Time taken: "+str(end_time-start_time))
# print the 5 best shapelets extracted in the minute:
for s in range(5):
print(st.shapelets[s])
# Transform the training data, then visualise the first 5 transformed cases
t_train_x = st.transform(train_x)
print("Number of shapelets: "+str(len(st.shapelets))+" (columns)")
print("Number of series: "+str(len(train_x))+" (rows) (limited to 5 below for presentation)")
t_train_x.head()
# Plot the top 5 shapelets on top of the series that they were extracted from
for s in st.shapelets[0:5]:
# summary info about the shapelet
print(s)
# plot the series that the shapelet was extracted from
plt.plot(
train_x.iloc[s.series_id,0],
'gray'
)
# overlay the shapelet onto the full series
plt.plot(
list(range(s.start_pos,(s.start_pos+s.length))),
train_x.iloc[s.series_id,0][s.start_pos:s.start_pos+s.length],
'r',
linewidth=3.0
)
plt.show()
###Output
Series ID: 4, start_pos: 91, length: 42, info_gain: 0.8749030545442665,
###Markdown
Multivariate Example: BasicMotions
###Code
# All steps as above for a multivariate datasets. The only difference is the last step, where we plot the single
# best shapelet from the 1 minute search across the 6 dimensions of the BasicMotions problem
dataset = "BasicMotions"
train_x, train_y = load_from_arff_to_dataframe("../sktime/datasets/data/"+dataset+"/"+dataset+"_TRAIN.arff")
test_x, test_y = load_from_arff_to_dataframe("../sktime/datasets/data/"+dataset+"/"+dataset+"_TRAIN.arff")
st = ContractedShapeletTransform(
random_state=0,
verbose=0,
time_limit_in_mins=1,
num_candidates_to_sample_per_case=5,
max_shapelets_to_store_per_class=1000,
remove_self_similar=True
)
start_time = time.time()
shapelets = st.fit(train_x, train_y)
end_time = time.time()
for s in range(5):
print(st.shapelets[s])
t_train_x = st.transform(train_x)
print("Number of shapelets: "+str(len(st.shapelets))+" (columns)")
print("Number of series: "+str(len(train_x))+" (rows) (limited to 5 below for presentation)")
t_train_x.head()
###Output
Number of shapelets: 32 (columns)
Number of series: 40 (rows) (limited to 5 below for presentation)
###Markdown
Single shapelet visualised over the 6 dimensions of BasicMotions
###Code
s = st.shapelets[0]
print(s)
# for each extracted shapelet (in descending order of quality/information gain)
for dim in range(len(train_x.iloc[0])):
print("Dimension "+str(dim+1))
# plot the series that the shapelet was extracted from
plt.plot(
train_x.iloc[s.series_id,dim],
'gray'
)
# overlay the shapelet onto the full series
plt.plot(
list(range(s.start_pos,(s.start_pos+s.length))),
train_x.iloc[s.series_id,dim][s.start_pos:s.start_pos+s.length],
'r',
linewidth=3.0
)
plt.show()
###Output
Series ID: 34, start_pos: 7, length: 16, info_gain: 0.7793498372920851,
Dimension 1
|
evaluations/jupyter/PlotSingleResults.ipynb | ###Markdown
Plot Results From a Single File
###Code
# to do math
import numpy as np
# to draw plots
import matplotlib.pyplot as plt
# to import csv files
import pandas as pd
# to manipulate path
import os.path
# report error
import sys
# make sure that the graphs appear directly on this page
%matplotlib inline
# to produce cosmetic print in markdown format
from IPython.display import Markdown, display
# cosmetic print for numpy
np.set_printoptions(precision=4, suppress=True)
###Output
_____no_output_____
###Markdown
User Parameters
###Code
#TODO: fill those variable to your files
env_name = 'ETH'
results_paths = ['../../../../data/pointmatcher_eval/eth_besl92.csv',
'../../../../data/pointmatcher_eval/eth_chen91.csv',
]
solution_names = ['point-to-point',
'point-to-plane',
]
protocol_path = '../../../../data/pointmatcher_eval/eth_protocol.csv'
validation_path = '../../../../data/pointmatcher_eval/eth_validation.csv'
###Output
_____no_output_____
###Markdown
Load Useful Files
###Code
def load_file(data_path):
if not os.path.isfile(protocol_path):
display(Markdown("**Error**: Could not find the file _%s_."%data_path))
sys.exit()
data = pd.read_csv(data_path)
# Parse header
nb_rows = len(data)
id_T = np.identity(4)
extra_headers = []
id_extra_header = []
for col, label in enumerate(data.columns.values):
label = label.strip()
if(label[0] == 'T'):
i = int(label[1])
j = int(label[2])
id_T[i,j] = col
elif(label[1] == 'T'):
i = int(label[2])
j = int(label[3])
id_T[i,j] = col
else:
extra_headers.append(label)
id_extra_header.append(col)
# Load data
new_header = extra_headers
new_header.append('T')
data_out = pd.DataFrame(index=np.arange(nb_rows), columns=new_header)
for row in np.arange(nb_rows):
for label, id_head in zip(extra_headers, id_extra_header):
data_out.iloc[row][label] = data.iloc[row, id_head]
T = np.identity(4)
for index, id_head in np.ndenumerate(id_T):
T[index] = data.iloc[row, int(id_head)]
data_out.iloc[row]['T'] = T
if 'time' in data_out.columns:
data_out['time'] = data_out['time'].astype(float, copy=False)
return data_out
# Load all files for a given environment
protocol_data = load_file(protocol_path)
validation_data = load_file(validation_path)
results_data_list = []
for results_path in results_paths:
results_data = load_file(results_path)
results_data_list.append(results_data)
if(not(len(results_data) == len(protocol_data) == len(validation_data))):
display(Markdown("**Error**: number of rows are not the same in each file."))
def perturbation(row):
delta_T = row.protocol['T'].dot(np.linalg.inv(row.validation['T']))
p_trans = np.linalg.norm(delta_T[0:3, 3])
rod = (np.trace(delta_T)/2.) - 1.
# handle value close to -1 or 1
rod = np.min([rod, 1.])
rod = np.max([rod, -1.])
p_rot = np.arccos(rod)
return pd.Series({('validation', 'perturbation_trans'):p_trans, ('validation', 'perturbation_rot'):p_rot})
def error(row):
out = []
for name in solution_names:
error_T = row[name, 'T'].dot(np.linalg.inv(row.validation['T']))
e_trans = np.linalg.norm(error_T[0:3, 3])
rod = (np.trace(error_T)/2.) - 1.
# handle value close to -1 or 1
rod = np.min([rod, 1.])
rod = np.max([rod, -1.])
e_rot = np.arccos(rod)
out.append(pd.Series({(name, 'error_trans'):e_trans, (name, 'error_rot'):e_rot}))
return pd.concat(out, axis=0)
# combine to one table
plot_data = pd.concat(([protocol_data, validation_data] + results_data_list),
axis=1, keys=(['protocol', 'validation'] + solution_names))
# Compute the level of perturbations
plot_data = pd.concat([plot_data, plot_data.apply(perturbation, axis=1)], axis=1)
# Compute the errors
plot_data = pd.concat([plot_data, plot_data.apply(error, axis=1)], axis=1)
# display the table
plot_data.sort_index(axis='columns', inplace=True)
plot_data.head(1)
###Output
_____no_output_____
###Markdown
Overall Performance Boxplot
###Code
boxprops = dict(linestyle='-', linewidth=1, color='blue')
medianprops = dict(linestyle='-', linewidth=5, color='red')
whiskerprops = dict(linestyle='--', linewidth=1, color='black')
fig = plt.figure(figsize=(12,6))
ax1 = fig.add_subplot(131)
plot_data.boxplot([('point-to-point', 'error_trans'), ('point-to-plane', 'error_trans')],
ax=ax1, return_type=None,
whis=[0,100], medianprops=medianprops, boxprops=boxprops, whiskerprops=whiskerprops);
ax1.set_xticklabels(solution_names)
ax1.set_title('$\it{' + env_name + '}$', fontsize=20)
ax1.set_ylabel('Error on translation (m)')
ax1.set_yscale('log')
ax2 = fig.add_subplot(132)
plot_data.boxplot([('point-to-point', 'error_rot'), ('point-to-plane', 'error_rot')],
ax=ax2, return_type=None,
whis=[0,100], medianprops=medianprops, boxprops=boxprops, whiskerprops=whiskerprops);
ax2.set_xticklabels(solution_names)
ax2.set_title('$\it{' + env_name + '}$', fontsize=20)
ax2.set_ylabel('Error on rotation (rad)')
ax2.set_yscale('log')
ax3 = fig.add_subplot(133)
plot_data.boxplot([('point-to-point', 'time'), ('point-to-plane', 'time')],
ax=ax3, return_type=None,
whis=[0,100], medianprops=medianprops, boxprops=boxprops, whiskerprops=whiskerprops);
ax3.set_xticklabels(solution_names)
ax3.set_title('$\it{' + env_name + '}$', fontsize=20)
ax3.set_ylabel('Time (sec)')
ax3.set_yscale('log')
fig.tight_layout(w_pad=2.)
fig = plt.figure(figsize=(12,6))
ax1 = fig.add_subplot(211)
for name in solution_names:
data = plot_data[name].error_trans.sort(inplace=False).values
cum_prob = np.linspace(0, 1., len(data))
ax1.plot(data, cum_prob,
'-', lw=2
);
ax1.set_xlabel('Error on translation (m)')
ax1.set_ylabel('Cumulative probability')
ax1.set_xlim([0., data.max()])
ax1.set_ylim([0., 1.01])
ax1.legend(solution_names)
ax2 = fig.add_subplot(212)
for name in solution_names:
data = plot_data[name].error_rot.sort(inplace=False).values
cum_prob = np.linspace(0, 1., len(data))
ax2.plot(data, cum_prob,
'-', lw=2
);
ax2.set_xlabel('Error on rotation (rad)')
ax2.set_ylabel('Cumulative probability')
ax2.set_xlim([0., data.max()])
ax2.set_ylim([0., 1.01])
ax2.legend(solution_names)
fig.tight_layout()
fig = plt.figure(figsize=(8,8))
ax1 = fig.add_subplot(111)
ax1.hexbin(plot_data.validation.perturbation_trans.unique(), plot_data.validation.perturbation_rot.unique(),
gridsize=30);
ax1.set_xlabel('Translation (m)')
ax1.set_ylabel('Rotation (rad)')
fig.tight_layout()
fig = plt.figure(figsize=(8,8))
ax1 = fig.add_subplot(111)
ax1.violinplot(plot_data[[('point-to-point', 'error_trans'), ('point-to-plane', 'error_trans')]].values)
ax1.set_yscale('log')
np.min(plot_data[[('point-to-point', 'error_rot')]])
plot_data['point-to-point', 'time'].values
###Output
_____no_output_____ |
neural-networks/assignment4/assignment4_final.ipynb | ###Markdown
Exercise Sheet 4 Implementing regression Deadline: 08.12.2020 23:59**Instructions:**Insert your code in the *TODO* sections ans type your answers in the *Answer* cells. Submit as a notebook together with the extra files (mentioned in later in the exercise) in an archive. -Bernadeta Griciūtė (7007672) \-Sangeet Sagar (7009050{begr00001,sasa00001\}@stud.uni-saarland.de} In this exercise we will implement a regression by hand instead of using sklearn package. We will use the same titanic dataset as last time, so first we have to load it.
###Code
import pandas as pd
## TODO: load the dataset into a pandas dataframe
titanic = pd.read_csv("titanic.csv")
titanic.head()
###Output
_____no_output_____
###Markdown
Fitting a regression means finding a line such that the mean distance from the actual datapoints and their projections onto the line (predictions), i.e. the error, is minimal. We achive that by defining the loss function (MSE in case of linear regression) and minimizing it, or in other words, finding the minimum point. In this exercise we will fit a linear regression with one predictor (age of the passenger) without intercept, so that our loss function is dependent only on the coefficient (aka weight) *w*, so that the loss function is defined as *MSE(w)*. 4.1 Prepare data (0.5 points)As we are fitting a model without the intercept, we need to center the data.
###Code
import matplotlib.pyplot as plt
import numpy as np
## TODO: center the input data and save under x (age of the passenger) and y (price of the ticket) variables
x = titanic[["Age"]] - np.mean(titanic[["Age"]])
y = titanic[["Price"]] - np.mean(titanic[["Price"]])
## Uncomment this part for plotting
fig, axs = plt.subplots(1, 2)
fig.tight_layout()
axs[0].scatter(titanic.Age, titanic.Price, s=4)
axs[0].set_title('Original')
axs[0].set_ylabel('Price of the ticket')
axs[1].scatter(x, y, color = 'r', s=4)
axs[1].set_title('Centered')
for ax in axs:
ax.set_xlim(-40, 90)
ax.set_ylim(-50, 250)
ax.set_xlabel('Age')
ax.grid(True)
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
plt.show()
###Output
_____no_output_____
###Markdown
4.2 Define the loss function (0.5 points)Write the formula for calculating the loss function *MSE(w)* with $\textbf{X}^{n*m}$ as a matrix with input data, *n* - the number of datapoints, *m* - the number of features, $\textbf{y}^{n}$ - vector containing ground truth values. *Answer*: $$MSE(w) = \sum_1^N\|\textbf{y}^n −\textbf{X}^{n\times m}w^T\|^2 $$Where: $w$: vector of size $1 \times m$ 4.3 Create a computational graph for the loss function (2 points)In this part you will create a computational graph for the loss funciton defined above. Please, have a look at this tutorial to understand what a computational graph is.We will use an application for creating diagrams draw.io for creating the graph. In the exercise materials there is a file *ComputationalGraphs_Instructions*. Go to the application and open this file. Follow the instructions in the file.Save your graph under *computational_graph.png* in the same folder as this notebook and execute the next cell to print it. You can change the *width* parameter to adjust to your image.Don't forget to add the file to the archive together with this notebook! 4.4 Plot the loss function (2 points)In this part you will use the computational graph for calculating the loss function and plotting it.
###Code
import numpy as np
## TODO: define the input values
## w: an array of possible values of w for plotting, from -5 to 5 with a step of 0.1
## x: centered input values (age of the passengers)
## y: centered output values (price of the ticket)
## n: number of data points
x = titanic[["Age"]] - np.mean(titanic[["Age"]])
y = titanic[["Price"]] - np.mean(titanic[["Price"]])
w = np.arange(-5,5, 0.1)
x = x.to_numpy()
y = y.to_numpy()
n = x.shape[0]
## Reshape the data according to how you defined dimensions in the computational graph using .reshape() method
w = w.reshape(len(w),1)
x = x.reshape(n,1)
y = y.reshape(n,1)
# n # scalar value can not be rehaped
## Uncomment for printing
print('w:', str(w.shape),
'\nx:', str(x.shape),
'\ny:', str(y.shape))
## TODO: compute the intermediate nodes and the output node of the graph.
## Be consistent with the names of the variables.
B = np.dot(x, w.T)
C = y - B
D = C**2
E = np.ones(n).reshape(1, n)
F = np.dot(E, D)
## TODO: reshape w and mse for plotting: they should have shape (100,)
mse = F.reshape(len(w),1)
w = w.reshape(len(w),1)
print('mse:', str(mse.shape))
# ## Uncomment for plotting
plt.plot(w, mse)
plt.xlabel('w')
plt.ylabel('MSE')
plt.title('Optimization of w')
plt.grid(True)
plt.show()
###Output
w: (100, 1)
x: (714, 1)
y: (714, 1)
mse: (100, 1)
###Markdown
4.5 Find the minimum point of the loss functionWe can find the minimum point of the function, which is the optimal weight, using its first derivative. Go through this tutorial on Khan Academy for refreshment of calculating the derivative. 4.5.1 Get the formula to calculate the optimal weight (2 points)Insert intermediate steps (you can find them on pages 106-107 of Deep Learning book, chapter 5 Machine Learning) and explain the transitions from one step to another. *Answer*: 1. $\nabla_w MSE = \nabla_w \frac{1}{n}||\hat{y} - y||_2^2$ = 0 We know that $\hat{y}$ represent the predictions of the model on the test set and is equal to $X^{train}w$$$ \frac{1}{n}\nabla_w \|X^{train}w -\textbf{y}^{train}\|_2^2 = 0 $$Expanding the above equation we get-$$ \nabla_w (X^{train}w -\textbf{y}^{train})^T*(X^{train}w -\textbf{y}^{train}) = 0 $$$$ \nabla_w ((X^{train}w)^T -(\textbf{y}^{train})^T)*(X^{train}w -\textbf{y}^{train}) = 0 $$Use the property- $(AB)^T = B^TA^T$ and multiply both terms$$ \nabla_w ((w^TX^{train^T} -\textbf{y}^{train^T})*(X^{train}w -\textbf{y}^{train}) = 0 $$$$ \nabla_w (w^TX^{train^T}X^{train}w - w^TX^{train^T}y^{train}-\textbf{y}^{train^T}X^{train}w + y^{train^T}y^{train}) = 0 $$Focus on the third term- again use: $(AB)^T = B^TA^T$$$ (w^TX^{train^T}X^{train}w - w^TX^{train^T}y^{train}-(X^{train}w)^T{y}^{train^T} + y^{train^T}y^{train}) = 0 $$$$ (w^TX^{train^T}X^{train}w - w^TX^{train^T}y^{train}-X^{train^T}w^T{y}^{train^T} + y^{train^T}y^{train}) = 0 $$Now we can add second and third term-$$ (w^TX^{train^T}X^{train}w - 2w^TX^{train^T}y^{train} + y^{train^T}y^{train}) = 0 $$$$ \implies 2X^{train^T}X^{train}w - 2X^{train^T}y^{train} = 0 $$$$ \implies w =(X^{train^T}X^{train})^{-1}X^{train^T}y^{train} = 0 $$ 6. $w = (X^T X)^{-1} X^T y$ 4.5.2 Compute the optimal **w** (0.5 points)1. from formula 6;2. using sklearn: fit a regression (without the intercept!) and get the value of **w** to check your solution.
###Code
from sklearn.linear_model import LinearRegression
from numpy.linalg import inv # for calculating the inverse
## TODO: compute the optimal w using formula 6 from the exercise above
a = np.dot(x.T, x)
b = np.linalg.inv(a)
c = np.dot(x.T, y)
optimal_w = np.dot(b, c)[0][0] ## this shold be a float number
## TODO: fit a regression without the intercept and get the value of the coefficient (call using .coef_)
lr = LinearRegression()
X = titanic["Age"].to_numpy().reshape(-1, 1) # Training data
y_true = titanic["Price"].to_numpy().reshape(-1, 1) # Target values
lr.fit(X, y_true)
sk_model_coef = lr.coef_[0][0] ## this shold be a float number
## Uncomment for printing
print('Optimal weight we computed:', '\t\t', str(optimal_w), '\n'
'Model coefficient from sklearn:', '\t', str(sk_model_coef))
###Output
Optimal weight we computed: 0.33511180736566953
Model coefficient from sklearn: 0.3351118073656695
|
examples/Figure generation.ipynb | ###Markdown
Read in variables
###Code
inFile = open('trace_n100_genParams.pkl','rb')
trace = load(inFile)
inFile.close()
datadir = '../data/small_sample/'
infile = open(datadir+'T.pkl','rb')
T = load(infile)
infile.close()
infile = open(datadir+'obs_jumps.pkl','rb')
obs_jumps = load(infile)
infile.close()
infile = open(datadir+'O.pkl','rb')
O = load(infile)
infile.close()
newN = 100
T = T[:newN]
nObs = T.sum()
obs_jumps = obs_jumps[0:nObs]
O = O[0:nObs]
pi = trace['pi']
Q = trace['Q']
S = trace['S']
B0 = trace['B0']
B = trace['B']
X = trace['X']
Z = trace['Z']
L = trace['L']
N = T.shape[0] # Number of patients
M = pi[0].shape[0] # Number of hidden states
K = Z[0].shape[0] # Number of comorbidities
D = Z[0].shape[1] # Number of claims
Sbin = np.vstack([np.bincount(S[i],minlength=4)/float(len(S[i])) for i in range(len(S))])
zeroIndices = np.roll(T.cumsum(),1)
zeroIndices[0] = 0
pibar = np.vstack([np.bincount(S[i][zeroIndices],minlength=M)/float(zeroIndices.shape[0]) for i in range(len(S))])
SEnd = np.vstack([np.bincount(S[i][zeroIndices-1],minlength=M)/float(zeroIndices.shape[0]) for i in range(len(S))])
XChanges = np.insert(1-(1-(X[:,1:]-X[:,:-1])).prod(axis=2),0,0,axis=1)
XChanges.T[zeroIndices] = 0
XChanges[XChanges.nonzero()] = XChanges[XChanges.nonzero()]/XChanges[XChanges.nonzero()]
XChanges = XChanges.sum(axis=1)/float(N)
###Output
_____no_output_____
###Markdown
Probability of Current and Future States
###Code
nPick=10
tPick = 1
ntStart = zeroIndices[nPick]
curObs = ntStart + tPick+1
#print obs_jumps[ntStart:ntStart+10]
#print O[ntStart:ntStart+10]
#print X[-1][ntStart:ntStart+10]
#OK, do this properly later
likelihood_S_0_1 = np.array([9.53625347e-01, 1.86315267e-02, 1.44532352e-03, 3.14356015e-04])
likelihood_X_0_1 = np.array([[ 2.56550334e-14, 1.21956409e-04],
[ 1.63014965e-04,1.63011786e-04],
[ 1.42531099e-04, 4.28589290e-05],
[ 1.27941508e-09,9.56828390e-05]])
likelihood_X_0_1 = likelihood_X_0_1[:,1]/likelihood_X_0_1.sum(axis=1)
print likelihood_S_0_1
print likelihood_X_0_1
###Output
[ 9.53625347e-01 1.86315267e-02 1.44532352e-03 3.14356015e-04]
[ 1. 0.49999512 0.23118249 0.99998663]
|
p1_navigation/Navigation_tf.ipynb | ###Markdown
Navigation---In this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893). 1. Start the EnvironmentWe begin by importing some necessary packages. If the code cell below returns an error, please revisit the project instructions to double-check that you have installed [Unity ML-Agents](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md) and [NumPy](http://www.numpy.org/).
###Code
import os
from unityagents import UnityEnvironment
import numpy as np
import tensorflow as tf
print('TensorFlow Version:', tf.__version__)
from utility_tf import mask_busy_gpus
mask_busy_gpus(1) # randomly select 1 unused GPU
from collections import deque
import matplotlib.pyplot as plt
%matplotlib inline
plt.ion()
###Output
WARNING:tensorflow:From /home/LZhu14/Work/Code/deep-reinforcement-learning/p1_navigation/utility_tf.py:55: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
###Markdown
Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded.- **Mac**: `"path/to/Banana.app"`- **Windows** (x86): `"path/to/Banana_Windows_x86/Banana.exe"`- **Windows** (x86_64): `"path/to/Banana_Windows_x86_64/Banana.exe"`- **Linux** (x86): `"path/to/Banana_Linux/Banana.x86"`- **Linux** (x86_64): `"path/to/Banana_Linux/Banana.x86_64"`- **Linux** (x86, headless): `"path/to/Banana_Linux_NoVis/Banana.x86"`- **Linux** (x86_64, headless): `"path/to/Banana_Linux_NoVis/Banana.x86_64"`For instance, if you are using a Mac, then you downloaded `Banana.app`. If this file is in the same folder as the notebook, then the line below should appear as follows:```env = UnityEnvironment(file_name="Banana.app")```
###Code
env = UnityEnvironment(file_name=os.path.normpath("./Banana_Linux_NoVis/Banana.x86_64"))
###Output
INFO:unityagents:
'Academy' started successfully!
Unity Academy name: Academy
Number of Brains: 1
Number of External Brains : 1
Lesson number : 0
Reset Parameters :
Unity brain name: BananaBrain
Number of Visual Observations (per agent): 0
Vector Observation space type: continuous
Vector Observation space size (per agent): 37
Number of stacked Vector Observation: 1
Vector Action space type: discrete
Vector Action space size (per agent): 4
Vector Action descriptions: , , ,
###Markdown
Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.
###Code
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
###Output
_____no_output_____
###Markdown
2. Examine the State and Action SpacesThe simulation contains a single agent that navigates a large environment. At each time step, it has four actions at its disposal:- `0` - walk forward - `1` - walk backward- `2` - turn left- `3` - turn rightThe state space has `37` dimensions and contains the agent's velocity, along with ray-based perception of objects around agent's forward direction. A reward of `+1` is provided for collecting a yellow banana, and a reward of `-1` is provided for collecting a blue banana. Run the code cell below to print some information about the environment.
###Code
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.vector_observations[0]
print('States is of type:', type(state))
print('States look like:', state)
state_size = len(state)
print('States have length:', state_size)
###Output
Number of agents: 1
Number of actions: 4
States is of type: <class 'numpy.ndarray'>
States look like: [1. 0. 0. 0. 0.84408134 0.
0. 1. 0. 0.0748472 0. 1.
0. 0. 0.25755 1. 0. 0.
0. 0.74177343 0. 1. 0. 0.
0.25854847 0. 0. 1. 0. 0.09355672
0. 1. 0. 0. 0.31969345 0.
0. ]
States have length: 37
###Markdown
3. Take Random Actions in the EnvironmentIn the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment.Once this cell is executed, you will watch the agent's performance, if it selects an action (uniformly) at random with each time step. A window should pop up that allows you to observe the agent, as it moves through the environment. Of course, as part of the project, you'll have to change the code so that the agent is able to use its experience to gradually choose better actions when interacting with the environment!
###Code
# test the untrained agent for n_test times
n_test = 20
score_list = []
for _ in range(n_test):
env_info = env.reset(train_mode=False)[brain_name] # reset the environment
state = env_info.vector_observations[0] # get the current state
score = 0 # initialize the score
while True:
action = np.random.randint(action_size) # select an action
env_info = env.step(action)[brain_name] # send the action to the environment
next_state = env_info.vector_observations[0] # get the next state
reward = env_info.rewards[0] # get the reward
done = env_info.local_done[0] # see if episode has finished
state = next_state # roll over the state to next time step
score += reward # update the score
if done: # exit loop if episode finished
break
score_list.append(score)
print("Average score (random actions): {}".format(np.mean(score_list)))
###Output
Average score (random actions): 0.15
###Markdown
When finished, you can close the environment.```pythonenv.close()``` 4. Define the agent training function
###Code
def train_dqn(env, agent, save_model, n_episodes=3000,
eps_start=1.0, eps_end=0.01, eps_decay=0.995,
deque_len=100, print_every=100, finish_threshold=13.0):
"""Deep Q-Learning.
Params
======
env: environment
agent: deep Q-learning agent
save_model: model filename for saving
n_episodes (int): maximum number of training episodes
eps_start (float): starting value of epsilon, for epsilon-greedy action selection
eps_end (float): minimum value of epsilon
eps_decay (float): multiplicative factor (per episode) for decreasing epsilon
deque_len (int): length of score deque
print_every (int): print a new line of scores after such number of episodes
finish_threshold (float): the training process will finish if the average score is larger than such threshold
"""
scores_deque = deque(maxlen=deque_len) # deque containing last deque_len scores to calculate moving average scores
scores = [] # list containing scores from each episode
scores_movingmean = [] # list containing moving average scores
eps = eps_start # initialize epsilon
for i_episode in range(1, n_episodes+1):
env_info = env.reset(train_mode=True)[brain_name]
state = env_info.vector_observations[0]
score = 0
step = 0
while True:
step += 1
action = agent.act(state, eps)
env_info = env.step(action)[brain_name] # send the action to the environment
next_state = env_info.vector_observations[0] # get the next state
reward = env_info.rewards[0] # get the reward
done = env_info.local_done[0] # see if episode has finished
agent.step(state, action, reward, next_state, done)
state = next_state
score += reward
if done:
break
scores.append(score) # save most recent score
scores_deque.append(score) # save most recent score
scores_movingmean.append(np.mean(scores_deque))
eps = max(eps_end, eps_decay*eps) # decrease epsilon
print('\rEpisode {}\tMoving average score: {:.2f}\tCurrent score: {}'.format(i_episode, scores_movingmean[-1], score), end="")
if i_episode % print_every == 0:
print('\rEpisode {}\tMoving average score: {:.2f}\tCurrent score: {}'.format(i_episode, scores_movingmean[-1], score))
if scores_movingmean[-1] >= finish_threshold:
print('\nEnvironment solved in {:d} episodes!\tMoving average score: {:.2f}'.format(i_episode-deque_len, scores_movingmean[-1]))
break
agent.qnetwork_local.save_weights(save_model) # save the model
return scores, scores_movingmean
###Output
_____no_output_____
###Markdown
5. Deep Q-learning 5.1. Train the agent
###Code
from agent_dqn_tf import Agent
# deep Q-learning agent
agent_dqn = Agent(action_size, seed=0, use_double=False, use_dueling=False, use_per=False)
scores_dqn, scores_dqn_movingmean = train_dqn(env, agent_dqn, 'model_dqn.h5', finish_threshold=14.5)
agent_dqn.qnetwork_local.summary()
###Output
Episode 3 Moving average score: -1.33 Current score: 0.00
###Markdown
5.2. Plot the training score curve
###Code
plt.figure()
plt.plot(np.arange(1, len(scores_dqn)+1), scores_dqn,
label='scores')
plt.plot(np.arange(1, len(scores_dqn_movingmean)+1), scores_dqn_movingmean,
label='moving average scores')
plt.legend()
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.title('Deep Q-learning')
plt.show()
###Output
_____no_output_____
###Markdown
5.3. Test the trained deep Q-learning agent
###Code
# load the saved model file
agent_dqn.qnetwork_local.load_weights('model_dqn.h5')
# test the trained agent for n_test times
n_test = 20
score_dqn_list = []
for _ in range(n_test):
env_info = env.reset(train_mode=False)[brain_name]
state = env_info.vector_observations[0]
score = 0
while True:
action = agent_dqn.act(state)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
state = next_state
score += reward
if done:
break
score_dqn_list.append(score)
print("Average score (after deep Q-learning): {}".format(np.mean(score_dqn_list)))
###Output
Average score (after deep Q-learning): 9.25
###Markdown
6. Double deep Q-learning 6.1. Train the agent
###Code
# double deep Q-learning agent
agent_doubledqn = Agent(action_size, seed=0, use_double=True, use_dueling=False, use_per=False)
scores_doubledqn, scores_doubledqn_movingmean = train_dqn(env, agent_doubledqn, 'model_doubledqn.h5', finish_threshold=14.5)
agent_doubledqn.qnetwork_local.summary()
###Output
Episode 3 Moving average score: 0.00 Current score: 1.000
###Markdown
6.2. Plot the training score curve
###Code
plt.figure()
plt.plot(np.arange(1, len(scores_doubledqn)+1), scores_doubledqn,
label='scores')
plt.plot(np.arange(1, len(scores_doubledqn_movingmean)+1), scores_doubledqn_movingmean,
label='moving average scores')
plt.legend()
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.title('Double deep Q-learning')
plt.show()
###Output
_____no_output_____
###Markdown
6.3. Test the trained double deep Q-learning agent
###Code
# load the saved model file
agent_doubledqn.qnetwork_local.load_weights('model_doubledqn.h5')
# test the trained agent for n_test times
n_test = 20
score_doubledqn_list = []
for _ in range(n_test):
env_info = env.reset(train_mode=False)[brain_name]
state = env_info.vector_observations[0]
score = 0 # initialize the score
while True:
action = agent_doubledqn.act(state)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
state = next_state
score += reward
if done:
break
score_doubledqn_list.append(score)
print("Average score (after double deep Q-learning): {}".format(np.mean(score_doubledqn_list)))
###Output
Average score (after double deep Q-learning): 7.65
###Markdown
7. Dueling deep Q-learning 7.1. Train the agent
###Code
# dueling deep Q-learning agent
agent_duelingdqn = Agent(action_size, seed=0, use_double=False, use_dueling=True, use_per=False)
scores_duelingdqn, scores_duelingdqn_movingmean = train_dqn(env, agent_duelingdqn, 'model_duelingdqn.h5', finish_threshold=14.5)
agent_duelingdqn.qnetwork_local.summary()
###Output
Episode 3 Moving average score: 0.00 Current score: -1.0
###Markdown
7.2. Plot the training score curve
###Code
plt.figure()
plt.plot(np.arange(1, len(scores_duelingdqn)+1), scores_duelingdqn,
label='scores')
plt.plot(np.arange(1, len(scores_duelingdqn_movingmean)+1), scores_duelingdqn_movingmean,
label='moving average scores')
plt.legend()
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.title('Dueling deep Q-learning')
plt.show()
###Output
_____no_output_____
###Markdown
7.3. Test the trained dueling deep Q-learning agent
###Code
# load the saved model file
agent_duelingdqn.qnetwork_local.load_weights('model_duelingdqn.h5')
# test the trained agent for n_test times
n_test = 20
score_duelingdqn_list = []
for _ in range(n_test):
env_info = env.reset(train_mode=False)[brain_name]
state = env_info.vector_observations[0]
score = 0 # initialize the score
while True:
action = agent_duelingdqn.act(state)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
state = next_state
score += reward
if done:
break
score_duelingdqn_list.append(score)
print("Average score (after dueling deep Q-learning): {}".format(np.mean(score_duelingdqn_list)))
###Output
Average score (after dueling deep Q-learning): 7.7
###Markdown
8. Double deep Q-learning with Prioritized Experience Replay (PER) 8.1. Train the agent
###Code
# double deep Q-learning agent with PER
agent_doubledqnper = Agent(action_size, seed=0, use_double=True, use_dueling=False, use_per=True)
scores_doubledqnper, scores_doubledqnper_movingmean = train_dqn(env, agent_doubledqnper, 'model_doubledqnper.h5', finish_threshold=14.5)
agent_doubledqnper.qnetwork_local.summary()
###Output
Episode 3 Moving average score: -0.33 Current score: -1.0
###Markdown
8.2. Plot the training score curve
###Code
plt.figure()
plt.plot(np.arange(1, len(scores_doubledqnper)+1), scores_doubledqnper,
label='scores')
plt.plot(np.arange(1, len(scores_doubledqnper_movingmean)+1), scores_doubledqnper_movingmean,
label='moving average scores')
plt.legend()
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.title('Double deep Q-learning with PER')
plt.show()
###Output
_____no_output_____
###Markdown
8.3. Test the trained double deep Q-learning agent with PER
###Code
# load the saved model file
agent_doubledqnper.qnetwork_local.load_weights('model_doubledqnper.h5')
# test the trained agent for n_test times
n_test = 20
score_doubledqnper_list = []
for _ in range(n_test):
env_info = env.reset(train_mode=False)[brain_name]
state = env_info.vector_observations[0]
score = 0 # initialize the score
while True:
action = agent_doubledqnper.act(state)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
state = next_state
score += reward
if done:
break
score_doubledqnper_list.append(score)
print("Average score (after double deep Q-learning with PER): {}".format(np.mean(score_doubledqnper_list)))
###Output
Average score (after double deep Q-learning with PER): 12.85
###Markdown
9. Comparing the running mean score curves
###Code
plt.figure()
plt.plot(np.arange(1, len(scores_dqn_movingmean)+1), scores_dqn_movingmean,
label='deep Q-learning')
plt.plot(np.arange(1, len(scores_doubledqn_movingmean)+1), scores_doubledqn_movingmean,
label='double deep Q-learning')
plt.plot(np.arange(1, len(scores_duelingdqn_movingmean)+1), scores_duelingdqn_movingmean,
label='dueling deep Q-learning')
plt.plot(np.arange(1, len(scores_doubledqnper_movingmean)+1), scores_doubledqnper_movingmean,
label='double deep Q-learning w/PER')
plt.legend()
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.title('Moving average scores of various deep Q-learning methods')
plt.show()
###Output
_____no_output_____
###Markdown
10. Close the environment
###Code
env.close()
###Output
_____no_output_____ |
Machine Learning/_U10/CNN_ResNet.ipynb | ###Markdown
Task 2Plot the loss and acc at each iteration and epoch
###Code
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import argparse
import os
# check if cuda is available, if not just use cpu
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# configuration of parameters
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('--outf', default='./model/', help='folder to output images and model checkpoints')
args = parser.parse_args([])
# configuration of hyperparameters
EPOCH = 5
pre_epoch = 0
BATCH_SIZE = 128
LR = 0.01
# prepare the dataset and preprocessing
# use mean and variance to normalize
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
# Get dataset online
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)
# Cifar-10 labels
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# define a resnet
net = ResNet18().to(device)
criterion = nn.CrossEntropyLoss()
#optimize with mini-batch momentum-SGD using L2-normalization
optimizer = optim.SGD(net.parameters(), lr=LR, momentum=0.9, weight_decay=5e-4)
best_acc = 85
print("Start Training...")
for epoch in range(pre_epoch, EPOCH):
print('\nEpoch: %d' % (epoch + 1))
net.train()
sum_loss = 0.0
correct = 0.0
total = 0.0
for i, data in enumerate(trainloader, 0):
# preparing for data
length = len(trainloader)
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
# forward + backward
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print out the loss and acc for every batch
sum_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += predicted.eq(labels.data).cpu().sum()
print('[epoch:%d, iter:%d] Loss: %.03f | Acc: %.3f%% '
% (epoch + 1, (i + 1 + epoch * length), sum_loss / (i + 1), 100. * correct / total))
# after each epoch print out the acc
print("Waiting Test!")
with torch.no_grad():
correct = 0
total = 0
for data in testloader:
net.eval()
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Test acc:%.3f%%' % (100 * correct / total))
acc = 100. * correct / total
print("Training Finished, TotalEPOCH=%d" % EPOCH)
###Output
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz
###Markdown
best_acc= 96.285%In this src file, we just set the epoch = 5 for quick execution. While we were training the model, we have set epoch = 135 and it takes ~ 54min. You can check the changes of acc from the sreenshot in the zip-file.
###Code
print(net.layer1)
# Get the first CNN layer
print(list(list(net.layer1[0].children())[0].children())[0])
first_filter = list(list(net.layer1[0].children())[0].children())[0].weight
###Output
Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
###Markdown
Task 1Plot the filters of the first layer
###Code
import numpy as np
import matplotlib.pyplot as plt
global res
print(res.size())
print(res)
# torchvision.utils.make_grid(res)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i in range (0,128):
z = res[i]
ax.plot_surface(z.cpu().detach().numpy()[0],z.cpu().detach().numpy()[1],z.cpu().detach().numpy()[2],cmap='rainbow')
plt.show()
# visualize the first conv layer filters
def virtualize(color):
plt.figure(figsize=(20, 17))
for i, filter in enumerate(first_filter):
# (4, 4) because in conv0 we have 3x3 filters and total of 16 (see printed shapes)
plt.subplot(4, 4, i+1)
plt.imshow(filter[0, :, :].cpu().detach(), cmap=color)
plt.axis('off')
plt.show()
virtualize("gray")
virtualize("rainbow")
###Output
_____no_output_____ |
Code/ballot-polling-audit-example.ipynb | ###Markdown
Ballot Polling Assertion RLA Examples
###Code
from __future__ import division, print_function
import math
import json
import warnings
import numpy as np
import copy
from collections import OrderedDict
from assertion_audit_utils import \
Assertion, Assorter, CVR, TestNonnegMean, check_audit_parameters,\
find_p_values, summarize_status
###Output
_____no_output_____
###Markdown
Example 1: small election, large marginThis election is between Alice and Bob and contains 100 ballots. The reported winner is Alice with 70% of the valid votes. Candidate | total ---|---Alice | 70Bob | 30Ballots | 100A sample of 30 ballots (simulated from ASN) is drawn from 100 ballots with and without replacement. 73.33% (22/30 cards) of the sample is for Alice and 26.67% (8/30 cards) of the ballots is for Bob. The example audits are done with and without replacement using the `wald_sprt` and `kaplan_kolmogorov` risk functions respectively.
###Code
contests = {'339':{'risk_limit': 0.05,
'choice_function': 'plurality',
'n_winners': 1,
'candidates': ['Alice', 'Bob'],
'reported_winners': ['Alice']
}
}
mvr_file = './Data/mvr_polling_example_1.json'
manifest_type = 'STYLE'
all_assertions = Assertion.make_all_assertions(contests)
with open(mvr_file) as f:
mvr_json = json.load(f)
mvr_sample = CVR.from_dict(mvr_json['ballots'])
###Output
_____no_output_____
###Markdown
With replacement
###Code
risk_fn = lambda x: TestNonnegMean.wald_sprt(np.array(x), N=N_cards, t=t, p1=p1, random_order=False)
N_cards = np.inf
t=1/2
p1=0.7
p_max = find_p_values(contests, all_assertions, risk_fn, manifest_type, mvr_sample)
print("maximum assertion p-value {}".format(p_max))
np.testing.assert_almost_equal(p_max, (t/p1)**22 * np.divide(1-t, 1-p1)**8)
###Output
maximum assertion p-value 0.036305566021550766
###Markdown
Without replacement
###Code
risk_fn = lambda x: TestNonnegMean.kaplan_kolmogorov(np.array(x), N=N_cards, t=t, g=g, random_order=False)
N_cards = 100
t=1/2
g=0.1
p_max = find_p_values(contests, all_assertions, risk_fn, manifest_type, mvr_sample)
print("maximum assertion p-value {}".format(p_max))
np.testing.assert_almost_equal(p_max, 1.1**-22 * 0.6 * np.prod(np.divide(np.linspace(60, 38, 21), \
np.arange(79, 100))) * 0.1**-8 * (np.prod(np.divide(np.linspace(36.9, 36.2, 8), \
np.arange(71, 79)))))
###Output
maximum assertion p-value 0.07715494796551615
###Markdown
Example 2: Medium election, large marginThis election is between Alice and Bob and contains 10000 ballots. The reported winner is Alice with 60% of the valid votes. Candidate | total ---|---Alice | 6000Bob | 4000Ballots | 10000A sample of 200 ballots is drawn from 10000 ballots with and without replacement. The sample shows 65% (130/200 cards) of the ballots are for Alice and 35% (70/200 cards) of the ballots are for Bob. The example audits are done with and without replacement using the `wald_sprt` and `kaplan_kolmogorov` risk functions respectively.
###Code
#contests to audit
contests = {'339':{'risk_limit': 0.05,
'choice_function': 'plurality',
'n_winners': 1,
'candidates': ['Alice', 'Bob'],
'reported_winners': ['Alice']
}
}
mvr_file = './Data/mvr_polling_example_2.json'
manifest_type = 'STYLE'
all_assertions = Assertion.make_all_assertions(contests)
with open(mvr_file) as f:
mvr_json = json.load(f)
mvr_sample = CVR.from_dict(mvr_json['ballots'])
###Output
_____no_output_____
###Markdown
With replacement
###Code
risk_fn = lambda x: TestNonnegMean.wald_sprt(np.array(x), N=N_cards, t=t, p1=p1, random_order=False)
N_cards = np.inf
t=1/2
p1=0.60
p_max = find_p_values(contests, all_assertions, risk_fn, manifest_type, mvr_sample)
print("maximum assertion p-value {}".format(p_max))
np.testing.assert_almost_equal(p_max, (t/p1)**130 * np.divide(1-t, 1-p1)**70)
###Output
maximum assertion p-value 0.0003091284130380668
###Markdown
Without replacement
###Code
risk_fn = lambda x: TestNonnegMean.kaplan_kolmogorov(np.array(x), N=N_cards, t=t, g=g, random_order=False)
N_cards = 10000
t=1/2
g=0.5
p_max = find_p_values(contests, all_assertions, risk_fn, manifest_type, mvr_sample)
print("maximum assertion p-value {}".format(p_max))
np.testing.assert_almost_equal(p_max, 1.5**-130 * np.prod(np.divide(np.linspace(10000, 9808, 129), \
np.arange(9871, 10000))) * 0.5**-70 * (np.prod(np.divide(np.linspace(9806.5, \
9772, 70), np.arange(9801, 9871)))))
###Output
maximum assertion p-value 0.00726793364131293
|
Model backlog/Inference/249-tweet-inference-5fold-roberta-onecycle-lr-hidd.ipynb | ###Markdown
Dependencies
###Code
import json, glob
from tweet_utility_scripts import *
from tweet_utility_preprocess_roberta_scripts_aux import *
from transformers import TFRobertaModel, RobertaConfig
from tokenizers import ByteLevelBPETokenizer
from tensorflow.keras import layers
from tensorflow.keras.models import Model
###Output
_____no_output_____
###Markdown
Load data
###Code
test = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/test.csv')
print('Test samples: %s' % len(test))
display(test.head())
###Output
Test samples: 3534
###Markdown
Model parameters
###Code
input_base_path = '/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/'
with open(input_base_path + 'config.json') as json_file:
config = json.load(json_file)
config
vocab_path = input_base_path + 'vocab.json'
merges_path = input_base_path + 'merges.txt'
base_path = '/kaggle/input/qa-transformers/roberta/'
# vocab_path = base_path + 'roberta-base-vocab.json'
# merges_path = base_path + 'roberta-base-merges.txt'
config['base_model_path'] = base_path + 'roberta-base-tf_model.h5'
config['config_path'] = base_path + 'roberta-base-config.json'
model_path_list = glob.glob(input_base_path + '*.h5')
model_path_list.sort()
print('Models to predict:')
print(*model_path_list, sep = '\n')
###Output
Models to predict:
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_1.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_2.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_3.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_4.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_5.h5
###Markdown
Tokenizer
###Code
tokenizer = ByteLevelBPETokenizer(vocab_file=vocab_path, merges_file=merges_path,
lowercase=True, add_prefix_space=True)
###Output
_____no_output_____
###Markdown
Pre process
###Code
test['text'].fillna('', inplace=True)
test['text'] = test['text'].apply(lambda x: x.lower())
test['text'] = test['text'].apply(lambda x: x.strip())
x_test, x_test_aux, x_test_aux_2 = get_data_test(test, tokenizer, config['MAX_LEN'], preprocess_fn=preprocess_roberta_test)
###Output
_____no_output_____
###Markdown
Model
###Code
module_config = RobertaConfig.from_pretrained(config['config_path'], output_hidden_states=True)
def model_fn(MAX_LEN):
input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')
base_model = TFRobertaModel.from_pretrained(config['base_model_path'], config=module_config, name="base_model")
_, _, hidden_states = base_model({'input_ids': input_ids, 'attention_mask': attention_mask})
h11 = hidden_states[-2]
logits = layers.Dense(2, use_bias=False, name="qa_outputs")(h11)
start_logits, end_logits = tf.split(logits, 2, axis=-1)
start_logits = tf.squeeze(start_logits, axis=-1, name='y_start')
end_logits = tf.squeeze(end_logits, axis=-1, name='y_end')
model = Model(inputs=[input_ids, attention_mask], outputs=[start_logits, end_logits])
return model
###Output
_____no_output_____
###Markdown
Make predictions
###Code
NUM_TEST_IMAGES = len(test)
test_start_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN']))
test_end_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN']))
for model_path in model_path_list:
print(model_path)
model = model_fn(config['MAX_LEN'])
model.load_weights(model_path)
test_preds = model.predict(get_test_dataset(x_test, config['BATCH_SIZE']))
test_start_preds += test_preds[0]
test_end_preds += test_preds[1]
###Output
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_1.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_2.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_3.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_4.h5
/kaggle/input/249-tweet-train-5fold-roberta-onecycle-lr-hidden11/model_fold_5.h5
###Markdown
Post process
###Code
test['start'] = test_start_preds.argmax(axis=-1)
test['end'] = test_end_preds.argmax(axis=-1)
test['selected_text'] = test.apply(lambda x: decode(x['start'], x['end'], x['text'], config['question_size'], tokenizer), axis=1)
# Post-process
test["selected_text"] = test.apply(lambda x: ' '.join([word for word in x['selected_text'].split() if word in x['text'].split()]), axis=1)
test['selected_text'] = test.apply(lambda x: x['text'] if (x['selected_text'] == '') else x['selected_text'], axis=1)
test['selected_text'].fillna(test['text'], inplace=True)
###Output
_____no_output_____
###Markdown
Visualize predictions
###Code
test['text_len'] = test['text'].apply(lambda x : len(x))
test['label_len'] = test['selected_text'].apply(lambda x : len(x))
test['text_wordCnt'] = test['text'].apply(lambda x : len(x.split(' ')))
test['label_wordCnt'] = test['selected_text'].apply(lambda x : len(x.split(' ')))
test['text_tokenCnt'] = test['text'].apply(lambda x : len(tokenizer.encode(x).ids))
test['label_tokenCnt'] = test['selected_text'].apply(lambda x : len(tokenizer.encode(x).ids))
test['jaccard'] = test.apply(lambda x: jaccard(x['text'], x['selected_text']), axis=1)
display(test.head(10))
display(test.describe())
###Output
_____no_output_____
###Markdown
Test set predictions
###Code
submission = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/sample_submission.csv')
submission['selected_text'] = test['selected_text']
submission.to_csv('submission.csv', index=False)
submission.head(10)
###Output
_____no_output_____ |
management/Scratchpad 2020.06.26.ipynb | ###Markdown
Scratchpad 2020.06.26
###Code
import qcportal as ptl
import pandas as pd
import datetime
import time
from management import *
###Output
_____no_output_____
###Markdown
connect without auth read onlyclient = ptl.FractalClient()
###Code
# connect with authentication, therefore write access
# don't use unless you plan to submit things
client = ptl.FractalClient.from_file()
client
client.query_procedures('17477571')[0].get_error().error_message
client.query_procedures('18536988')[0].get_error().error_message
client.query_procedures('18536988')
###Output
_____no_output_____
###Markdown
From Trevor
###Code
import json
td_opts = '{"18045875": ["21139782"], "18045886": ["21234708", "21234712"], "18045948": ["18304746", "18305046", "18305452", "18305315", "18305401"], "18045967": ["18319507", "18319524"], "18536969": ["21230311"], "18886222": ["18888532"], "18886558": ["19194347", "19194344"], "18886565": ["19197486"], "18045715": ["21139587"], "18045716": ["21231948"], "18045852": ["21241161", "21241163", "21241164"], "18045879": ["21230833", "21230839"], "18045891": ["18234262", "18234267"], "18045896": ["21240215"], "18045901": ["21240741", "21240743", "21240744", "21240745", "21240747", "21240748", "21240749", "21240750", "21240752", "21240754", "21240756"], "18045902": ["21232696"], "18045909": ["21231115"], "18045910": ["21240553", "21240554"], "18045912": ["21229652", "21229654"], "18045913": ["21236552", "21236555"], "18045917": ["21236138"], "18045925": ["18283934", "18283946", "18283947", "18283955", "18283960", "18283963"], "18045929": ["18292370", "18292396"], "18045930": ["21240809", "21240811", "21240813"], "18045937": ["18298991", "18299039", "18299060"], "18045941": ["18301534"], "18045942": ["18301550", "18301552", "18301563", "18301579", "18301609", "18301610", "18301612", "18301648", "18301651", "18301652", "18301661", "18301666", "18301702", "18301705", "18301719", "18301720", "18301721", "18301722", "18301724", "18301727", "18301728", "18301730", "18301759", "18301821", "18301822", "18301825", "18301826"], "18045953": ["21232906"], "18045959": ["21236408", "21236412", "21236419"], "18045964": ["21240292", "21240294"], "18045965": ["21236073", "21236085"], "18045969": ["18319750", "18319751"], "18536127": ["21241319", "21241320"], "18537079": ["18893526"], "18537099": ["18819828"], "18885888": ["18885922", "18885924", "18885930", "18885931"], "18886355": ["19074332"], "18886560": ["19195427"]}'
td_opts = json.loads(td_opts)
td_opts
###Output
_____no_output_____ |
P0-chopstick-length/Data_Analyst_ND_Project0.ipynb | ###Markdown
Chopsticks!A few researchers set out to determine the optimal length of chopsticks for children and adults. They came up with a measure of how effective a pair of chopsticks performed, called the "Food Pinching Performance." The "Food Pinching Performance" was determined by counting the number of peanuts picked and placed in a cup (PPPC). An investigation for determining the optimum length of chopsticks.[Link to Abstract and Paper](http://www.ncbi.nlm.nih.gov/pubmed/15676839) *the abstract below was adapted from the link*Chopsticks are one of the most simple and popular hand tools ever invented by humans, but have not previously been investigated by [ergonomists](https://www.google.com/search?q=ergonomists). Two laboratory studies were conducted in this research, using a [randomised complete block design](http://dawg.utk.edu/glossary/whatis_rcbd.htm), to evaluate the effects of the length of the chopsticks on the food-serving performance of adults and children. Thirty-one male junior college students and 21 primary school pupils served as subjects for the experiment to test chopsticks lengths of 180, 210, 240, 270, 300, and 330 mm. The results showed that the food-pinching performance was significantly affected by the length of the chopsticks, and that chopsticks of about 240 and 180 mm long were optimal for adults and pupils, respectively. Based on these findings, the researchers suggested that families with children should provide both 240 and 180 mm long chopsticks. In addition, restaurants could provide 210 mm long chopsticks, considering the trade-offs between ergonomics and cost. For the rest of this project, answer all questions based only on the part of the experiment analyzing the thirty-one adult male college students.Download the [data set for the adults](https://www.udacity.com/api/nodes/4576183932/supplemental_media/chopstick-effectivenesscsv/download), then answer the following questions based on the abstract and the data set.**If you double click on this cell**, you will see the text change so that all of the formatting is removed. This allows you to edit this block of text. This block of text is written using [Markdown](http://daringfireball.net/projects/markdown/syntax), which is a way to format text using headers, links, italics, and many other options. You will learn more about Markdown later in the Nanodegree Program. Hit shift + enter or shift + return to show the formatted text. 1. What is the independent variable in the experiment?You can either double click on this cell to add your answer in this cell, or use the plus sign in the toolbar (Insert cell below) to add your answer in a new cell.Chopstick.Length 2. What is the dependent variable in the experiment?Food.Pinching.Efficiency 3. How is the dependent variable operationally defined?It's operationally defined as the "Food Pinching Performance" which was determined by counting the number of peanuts picked and placed in a cup (PPPC). 4. Based on the description of the experiment and the data set, list at least two variables that you know were controlled.Think about the participants who generated the data and what they have in common. You don't need to guess any variables or read the full paper to determine these variables. (For example, it seems plausible that the material of the chopsticks was held constant, but this is not stated in the abstract or data description.)The type of food that's used - peanutsThe type of container to pinch the peanuts into - cup One great advantage of ipython notebooks is that you can document your data analysis using code, add comments to the code, or even add blocks of text using Markdown. These notebooks allow you to collaborate with others and share your work. For now, let's see some code for doing statistics.
###Code
import pandas as pd
# pandas is a software library for data manipulation and analysis
# We commonly use shorter nicknames for certain packages. Pandas is often abbreviated to pd.
# hit shift + enter to run this cell or block of code
path = r'C:/Users/George/Dropbox/WorkingDir/Udacity/P0/chopstick-effectiveness.csv'
# Change the path to the location where the chopstick-effectiveness.csv file is located on your computer.
# If you get an error when running this block of code, be sure the chopstick-effectiveness.csv is located at the path on your computer.
dataFrame = pd.read_csv(path)
dataFrame
###Output
_____no_output_____
###Markdown
Let's do a basic statistical calculation on the data using code! Run the block of code below to calculate the average "Food Pinching Efficiency" for all 31 participants and all chopstick lengths.
###Code
dataFrame['Food.Pinching.Efficiency'].mean()
###Output
_____no_output_____
###Markdown
This number is helpful, but the number doesn't let us know which of the chopstick lengths performed best for the thirty-one male junior college students. Let's break down the data by chopstick length. The next block of code will generate the average "Food Pinching Effeciency" for each chopstick length. Run the block of code below.
###Code
meansByChopstickLength = dataFrame.groupby('Chopstick.Length')['Food.Pinching.Efficiency'].mean().reset_index()
meansByChopstickLength
# reset_index() changes Chopstick.Length from an index to column. Instead of the index being the length of the chopsticks, the index is the row numbers 0, 1, 2, 3, 4, 5.
###Output
_____no_output_____
###Markdown
5. Which chopstick length performed the best for the group of thirty-one male junior college students?240 mm
###Code
# Causes plots to display within the notebook rather than in a new window
%pylab inline
import matplotlib.pyplot as plt
plt.scatter(x=meansByChopstickLength['Chopstick.Length'], y=meansByChopstickLength['Food.Pinching.Efficiency'])
# title="")
plt.xlabel("Length in mm")
plt.ylabel("Efficiency in PPPC")
plt.title("Average Food Pinching Efficiency by Chopstick Length")
plt.show()
###Output
Populating the interactive namespace from numpy and matplotlib
|
Speech_to_Text_Demo_Streaming_Transcription.ipynb | ###Markdown
###Code
!apt install libasound2-dev portaudio19-dev libportaudio2 libportaudiocpp0 ffmpeg
!pip install deepspeech==0.8.2
!wget https://github.com/mozilla/DeepSpeech/releases/download/v0.8.2/deepspeech-0.8.2-models.pbmm
!wget https://github.com/mozilla/DeepSpeech/releases/download/v0.8.2/deepspeech-0.8.2-models.scorer
from deepspeech import Model
import numpy as np
import os
import wave
import json
from IPython.display import Audio
model_file_path = 'deepspeech-0.8.2-models.pbmm'
lm_file_path = 'deepspeech-0.8.2-models.scorer'
beam_width = 100
lm_alpha = 0.93
lm_beta = 1.18
model = Model(model_file_path)
model.enableExternalScorer(lm_file_path)
model.setScorerAlphaBeta(lm_alpha, lm_beta)
model.setBeamWidth(beam_width)
stream = model.createStream()
def read_wav_file(filename):
with wave.open(filename, 'rb') as w:
rate = w.getframerate()
frames = w.getnframes()
buffer = w.readframes(frames)
return buffer, rate
from IPython.display import clear_output
def transcribe_streaming(audio_file):
buffer, rate = read_wav_file(audio_file)
offset=0
batch_size=8196
text=''
while offset < len(buffer):
end_offset=offset+batch_size
chunk=buffer[offset:end_offset]
data16 = np.frombuffer(chunk, dtype=np.int16)
stream.feedAudioContent(data16)
text=stream.intermediateDecode()
#clear_output(wait=True)
print(text)
offset=end_offset
return True
!wget -O speech.wav https://github.com/EN10/DeepSpeech/blob/master/man1_wb.wav?raw=true
!ls
Audio('speech.wav')
transcribe_streaming('speech.wav')
###Output
_____no_output_____ |
_sources/curriculum-notebooks/Mathematics/IntervalsAndInequalities/intervals-and-inequalities.ipynb | ###Markdown

###Code
from IPython.display import display, Math, Latex, Markdown, HTML, clear_output, Javascript
HTML('''<script>
function code_toggle() {
if (code_shown){
$('div.input').hide();
$('#toggleButton').val('Show Code')
} else {
$('div.input').show();
$('#toggleButton').val('Hide Code')
}
code_shown = !code_shown
}
$( document ).ready(function(){
code_shown=false;
$('div.input').hide()
});
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form''')
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, Math, Latex, Markdown, HTML, clear_output, Javascript
import matplotlib as mpl
import ipywidgets as widgets
from ipywidgets import interact, interactive, Layout, Label,interact_manual,Text, HBox
from ipywidgets import IntSlider as slid
import time
import matplotlib.image as mpimg
from ipywidgets import IntSlider
###Output
_____no_output_____
###Markdown
Introduction In this notebook, we will review some basics about polynomial functions such as- the general form of a polynomial- what terms make up a polynomial- what defines the degree or order of a polynomialWe will then examine solving inequalities involving polynomials of degree 3 or less, both analytically and graphically, and briefly look over how to display the solutions on a number line, and how to represent solutions in interval notation. Finally, we will visualize how changing certain parameters of polynomials can change the shape of its graph, which results in a different interval, satisfying a given inequality.At the end of this notebook, there will be a small section covering some basics of `python` syntax and coding. This optional section will show the user how to create simple plots of polynomials in `python`, which can be used to help solve some of the extra problems. Polynomials A polynomial is a function comprised of constants and variables. The constants and variables can be related to each other by addition, multiplication and exponentiation to a non-negative integer power ( https://en.wikipedia.org/wiki/Polynomial ). In this notebook, we will let $P(x)$ denote a general polynomial, and we will only deal with polynomials of a single variable $x$. In general, a polynomial is expressed as:$P(x) = c_0 \, + \,c_1x \, + ... +\, c_{n-2}x^{n-2} + c_{n-1}x^{n-1} + c_nx^n = \sum^n_{k=0}c_kx^k$where $c_k$ are *constant terms*, $x$ is the variable. The largest value of $n$ ( i.e. the largest exponent of the polynomial) determines the *degree* of the polynomial. For example, some polynomials of degree *three* ($n=3$) could be:$P(x) = x^3 + 2x^2 + 5x + 4$$P(x) = 3x^3 + 8x $$P(x) = x^3 + x^2 + 4$Note how the number of terms **does not** affect the degree of the polynomial, only the value of the largest exponent does. A polynomial with degree 0 is called a *constant polynomial*, or just a *constant*. This is because of the mathematical identity$x^0 = 1$,so if we have any polynomail of degree 0, we have$P(x) = c_1x^0 + c_2 = c_1 + c_2 = C$,which of course is just a constant (i.e. some number, $C$).While we will only be dealing with singe variable polynomials, it is worth noting that they can exist with *multiple variables*, i.e.$P(x,y,z) = x^3 - xy^2 + z^6 -3x^2y^6z^4 +2$
###Code
#display(Latex('...')) will print the string in the output cell, in a nice font, and allows for easily inputing Math symbos and equations
display(Latex('From the list of functions below, check which ones are polynomials:'))
#define a series of checkboxes to test knowledge of polynomial forms
style = {'description_width': 'initial'}
a=widgets.Checkbox(
# description= '$\ x^2+5x-8x^3$',
description= r'$x^2$'+r'$+5x$'+r'$-8x^3$',
value=False, #a false value means unchecked, while a checked value will be "True'"
style = style
)
b=widgets.Checkbox(
value=False,
description=r'$x$'+r'$+3$',
# description=r'$\ x+3$',
style = style
)
c=widgets.Checkbox(
value=False,
# description=r'$\ \sin(x) + \cos(x)$',
description=r'$\sin$'+'('+r'$x$'+')'+r'$+\cos$'+'('+r'$x$'+')',
style = style
)
d=widgets.Checkbox(
value=False,
# description=r'$\ x^5-2$',
description=r'$x^5$'+r'$-2$',
disabled=False,
style = style
)
e=widgets.Checkbox(
value=False,
# description=r'$\ \ln(x)$',
description=r'$\ln$'+r'$(x)$',
disabled=False,
style = style
)
f=widgets.Checkbox(
value=False,
# description= r'$\ 100$',
description= r'$100$',
disabled=False,
style = style
)
#to actually display the buttons, we need to use the IPython.display package, and call each button as the argument
display(a,b,c,d,e,f)
#warning
text_warning = widgets.HTML()
#create a button widget to check answers, again calling the button to display
button_check = widgets.Button(description="Check Answer")
display(button_check)
#a simple funciton to determine if user inputs are correct
def check_button(x):
if a.value==True and b.value==True and c.value==False and d.value==True and e.value==False and f.value==True: #notebook will display 'correct' message IF (and only if) each of the boxes satisfy these value conditions
text_warning.value="Correct - these are all polynomials! Let's move on to the next cell."
else: #if any of the checkboxes have the incorrect value, output will ask user to try again
text_warning.value="Not quite - either some of your selections aren't polynomials, or some of the options that you didn't select are. Check your answers again!"
button_check.on_click(check_button)
display(text_warning)
###Output
_____no_output_____
###Markdown
Intervals of Inequalities Interval Notation Interval notation is a way of representing an interval of numbers by the two endpoints of the interval. Parentheses ( ) and brackets [ ] are used to represent whether the end points are included in the interval or not. For example, consider the interval between $-3$ and $4$, including $-3$, but **not** including $4$, i.e. $-3 \leq x < 4$. We can represent this on a number line as follows:In **interval notation**, we would simply write: $[-3,4)$If, however, the interval extended from $-3$ to **all** real numbers larger than $-3$, i.e. $-3 \leq x$, the number line would look like this:and our interval notation representation would be: $[-3, \infty)$, where $\infty$ (infinity) essentially means all possible numbers beyond this point.Sometimes it is also necessary to include multiple intervals. Consider an inequality in which the solution is $-3\leq x <0$ and $4 \leq x$. We can represent this solution in interval notation with the **union** symbol, which is just a capital U, and means that both intervals satisfy the inequality: $[-3,0)$ U $[4,\infty)$ Solving Inequalities Given a polynomial $P(x)$, we can determine the range in which that polynomial satisfies a certain inequality. For example, consider the polynomial function$P(x) = x^2 + 4x$.For which values of $x$ is the ploynomial $P(x)$ less than three? Or, in a mathematical representations, on which interval is the inequality $P(x) \leq -3$ satisfied?We can solve this algebraically, as follows:1. Write the polynomial in standard form: $x^2 + 4x + 3 \leq 0 $ 2. Factor the polynomial: $(x+1)(x+3) \leq 0$What this new expression is essential telling us is that the product of two numbers (say $a=(x+1)$ and $b=(x+3)$) is equal to zero, or negative, i.e. $a\cdot b\leq 0 $. The only way this is possible is if $a=0$, $b=0$, or $a$ and $b$ have **opposite** signs. So the inequality $P(x) \leq -3$ is satisfied if:- $(x+1) = 0$- $(x+3) = 0$- $(x+1)>0$ and $(x+3)<0$- $(x+1)0$From these possibilities, we can see the possible solutions are:- $x=-1$- $x=-3$- $x>-1$ and $x<-3$- $x-3$ If we consider the solution $x>-1$ and $x0$ and $(x+3)<0$, so we can eliminate this as a possible solution.However, we can find values of $x$ that satisfy $x-3$. For example, $x=-2$Thus, the solution to the inequality is $x=-1$, $x=-3$, and $x-3$. We can plot this solution set on a number line:or in *interval notation*, the solution is : **[-3,-1]** Let's work through an example together
###Code
std_form1 = "-4x^2+8x+96<=0"
display(Latex('1.Consider the inequality $(-x)(4x - 8) \leq -96$.'))
display(Latex(' Re-write the inequality in standard form (use the symbol ^ to indicate an exponent and <= for the inequality sign).'))
inpt1 = widgets.Text(placeholder='Enter inequality')
text_warning1 = widgets.HTML()
button_check1 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt1,button_check1]))
def check_button1(x):
inpt1.value = inpt1.value.replace(" ","")
if inpt1.value==std_form1 :
text_warning1.value="Very good!"
else:
text_warning1.value="Not quite - please try again!"
button_check1.on_click(check_button1)
display(text_warning1)
std_form2 = "x^2-2x-24>=0"
display(Latex('2.Consider the inequality we obtained in the first step.'))#: $-4x^2+8x+96\leq0$'))
display(Latex('We can simplify this further by reducing the leading coefficient to 1.'))
display(Latex('This can be done by simply dividing both sides by $-4$. If we do this, what does our expression become?'))
inpt2 = widgets.Text(placeholder='Enter inequality')
text_warning2 = widgets.HTML()
button_check2 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt2,button_check2]))
def check_button2(x):
inpt2.value = inpt2.value.replace(" ","")
if inpt2.value==std_form2 :
text_warning2.value="Very good!"
else:
text_warning2.value="Almost! It's important to remember that if we divide or multiply an inequality by a negative number, we flip the inequality sign."
button_check2.on_click(check_button2)
display(text_warning2)
std_form3_1 = '(x-6)(x+4)>=0'
std_form3_2 = '(x+4)(x-6)>=0'
display(Latex('3.The next step is to factor our simplified polynomial expression.')) #: $x^2 - 2x - 24 \geq 0$.'))
display(Latex('Input the factored expression below:'))
inpt3 = widgets.Text(placeholder='Enter inequality')
text_warning3 = widgets.HTML()
button_check3 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt3,button_check3]))
def check_button3(x):
inpt3.value = inpt3.value.replace(" ","")
if inpt3.value==std_form3_1 or inpt3.value==std_form3_2:
text_warning3.value="Correct!"
else:
text_warning3.value="Not quite - please try again!"
button_check3.on_click(check_button3)
display(text_warning3)
display(Latex('Since we have $(x-6)(x+4)\geq 0$, there are the two sign possibilities; either'))
display(Latex('$1. ~ (x-6)\geq 0$ and $(x+4)\geq 0$'))
display(Latex('or'))
display(Latex('$2. ~ (x-6)\leq 0$ and $(x+4)\leq 0$'))
std_form4 = 'x>=6'
display(Latex('4. Consider expression $1.$'))
display(Latex(' Can you see what solution satisfies both $(x-6)\geq 0$ and $(x+4)\geq 0$? Enter your answer below in the form "x>= _"'))
inpt4 = widgets.Text(placeholder='Enter interval')
text_warning4 = widgets.HTML()
button_check4 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt4,button_check4]))
def check_button4(x):
inpt4.value = inpt4.value.replace(" ","")
if inpt4.value==std_form4 :
text_warning4.value="Very good! Since we are looking for values of x that are larger than 6 and -4, and 6>-4, the first expresssion gives us one simple solution interval: x>=6"
else:
text_warning4.value="Not quite - please try again!"
button_check4.on_click(check_button4)
display(text_warning4)
std_form5 = 'x<=-4'
display(Latex('5.Now consider expression $2$ What is the interval satsfying these inequalities?'))
inpt5 = widgets.Text(placeholder='Enter interval')
text_warning5 = widgets.HTML()
button_check5 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt5,button_check5]))
def check_button5(x):
inpt5.value = inpt5.value.replace(" ","")
if inpt5.value==std_form5 :
text_warning5.value="Very good! Since we are looking for values of x that are less than -4 and 6 and 6>-4, this expresssion also gives us one simple solution interval: x<=-4"
else:
text_warning5.value="Not quite - please try again!"
button_check5.on_click(check_button5)
display(text_warning5)
std_form6 = '(-inf,-4]U[6,inf)'
display(Latex('6. So, what is our final solution interval for the inequality $(-x)(4x - 8) \leq -96$?'))
display(Latex("Enter your answer in interval notation, using the following notations if necessary: 'U' for union symbol and 'inf' for infinity"))
inpt6 = widgets.Text(placeholder='Enter interval')
text_warning6 = widgets.HTML()
button_check6 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt6,button_check6]))
def check_button6(x):
inpt6.value = inpt6.value.replace(" ","")
if inpt6.value==std_form6 :
text_warning6.value="Excellent! Now let's see how the solution looks like on the number line"
else:
text_warning6.value="Not quite - please try again!"
button_check6.on_click(check_button6)
display(text_warning6)
button7 = widgets.Button(description="Display solution on a number line",layout=Layout(width='40%', height='50px'))
display(button7)
def display_button7(x):
img = mpimg.imread('images/ex_soln.png')
fig, ax = plt.subplots(figsize=(18, 3))
imgplot = ax.imshow(img, aspect='auto')
ax.axis('off')
plt.show()
button7.disabled=True
button7.on_click(display_button7)
###Output
_____no_output_____
###Markdown
Graphical visualization of inequality solutions
###Code
%matplotlib inline
display(Latex('Click on the button below to graph the polynomial $P(x) = x^2 + 4x$'))
button_graph = widgets.Button(description="Graph the ploynomial")
display(button_graph)
def display_graph(t):
x = np.linspace(-10,10,1000); #define a vector space for the variable x
plt.figure(3,figsize=(11,8)) #define the figure window size
plt.plot(x,x**2 + 4*x, linewidth=2, label=r'$P(x) = x^2 + 4x$'); #plot the polynomial as a function of x
plt.ylabel('P(x)', fontsize=20) #label the axes
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7) #place a grid on the figure for readability; alpha defines the opacity
plt.xticks(np.arange(-10,11)) #define the xticks for easier reading
plt.ylim([-20,40]) #adjust the limits of the y and x axes of the figure for readability
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1) #plot solid lines along origin for easier reading
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.legend(loc='best', fontsize = 18) #add a legend
button_graph.disabled=True
button_graph.on_click(display_graph)
display(Latex("Let's try to solve where this polynomial is $\leq -3$, or $x^2 + 4x \leq -3$."))
display(Latex("Let's draw a line at $y=-3$ to help visualize this."))
button_draw = widgets.Button(description="Draw a line")
display(button_draw)
def draw_line(t):
x = np.linspace(-10,10,1000); #define a vector space for the variable x
plt.figure(3,figsize=(11,8)) #define the figure window size
plt.plot(x,x**2 + 4*x, linewidth=2, label=r'$P(x) = x^2 + 4x$'); #plot the polynomial as a function of x
plt.ylabel('P(x)', fontsize=20) #label the axes
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7) #place a grid on the figure for readability; alpha defines the opacity
plt.xticks(np.arange(-10,11)) #define the xticks for easier reading
plt.ylim([-20,40]) #adjust the limits of the y and x axes of the figure for readability
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1) #plot solid lines along origin for easier reading
plt.plot(x,np.ones(len(x))*-3, linewidth=2, label = r'$y = -3$'); #plot the y=0 line
plt.legend(loc='best', fontsize = 18) #add a legend
button_draw.disabled=True
button_draw.on_click(draw_line)
display(Latex('Can you see where the inequality is satisfied?'))
display(Latex('Click the button to shade the area where the inequality is satisfied'))
button_shade = widgets.Button(description="Shade")
display(button_shade)
def shade(t):
x = np.linspace(-10,10,1000); #define a vector space for the variable x
plt.figure(3,figsize=(11,8)) #define the figure window size
plt.plot(x,x**2 + 4*x, linewidth=2, label=r'$P(x) = x^2 + 4x$'); #plot the polynomial as a function of x
plt.ylabel('P(x)', fontsize=20) #label the axes
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7) #place a grid on the figure for readability; alpha defines the opacity
plt.xticks(np.arange(-10,11)) #define the xticks for easier reading
plt.ylim([-20,40]) #adjust the limits of the y and x axes of the figure for readability
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1) #plot solid lines along origin for easier reading
plt.plot(x,np.ones(len(x))*-3, linewidth=2, label = r'$y = -3$'); #plot the y=0 line
plt.legend(loc='best', fontsize = 18) #add a legend
plt.axvspan(-3,-1,facecolor='#2ca02c', alpha=0.5)
display(Latex("We can see that the interval for which $P(x) \leq -3$ is again [-3,-1], agreeing with our algebraic solution."))
button_shade.disabled=True
button_shade.on_click(shade)
###Output
_____no_output_____
###Markdown
Changing Parameters Constant term The **constant term** of a polynomial is the term in which the variable does not appear (i.e. the degree $0$ term). For example, the constant term for the polynomial $P(x) = x^3 + 2x^2 + 5x + 4$,is $4$.Let's look at how changing the constant term changes the graph of the polynomial. We will consider the same polynomial as before, but this time we will let $k$ be an arbitrary value for the constant term.
###Code
display(Latex('Adjust the value of $k$ using the slider. What do you notice about the graph as the value changes?'))
x = np.linspace(-10,10, 1000)
#define function to create a graph of a polynomial
def Plot_poly(k=0): #we make the python function a function of the variable 'k', which we will use as the constant term in the polynomial
plt.figure(figsize=(11,8))
plt.plot(x,x**3 + 2*x**2 + 5*x + k, linewidth = 2) #here is the variable k
plt.title(r'Graph of $P(x) = x^3 + 2x^2 + 5x + k$', fontsize = 20)
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.show()
#interact(Plot_poly,k=(-10,10)); #use the IPython interact function to create a slider to adjust the value of 'k' for the plot
interact(Plot_poly, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
#interact_manual(Plot_poly,k=widgets.IntSlider(min=-10,max=10,step=1,value=0))
display(Latex('Try doing the same with other polynomials. Is there a similar, or different behaviour?'))
display(Markdown('**Order 1 Polynomials:**'))
display(Latex('Provide a value for $a$ in the polynomial $P(x) = ax + k$:'))
inpt_a = widgets.Text(placeholder='Enter a')
text_warning_a = widgets.HTML()
button_check_a = widgets.Button(description="Graph")
display(widgets.HBox([inpt_a,button_check_a]))
button_check_a.disabled=False
inpt_a.disabled=False
def check_button_a(b):
inpt_a.value = inpt_a.value.replace(" ","")
if inpt_a.value.isdigit():
text_warning_a.value=""
button_check_a.disabled=True
inpt_a.disabled=True
x = np.linspace(-10,10,1000)
custom_poly = int(inpt_a.value)* x
def plot_poly1(k=0):
plt.figure(figsize=(11,8))
plt.plot(x,custom_poly + k, linewidth=2) #plot the polynomial with the constant term k
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.title('Graph of polynomial $P(x) ='+str(inpt_a.value) + 'x+ k$', fontsize=20)
plt.show()
#interact(plot_poly1,k=(-10,10));
interact(plot_poly1, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
else:
text_warning_a.value="Please enter numeric value"
button_check_a.on_click(check_button_a)
display(text_warning_a)
display(Markdown('**Order 2 Polynomials:**'))
display(Latex('Provide values for $a$ and $b$ in the polynomial $P(x) = ax^2 +bx + k$ using format a,b:'))
inpt_ab = widgets.Text(placeholder='Enter a,b')
text_warning_ab = widgets.HTML()
button_check_ab = widgets.Button(description="Graph")
display(widgets.HBox([inpt_ab,button_check_ab]))
button_check_ab.disabled=False
inpt_ab.disabled=False
def check_button_ab(b):
inpt_ab.value = inpt_ab.value.replace(" ","")
list_ab = inpt_ab.value.split(',')
if not len(list_ab)==2:
text_warning_ab.value="Please enter two numbers in format a,b"
else:
if list_ab[0].isdigit() and list_ab[1].isdigit():
text_warning_ab.value=""
button_check_ab.disabled=True
inpt_ab.disabled=True
x = np.linspace(-10,10,1000)
custom_poly = int(list_ab[0]) * x**2 + int(list_ab[1])*x
def plot_poly2(k=0):
plt.figure(figsize=(11,8))
plt.plot(x,custom_poly + k, linewidth=2) #plot the polynomial with the constant term k
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.title('Graph of polynomial $P(x) ='+str(list_ab[0]) + 'x^2 +' + str(list_ab[1]) + 'x + k$', fontsize=20)
plt.show()
#interact(plot_poly2,k=(-10,10))
interact(plot_poly2, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
else:
text_warning_ab.value="Please enter numeric values"
button_check_ab.on_click(check_button_ab)
display(text_warning_ab)
display(Markdown('**Order 3 Polynomials:**'))
display(Latex('Provide values for $a$, $b$, and $c$ in the polynomial $P(x) = ax^3 +bx^2 + cx + k$ using format a,b,c:'))
inpt_abc = widgets.Text(placeholder='Enter a,b,c')
text_warning_abc = widgets.HTML()
button_check_abc = widgets.Button(description="Graph")
display(widgets.HBox([inpt_abc,button_check_abc]))
button_check_abc.disabled=False
inpt_abc.disabled=False
def check_button_abc(b):
inpt_abc.value = inpt_abc.value.replace(" ","")
list_abc = inpt_abc.value.split(',')
if not len(list_abc)==3:
text_warning_abc.value="Please enter three numbers in format a,b,c"
else:
if list_abc[0].isdigit() and list_abc[1].isdigit() and list_abc[2].isdigit():
text_warning_abc.value=""
button_check_abc.disabled=True
inpt_abc.disabled=True
x = np.linspace(-10,10,1000)
custom_poly = int(list_abc[0]) * x**3 + int(list_abc[1])*x**2 + int(list_abc[2])*x
def plot_poly3(k=0):
plt.figure(figsize=(11,8))
plt.plot(x,custom_poly + k, linewidth=2) #plot the polynomial with the constant term k
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.title('Graph of polynomial $P(x) ='+str(list_abc[0]) + 'x^3 +' + str(list_abc[1]) + 'x^2+'+ str(list_abc[2]) + 'x+ k$', fontsize=20)
plt.show()
#interact(plot_poly3,k=(-10,10));
interact(plot_poly3, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
else:
text_warning_abc.value="Please enter numeric values"
button_check_abc.on_click(check_button_abc)
display(text_warning_abc)
###Output
_____no_output_____
###Markdown
In the next exercise, we will quantify how the constant term can change the interval satisfying an inequality. **Note**: Please press the enter key after typing in a value for the intercepts.
###Code
display(Latex("Where are the x intercepts for the polynomial $x^2-4x+3$?"))
#widgets for interactive cell input
guess1_in= widgets.Text(disabled = False, description = r'$x_1$')
guess2_in = widgets.Text(disabled = False, description = r'$x_2$')
check = widgets.Button(description = 'Check Answer')
change_c = widgets.Button(description = 'Change Constant')
text_warning_check = widgets.HTML()
display(guess1_in)
display(guess2_in)
display(check)
def check_answr(b):
int_1 = str(1)
int_2 = str(3)
if (guess1_in.value == int_1 and guess2_in.value == int_2) or (guess1_in.value == int_2 and guess2_in.value == int_1):
text_warning_check.value='Correct!'
check.disabled=True
guess1_in.disabled=True
guess2_in.disabled=True
plt.figure(1,figsize=(11,8))
plt.plot(x,x**2 - 4*x + 3, linewidth=2, label=r'$P(x) = x^2 -4x+3$');
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.plot(3,0,'ro',markersize=10)
plt.plot(1,0,'ro',markersize=10)
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,20])
plt.xlim([-9,9])
plt.legend(loc='best', fontsize = 18)
plt.show()
display(Latex('Based on the previous cell, what do you think will happen if we change the constant term from $3$ to $-3$? Press the button to find out if you are correct.'))
display(change_c)
else:
text_warning_check.value='Try Again!'
return
check.on_click(check_answr)
def change_const(b):
change_c.disabled=True
plt.figure(1,figsize=(11,8))
plt.plot(x,x**2 - 4*x - 3, linewidth=2, label=r'$P(x) = x^2 -4x-3$');
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.plot(2-np.sqrt(7),0,'yo',markersize=10)
plt.plot(2+np.sqrt(7),0,'yo', markersize=10)
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,20])
plt.xlim([-9,9])
plt.legend(loc='best', fontsize = 18)
plt.show()
display(Latex('As we can see, changing the constant term shifts the graph of a polynomial up or down. This results in different x-intercepts, and therefore a different interval. '))
change_c.on_click(change_const)
display(text_warning_check)
###Output
_____no_output_____
###Markdown
Another way to think about this is that changing the constant term is the same as solving for a different interval of inequality. Take, for example the polynomials we just used above.We know that $x^2-4x+3 \leq 0$ is **not** the same as $x^2-4x-3\leq 0$.However, consider a new inequality:$x^2 - 4x - 3 \leq -6$.If we simplify this expression, we find$x^2 - 4x +3 \leq 0$which is indeed equivalent to the first polynomial (plotted in blue in the cell above). Extra Problems Practice solving graphically First, we will practice how to solve inequalities graphically. Below is a plot of the polynomial $P(x) = x^3 - x^2 - 22x + 40$. Using the graph, find the values of the three x intercepts. Based on this, determine the interval where $P(x) \leq 0 $.This can method can be used to solve almost any polynomial inequality, provided that the x-intercepts are rational numbers which can be easily read off of the axes of the graph.
###Code
text_check_intvl = widgets.HTML()
intvl_1=widgets.Checkbox(
value=False,
description=r'$[$'+r'$-5$'+r'$,4$'+r'$]$',
disabled=False
)
intvl_2=widgets.Checkbox(
value=False,
description='['+'$-5$'+'$,3$'+']'+'$U$'+'['+r'$4,$'+r'$\infty$'+r')',
disabled=False
)
intvl_3=widgets.Checkbox(
value=False,
description=r'$[$'+r'$-5$'+r'$,2$'+r'$]$',
disabled=False
)
intvl_4=widgets.Checkbox(
value=False,
description=r'$($'+r'$-\infty$'+r'$,$'+r'$-5$'+'$]$'+'$U$'+ r'$[$' + r'$2$'+'$,$'+'$4$'+'$]$',
#description=r'$(-\infty,-5] \rm U [2,4]$',
disabled=False
)
def check_button2(x):
if intvl_2.value == False and intvl_1.value==False and intvl_3.value==False and intvl_4.value==True:
text_check_intvl.value='Correct!'
else:
text_check_intvl.value="Not quite - Check your answer again!"
button_check2 = widgets.Button(description="Check Answer")
button_check2.on_click(check_button2)
def slider(x1,x2,x3):
xx = np.linspace(-10,10,300)
p1 = plt.figure(1,figsize = (11,8))
hold = True
plt.plot(xx,xx**3 - 1*xx**2 - 22*xx + 40, linewidth = 2, label = r'$P(x) = x^3 - x^2 - 22x + 40$')
plt.axhline(y=0, color = 'k', linewidth=1)
plt.axvline(x=0, color = 'k', linewidth=1)
plt.plot(x1,0,'ro',markersize=10)
plt.plot(x2,0,'mo',markersize=10)
plt.plot(x3,0,'go',markersize=10)
if sorted([x1,x2,x3]) == sorted([-5,2,4]):
plt.text(-7,20,'VERY GOOD!', fontsize = 25, fontweight = 'bold',color = 'r')
plt.fill_between(xx,xx**3 - 1*xx**2 - 22*xx + 40,np.zeros(len(xx)), where=xx**3 - 1*xx**2 - 22*xx + 40<0, interpolate = True, alpha=0.5, color='g' )
display(Latex('What interval then satisfies $P(x) \leq 0$?'))
display(intvl_1)
display(intvl_2)
display(intvl_3)
display(intvl_4)
display(button_check2)
display(text_check_intvl)
plt.xlabel('$x$',fontsize = 14)
plt.ylabel('$y$',fontsize = 14)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-75,75])
plt.xlim([-9,9])
plt.legend(loc = 'best', fontsize = 18)
plt.show()
interact(slider, x1=slid(min = -10,max = 10,step = 1,continuous_update = False), x2=slid(min = -10,max = 10,step = 1,continuous_update = False), x3=slid(min = -10,max = 10,step = 1,continuous_update = False))
###Output
_____no_output_____
###Markdown
Solve the inequalities In the next two cells, we have a function that will generate a random polynomial of degree 2 and 3. Using the analytic steps shown above, try to solve the intervals of inequalities for a few polynomials. Since we can always rearrange the polynomial into standard form, without loss of generality we can always take the inequality to be $\leq 0 $ or $\geq 0 $. Re-run this function as many times as you would like, until you are comfortable with solving polynomial inequalities.If you have trouble solving the inequality analytically, you can try to find the solution graphically, following the method in the cell above. At the bottom of this notebook, there will be some instructions on how to make basic plots with Python. Follow these steps and try to solve the inequality.**Note**: you will need to scroll to the top of the notebook and press the '**show code**' button to be able to write your own code in a cell.
###Code
def find_interval2():
C = np.random.randint(-5,5,2)
C1 = -1*np.sum(C)
C2 = C[0]*C[1]
if C1>0:
str1 = '+' + str(C1) + 'x'
elif C1== 0:
str1 = ''
else:
str1= str(C1) + 'x'
if C2>0:
str2 = '+' + str(C2)
elif C2== 0:
str2=''
else:
str2= str(C2)
a = 'P(x) = x^2 ' + str1 + str2
def poly(x):
return x**2 + C1*x + C2
Max = max(C)
Min = min(C)
M = [Min, Max]
V = np.sort(C)
eps = 0.1
if Max == Min and poly(Max+eps)>0:
interval = '(-inf,'+str(Min)+')U('+str(Min)+',inf)' #one root, convex
elif poly(Max+eps)<0:
interval = '('+str(Min)+','+str(Max)+')' #Two distinct roots, Concave
elif poly(Max + eps)>0:
interval = '(-inf,'+str(Min)+')U(' + str(Max)+',inf)' #Two distinct roots, convex
else:
interval = 'Nowhere' #one root, concave
x = np.linspace(-100,100,10000)
p = poly(x)
y = poly(x)
return interval,y,a
def find_interval3():
C = np.random.randint(-5,5,3)
C1 = -1*np.sum(C)
C2 = C[0]*C[1] + C[2]*(C[0]+C[1])
C3 = -1*C[0]*C[1]*C[2]
if C1>0:
str1 = '+' + str(C1) + 'x^2'
elif C1== 0:
str1 = ''
else:
str1= str(C1) + 'x^2'
if C2>0:
str2 = '+' + str(C2) + 'x'
elif C2== 0:
str2=''
else:
str2= str(C2) + 'x'
if C3>0:
str3 = '+' + str(C3)
elif C3== 0:
str3=''
else:
str3= str(C3)
a = "P(x)= x^3" + str1 + str2 + str3
def poly(x):
return x**3 + C1*x**2 + C2*x + C3
Max = max(C)
Min = min(C)
M = [Min, Max]
V = np.sort(C)
eps = 0.1
v = V[1]
if Max == Min and poly(Max +eps) > 0:
interval = '('+str(Max)+',inf)' #One single root, increasing
if Max == Min and poly(Max +eps) < 0:
interval = '(-inf,' + str( Max)+')' #One single root, decreasing
if poly(Max + eps) >0:
if v != Max and v!= Min:
interval = '('+str(Min) + ',' + str(v) + ')U(' + str(Max) + ',inf)'
if v == Max:
interval = '(' + str(Min) + ',inf)'
if v== Min:
interval = '(' + str(Max) + ',inf)'
if poly(Max + eps) <0:
if v != Max and v != Min:
interval = '(-inf,' + str(Min) + 'U('+str(v) + ','+str(Max) + ')'
if v == Max:
interval = '(-inf,' + str( Max) + ')'
if v == Min:
interval = '(-inf,' + str(Min) + ')'
x = np.linspace(-100,100,10000)
y = poly(x)
return interval, y,a
def check_answer(answer,interval,y,a,hwidget):
if answer == interval:
hwidget.value="Correct! Here's a visualization of the solution:"
x=np.linspace(-100,100,10000)
plt.figure(figsize=(11,8))
plt.plot(x,y, linewidth = 2, label = '$' + str(a) + '$')
plt.xlabel('$x$',fontsize = 14)
plt.ylabel('$y$',fontsize = 14)
plt.axhline(y=0, color = 'k', linewidth=1)
plt.axvline(x=0, color = 'k', linewidth=1)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-75,75])
plt.xlim([-9,9])
plt.legend(loc = 'best', fontsize = 18)
plt.fill_between(x,y,0, where=y>0, interpolate=True, alpha = 0.5, color='g')
return True
elif answer != interval:
hwidget.value="That's not quite right, try again."
return False
interval2,y_values2,polynom_string2=find_interval2()
display(Markdown('**Order 2 Polynomials:**'))
display(Latex("Find the interval where $P(x) > 0$ , using 'inf' for infinity and 'U' for union:"))
display(Math(polynom_string2))
text_poly2 = widgets.Text(placeholder='Enter Interval')
display(text_poly2)
gen_button2 = widgets.Button(description="Re-generate polynomial", layout = Layout(width='30%', height='40px'))
check_button2 = widgets.Button(description="Check your answer", layout = Layout(width='30%', height='40px'),visible=False)
display(widgets.HBox([check_button2,gen_button2]))
text_check_ans2 = widgets.HTML()
display(text_check_ans2)
def generate_polynomial2(b):
display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index(), IPython.notebook.get_selected_index()+1)'))
gen_button2.on_click(generate_polynomial2)
def check_answer2(b):
text_poly2.value = text_poly2.value.replace(" ","")
result=check_answer(text_poly2.value,interval2,y_values2,polynom_string2,text_check_ans2)
if result:
check_button2.disabled=True
check_button2.on_click(check_answer2)
interval3,y_values3,polynom_string3=find_interval3()
display(Markdown('**Order 3 Polynomials:**'))
display(Latex("Find the interval where $P(x) > 0$ , using 'inf' for infinity and 'U' for union:"))
display(Math(polynom_string3))
text_poly3 = widgets.Text(placeholder='Enter Interval')
display(text_poly3)
gen_button3 = widgets.Button(description="Re-generate polynomial", layout = Layout(width='30%', height='40px'))
check_button3 = widgets.Button(description="Check your answer", layout = Layout(width='30%', height='40px'),visible=False)
display(widgets.HBox([check_button3,gen_button3]))
text_check_ans3 = widgets.HTML()
display(text_check_ans3)
def generate_polynomial3(b):
display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index(), IPython.notebook.get_selected_index()+1)'))
gen_button3.on_click(generate_polynomial3)
def check_answer3(b):
text_poly3.value = text_poly3.value.replace(" ","")
result=check_answer(text_poly3.value,interval3,y_values3,polynom_string3,text_check_ans3)
if result:
check_button3.disabled=True
check_button3.on_click(check_answer3)
###Output
_____no_output_____ |
06_Convolution/Student/01_Convolution/.ipynb_checkpoints/Convolution_Student-checkpoint.ipynb | ###Markdown
ConvolutionConvolution is a mathematical way of combining two signals to form a third signal. It is the single most important technique in Digital Signal Processing. Using the strategy of impulse decomposition, systems are described by a signal called the impulse response. Convolution is important because it relates the three signals of interest: the input signal, the output signal, and the impulse response. This chapter presents 1D and 2D convolution. For 1D convolution two different viewpoints, called the **input side algorithm** and the **output side algorithm**. are shown, then a vectorized implementation is presented. For 2D convolution a vectorized form is presented applied to image processing. 1D ConvolutionThe mathematical form of the convolution is:$$ y[i] = \sum_{j=0}^{M-1}{x[j]h[i-j]} $$ To develop the convolution we define the following: * Input Signal $x[n]$ of size $N$ * Impulse Response $h[n]$ of size $M$* Output Signal $y[n]$ of size $N + M -1$There are two types of algorithms that can be performed:1. Output Side Algorithm2. Input Side Algorithm 1. Output Side AlgorithmAnalyzes how each sample in the input signal affects many samples in the output signal. (We sum the contributions of each input to every output sample.)The algorithm calculates the convolution in the following way:$$y[i+j] = \sum_{i=0}^{N-1} \sum_{j=0}^{M-1}{x[i]h[j]}$$ where $M$ is the length of the impulse response and $N$ the input signal size and $y[n]$ has a size of $M+N-1$.The following picture describes the algorithm:
###Code
import sys
sys.path.insert(0, '../../../')
import numpy as np
import matplotlib.pyplot as plt
from Common import common_plots
cplots = common_plots.Plot()
file = {'x':'Signals/InputSignal_f32_1kHz_15kHz.dat', 'h':'Signals/Impulse_response.dat'}
x = np.loadtxt(file['x'])
N,M = x.shape
x = x.reshape(N*M, 1)
h = np.loadtxt(file['h'])
N = h.shape[0]
h = h.reshape(N, 1)
def convolve_output_algorithm(x, h):
"""
Function that convolves an input signal x with an step response h using the output side algorithm.
Parameters:
x (numpy array): Array of numbers representing the input signal to be convolved.
h (numpy array): Array of numbers representing the unit step response of a filter.
Returns:
numpy array: Returns convolved signal y[n]=h[n]*x[n].
"""
#SOLVE IN HERE
pass
output = convolve_output_algorithm(x, h)
cplots.plot_three_signals(x, h, output,
titles=('Input Signal', 'Impulse Response', 'Output Signal, Output Side Algorithm'))
###Output
_____no_output_____
###Markdown
2. Input Side AlgorithmWe look at individual samples in the output signal and find the contributing points from the input. (We find who contributed to the output.)The algorithm calculates the convolution in the following way:[//]: $$y[i] = \sum_{i=0}^{M+N-1} \sum_{j=0}^{M-1}{h[j]x[i-j]}$$ $$y[i] = \sum_{j=0}^{M-1}{h[j]x[i-j]}$$ if $$i-j>0 $$ and $$i-j<N-1$$where $M$ is the length of the impulse response and $N$ the input signal size and $y[n]$ has a size of $M+N-1$.The following picture describes the algorithm:
###Code
def convolve_input_algorithm(x, h):
"""
Function that convolves an input signal x with an step response h using the input side algorithm.
Parameters:
x (numpy array): Array of numbers representing the input signal to be convolved.
h (numpy array): Array of numbers representing the unit step response of a filter.
Returns:
numpy array: Returns convolved signal y[n]=h[n]*x[n].
"""
#SOLVE IN HERE
pass
output_ = convolve_input_algorithm(x, h)
cplots.plot_three_signals(x, h, output_[0:320])
###Output
_____no_output_____
###Markdown
Comparison Between Speeds of Both Algorithms`%timeit` is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method).
###Code
%timeit output = convolve_output_algorithm(x, h)
%timeit output = convolve_input_algorithm(x, h)
###Output
_____no_output_____
###Markdown
3. A Faster 1D ConvolutionA faster 1D convolution can be performed if inner loops can be transformed into matrix multiplications. This task can be accomplished by using *Toeplitz* matrices. A Toeplitz matrix or diagonal-constant matrix, named after Otto Toeplitz, is a matrix in which each descending diagonal from left to right is constant. For instance, the following matrix is a Toeplitz matrix:
###Code
from scipy.linalg import toeplitz
print(toeplitz(np.array([[1,2,3,4,5]])))
###Output
_____no_output_____
###Markdown
1D convolution can be obtained by using the lower triangular matrix of the Toeplitz matrix, $H$, and the vector $x$. For the matrix $H$ and vector $x$ to have right dimensions, zero padding must be used. The lower triangular matrix can be calculated using `np.tril()`.
###Code
print(np.tril(toeplitz(np.array([[1,2,3,4,5]]))))
def conv1d(x, h):
"""
Function that convolves an input signal x with an step response h using a Toeplitz matrix implementation.
Parameters:
x (numpy array): Array of numbers representing the input signal to be convolved.
h (numpy array): Array of numbers representing the unit step response of a filter.
Returns:
numpy array: Returns convolved signal y[n]=h[n]*x[n].
"""
#SOLVE IN HERE
pass
%timeit output = conv1d(x, h)
cplots.plot_three_signals(x, h, output)
###Output
_____no_output_____
###Markdown
2D Convolution on ImagesIf the convolution is performed between two signals spanning along two mutually perpendicular dimensions (i.e., if signals are two-dimensional in nature), then it will be referred to as 2D convolution. This concept can be extended to involve multi-dimensional signals due to which we can have multidimensional convolution.For a 2D filter $h[m,n]$, or *kernel*, that has size $2M$ by $2N$ a 2D convolution is defined as follows:$$y[i,j]=\sum_{m=-M}^{M+1}\sum_{n=-N}^{N+1}{h[m,n]x[i-m,j-n]}$$
###Code
def conv2d(image, kernel):
"""
Function that convolves an input image with a filter kernel.
Parameters:
image (numpy matrix): Matrix representing a 2D image.
kernel (numpy array): An m by n matrix to apply.
Returns:
numpy matrix: Returns convolved image with filter kernel.
"""
#SOLVE IN HERE
pass
from PIL import Image
# Load original image
image_original = Image.open('Images/dog.jpeg')
# Convert to gray scale
image_gray = image_original.convert('L')
# Resize gray image
scale_factor = 2
p,q = (np.array(np.array(image_gray).shape)/scale_factor).astype('int')
image_resize = image_gray.resize((p,q))
# Set image as an 2d-array x
x = np.array(image_resize)#.reshape(-1,1)
Sx = np.array([[-1, 0, 1],[-2, 0, 2], [-1, 0, 1]])
Sy = np.array([[-1, -2, -1],[0, 0, 0], [1, 2, 1]])
Gx_2 = conv2d(x, Sx)
Gy_2 = conv2d(x, Sy)
image_output = np.sqrt(np.power(Gx_2,2) + np.power(Gy_2,2))
plt.subplot(1,2,1)
plt.imshow(image_original.resize((p,q)))
plt.subplot(1,2,2)
plt.imshow(image_output, cmap='gray', vmin=0, vmax=255);
###Output
_____no_output_____ |
rsmtool/notebooks/summary/header.ipynb | ###Markdown
Summary Report
###Code
import itertools
import json
import os
import re
import pickle
import platform
import time
from collections import defaultdict as dd
from functools import partial
from os.path import abspath, dirname, exists, join
from string import Template
import numpy as np
import pandas as pd
import seaborn as sns
import scipy.stats as stats
from matplotlib import pyplot as plt
from IPython import sys_info
from IPython.display import display, HTML, Image, Javascript, Markdown, SVG
from rsmtool.utils.files import (get_output_directory_extension,
parse_json_with_comments)
from rsmtool.utils.notebook import (float_format_func,
int_or_float_format_func,
bold_highlighter,
color_highlighter,
show_thumbnail)
from rsmtool.reader import DataReader
from rsmtool.writer import DataWriter
from rsmtool.version import VERSION as rsmtool_version
rsm_report_dir = os.environ.get('RSM_REPORT_DIR', None)
if rsm_report_dir is None:
rsm_report_dir = os.getcwd()
rsm_environ_config = join(rsm_report_dir, '.environ.json')
if not exists(rsm_environ_config):
raise FileNotFoundError('The file {} cannot be located. '
'Please make sure that either (1) '
'you have set the correct directory with the `RSM_REPORT_DIR` '
'environment variable, or (2) that your `.environ.json` '
'file is in the same directory as your notebook.'.format(rsm_environ_config))
environ_config = parse_json_with_comments(rsm_environ_config)
###Output
_____no_output_____
###Markdown
div.prompt.output_prompt { color: white; } span.highlight_color { color: red; } span.highlight_bold { font-weight: bold; } @media print { @page { size: landscape; margin: 0cm 0cm 0cm 0cm; } * { margin: 0px; padding: 0px; } toc { display: none; } span.highlight_color, span.highlight_bold { font-weight: bolder; text-decoration: underline; } div.prompt.output_prompt { display: none; } h3Python-packages, divpackages { display: none; }
###Code
# NOTE: you will need to set the following manually
# if you are using this notebook interactively.
summary_id = environ_config.get('SUMMARY_ID')
description = environ_config.get('DESCRIPTION')
jsons = environ_config.get('JSONS')
output_dir = environ_config.get('OUTPUT_DIR')
use_thumbnails = environ_config.get('USE_THUMBNAILS')
file_format_summarize = environ_config.get('FILE_FORMAT')
# groups for subgroup analysis.
groups_desc = environ_config.get('GROUPS_FOR_DESCRIPTIVES')
groups_eval = environ_config.get('GROUPS_FOR_EVALUATIONS')
# javascript path
javascript_path = environ_config.get("JAVASCRIPT_PATH")
# initialize id generator for thumbnails
id_generator = itertools.count(1)
with open(join(javascript_path, "sort.js"), "r", encoding="utf-8") as sortf:
display(Javascript(data=sortf.read()))
# load the information about all models
model_list = []
for (json_file, experiment_name) in jsons:
model_config = json.load(open(json_file))
model_id = model_config['experiment_id']
model_name = experiment_name if experiment_name else model_id
model_csvdir = dirname(json_file)
model_file_format = get_output_directory_extension(model_csvdir, model_id)
model_list.append((model_id, model_name, model_config, model_csvdir, model_file_format))
Markdown("This report presents the analysis for **{}**: {} \n ".format(summary_id, description))
HTML(time.strftime('%c'))
# get a matched list of model ids and descriptions
models_and_desc = zip([model_name for (model_id, model_name, config, csvdir, model_file_format) in model_list],
[config['description'] for (model_id, model_name, config, csvdir, file_format) in model_list])
model_desc_list = '\n\n'.join(['**{}**: {}'.format(m, d) for (m, d) in models_and_desc])
Markdown("The report compares the following models: \n\n {}".format(model_desc_list))
if use_thumbnails:
display(Markdown("""***Note: Images in this report have been converted to """
"""clickable thumbnails***"""))
%%html
<div id="toc"></div>
###Output
_____no_output_____ |
nbs/01_extract.ipynb | ###Markdown
Extraction Utilities> Contains helpful functions for extracting embeddings and preparing data for it.
###Code
#export
from copy import deepcopy
import json
import torch.nn as nn
import pandas as pd
from fastcore.dispatch import *
from transfertab.utils import *
import os
emb_szs = ((3, 10), (4, 8))
embed = nn.ModuleList([nn.Embedding(ni, nf) for ni,nf in emb_szs])
embed
#export
class JSONizerWithBool(json.JSONEncoder):
def default(self, obj):
return super().encode(bool(obj)) \
if isinstance(obj, np.bool_) \
else super().default(obj)
#export
def _catdict2embedsdictstruct(catdict):
embedsdict = {}
for cat, classes in catdict.items():
embedsdict[cat] = {}
embedsdict[cat]["classes"] = classes
return embedsdict
#export
@typedispatch
def extractembeds(model: nn.Module, df: pd.DataFrame, *, transfercats, allcats, path=None, kind="bson"):
catdict = getcatdict(df, transfercats)
return extractembeds(model, catdict, transfercats=transfercats, allcats=allcats, path=path, kind=kind)
@typedispatch
def extractembeds(model: nn.Module, catdict: dict, *, transfercats, allcats, path=None, kind="bson"):
'''
Extracts embedding weights from `model`, which can be further transferred to other models.
model: Any pytorch model, containing the embedding layers.
catdict: A dictionary with category as key, and classes as value.
transfercats: Names of categories to be transferred.
allcats: Names of all categories corresponding to the embedding layers in model.
path: Path for the json to be stored.
'''
embedsdict = _catdict2embedsdictstruct(catdict)
model_dict = list(model.state_dict().items())
for i, cat in enumerate(transfercats):
classes = catdict[cat]
catidx = allcats.index(cat)
assert (model_dict[catidx][1].shape[0] == len(classes)), \
(f"embeddings dimension {model_dict[catidx][1].shape[0]} !="
f"num of classes {len(classes)} for vairable {cat}. Embeddings should have"
f"same number of classes. Something might have gone wrong.")
embedsdict[cat]["embeddings"] = model_dict[catidx][1].numpy().tolist()
if (path != None):
with open(path, 'w') as fp:
json.dump(embedsdict, fp, cls = JSONizerWithBool) if kind == "json" else store_bson(path, embedsdict)
return embedsdict
df = pd.DataFrame({"cat1": [1, 2, 3, 4, 5], "cat2": ['a', 'b', 'c', 'b', 'a'], "cat3": ['A', 'B', 'C', 'D', 'A']})
df
catdict = getcatdict(df, ("cat2", "cat3"))
cats = ("cat2", "cat3")
embdict = extractembeds(embed, df, transfercats=cats, allcats=cats, path="tempwtbson", kind="bson")
embdict
embdict = extractembeds(embed, df, transfercats=cats, allcats=cats, path="tempwtjson", kind="json")
embdict
load_bson("tempwtbson") == embdict
os.remove("tempwtbson")
os.remove("tempwtjson")
###Output
_____no_output_____
###Markdown
Export
###Code
#export
_all_ = ['extractembeds']
#hide
from nbdev.export import notebook2script
notebook2script()
###Output
Converted 00_utils.ipynb.
Converted 01_extract.ipynb.
Converted 02_transfer.ipynb.
Converted 03_load_tests.ipynb.
Converted index.ipynb.
|
lesson-3-12-multi-ticket-sample.ipynb | ###Markdown
From linear to multi-linear regressionIn the last notebook we learned about linear regression and using python libraries to make our life simpler. If you want to read about that, have a look athttps://github.com/jegali/DataScience/blob/main/lesson-3-9-ticket-sample.ipynbThe last code snippet dealt with the usage of statsmodel which we will use again in this example.
###Code
# a reference to the pandas library
import pandas as pd
# To visualize the data
import matplotlib.pyplot as plt
# This is new. Let's try a library which does
# the linear regression for us
import statsmodels.api as sm
from sklearn import linear_model
from sklearn.linear_model import LinearRegression
# To visualize the data
import matplotlib.pyplot as plt
# the excel file must be in the same directory as this notebook
# be sure to use the right excel data file.
# Udacity has some files named linear-example-data with different content
# I renamed this one to linear-example-data-3-13.xlsx
excel_file= 'linear-example-data-3-13.xlsx'
# via pandas, the contents ae read into a variable or data frame named data
data = pd.read_excel(excel_file)
# let's have a look at the data
print (" Contents of the file ", excel_file)
print(data)
# instead of only using one column for linear regression,
# we use two columns for multilinear regression
# column industry is no number column, so we can not integrate it into the calculation
X = data[['Number of Employees','Value of Contract']]
Y = data['Average Number of Tickets']
# let's do the evaluation with sklearn
# Many roads lead to Rome...
regr = linear_model.LinearRegression()
regr.fit(X, Y)
print ("\n\n")
print ("Linear Regression values evaluated by sklearn: ")
print(" ")
print('Y-intercept: \t', regr.intercept_)
print('Coefficients:\t', regr.coef_)
# let's to the evaluation with statsmodels
# we have to add a constant to the calculation or
# we do not have a Y-intercept
X = sm.add_constant(X)
# build the model
model = sm.OLS(Y,X).fit()
model_prediction = model.predict(X)
model_details = model.summary()
# and print the model summary
print("\n\n")
print("Linear Regression values evaluated by statsmodel: ")
print(" ")
print(model_details)
###Output
Contents of the file linear-example-data-3-13.xlsx
Average Number of Tickets Number of Employees Value of Contract \
0 1 51 25750
1 9 68 25000
2 20 67 40000
3 1 124 35000
4 8 124 25000
5 30 134 50000
6 20 157 48000
7 8 190 32000
8 20 205 70000
9 50 230 75000
10 35 265 50000
11 65 296 75000
12 35 336 50000
13 60 359 75000
14 85 403 81000
15 40 418 60000
16 75 437 53000
17 85 451 90000
18 65 465 70000
19 95 491 100000
Industry
0 Retail
1 Services
2 Services
3 Retail
4 Manufacturing
5 Services
6 Retail
7 Retail
8 Retail
9 Manufacturing
10 Manufacturing
11 Services
12 Manufacturing
13 Manufacturing
14 Services
15 Retail
16 Services
17 Services
18 Retail
19 Services
Linear Regression values evaluated by sklearn:
Y-intercept: -24.26671246720077
Coefficients: [0.10190728 0.00066845]
Linear Regression values evaluated by statsmodel:
OLS Regression Results
=====================================================================================
Dep. Variable: Average Number of Tickets R-squared: 0.878
Model: OLS Adj. R-squared: 0.863
Method: Least Squares F-statistic: 60.97
Date: Sun, 27 Dec 2020 Prob (F-statistic): 1.76e-08
Time: 14:27:30 Log-Likelihood: -75.083
No. Observations: 20 AIC: 156.2
Df Residuals: 17 BIC: 159.2
Df Model: 2
Covariance Type: nonrobust
=======================================================================================
coef std err t P>|t| [0.025 0.975]
---------------------------------------------------------------------------------------
const -24.2667 7.020 -3.457 0.003 -39.079 -9.455
Number of Employees 0.1019 0.028 3.594 0.002 0.042 0.162
Value of Contract 0.0007 0.000 3.564 0.002 0.000 0.001
==============================================================================
Omnibus: 0.901 Durbin-Watson: 2.452
Prob(Omnibus): 0.637 Jarque-Bera (JB): 0.511
Skew: -0.384 Prob(JB): 0.775
Kurtosis: 2.851 Cond. No. 1.70e+05
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.7e+05. This might indicate that there are
strong multicollinearity or other numerical problems.
###Markdown
The model above gave the following equation: \begin{equation}Tickets = -24.267 + 0.1019 \cdot [Number \; of \; Employees] + 0.0007 \cdot [Value \; of \; Contract]\end{equation}What would the model predict for the number of tickets for a customer with 750 employees and a contract of $13,000? Inserting the value in the formula we get 61. Below we can see a visualization of the data as a scatter plot
###Code
# create an object for linear regression from sklearn
linear_regressor = LinearRegression()
# convert the values in an array that fits the function's need
X = data['Number of Employees'].values.reshape(-1, 1)
Y = data['Average Number of Tickets'].values.reshape(-1, 1)
# and do the regression calculation with sklearn
linear_regressor.fit(X,Y)
# make predictions on Y based on X
Y_pred = linear_regressor.predict(X)
print(" ")
# scatter plot
figure = plt.figure()
ax = figure.add_subplot(1,1,1)
ax.set_ylabel('Avg number of tickets')
ax.set_xlabel('Number of employees')
plt.scatter(X, Y)
# linear regression function
plt.title("Number of employees vs. Avg number of tickets")
plt.plot(X, Y_pred, color='red')
# show the graphs
plt.show()
###############################
###############################
###############################
# convert the values in an array that fits the function's need
X = data['Value of Contract'].values.reshape(-1, 1)
Y = data['Average Number of Tickets'].values.reshape(-1, 1)
# and do the regression calculation with sklearn
linear_regressor.fit(X,Y)
# make predictions on Y based on X
Y_pred = linear_regressor.predict(X)
print(" ")
# scatter plot
figure = plt.figure()
ax = figure.add_subplot(1,1,1)
ax.set_ylabel('Avg number of tickets')
ax.set_xlabel('Value of Contract')
plt.scatter(X, Y)
# linear regression function
plt.title("Value of Contract vs. Avg number of tickets")
plt.plot(X, Y_pred, color='red')
# show the graphs
plt.show()
###Output
|
_posts/Which_Classificaiton_model_is_best.ipynb | ###Markdown
Test Train Split
###Code
import numpy as np
from sklearn.model_selection import train_test_split
X = data.drop(["class"], axis = 1 )
y = data[["class"]]
X_train, X_test, y_train, y_test = train_test_split(pd.get_dummies(X, prefix_sep="_"), y, test_size=0.33, random_state=42)
###Output
_____no_output_____
###Markdown
Logistic Regression
###Code
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(random_state=0, solver='lbfgs',multi_class='multinomial').fit(X_train, y_train)
clf.score(X_test, y_test)
###Output
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/utils/validation.py:578: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
y = column_or_1d(y, warn=True)
###Markdown
Random Forest
###Code
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)
clf.fit(X_train, y_train)
clf.score(X_test, y_test)
###Output
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/ipykernel_launcher.py:3: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().
This is separate from the ipykernel package so we can avoid doing imports until
###Markdown
Decision Tree
###Code
from sklearn import tree
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, y_train)
clf.score(X_test, y_test)
###Output
_____no_output_____
###Markdown
Navie Bayes Theorm
###Code
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(X_train, y_train)
clf.score(X_test, y_test)
###Output
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sklearn/utils/validation.py:578: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
y = column_or_1d(y, warn=True)
###Markdown
SVC
###Code
from sklearn.svm import SVC
clf = SVC(gamma='auto')
clf.fit(X_train, y_train)
clf.score(X_test, y_test)
X_Quant = data[["duration","credit_amount","personal_status","installment_commitment","residence_since","age", "existing_credits" ,"num_dependents"]]
data.columns
data.nunique()
pd.get_dummies(data, prefix_sep="__")
###Output
_____no_output_____ |
Homeworks/04 - Applied ML/Homework04.ipynb | ###Markdown
DeadlineWednesday, November 22, 2017, 11:59PM Important notes- When you push your Notebook to GitHub, all the cells must already have been evaluated.- Don't forget to add a textual description of your thought process and of any assumptions you've made.- Please write all your comments in English, and use meaningful variable names in your code. Question 1: Propensity score matchingIn this exercise, you will apply [propensity score matching](http://www.stewartschultz.com/statistics/books/Design%20of%20observational%20studies.pdf), which we discussed in lecture 5 ("Observational studies"), in order to draw conclusions from an observational study.We will work with a by-now classic dataset from Robert LaLonde's study "[Evaluating the Econometric Evaluations of Training Programs](http://people.hbs.edu/nashraf/LaLonde_1986.pdf)" (1986).The study investigated the effect of a job training program ("National Supported Work Demonstration") on the real earnings of an individual, a couple of years after completion of the program.Your task is to determine the effectiveness of the "treatment" represented by the job training program. Dataset description- `treat`: 1 if the subject participated in the job training program, 0 otherwise- `age`: the subject's age- `educ`: years of education- `race`: categorical variable with three possible values: Black, Hispanic, or White- `married`: 1 if the subject was married at the time of the training program, 0 otherwise- `nodegree`: 1 if the subject has earned no school degree, 0 otherwise- `re74`: real earnings in 1974 (pre-treatment)- `re75`: real earnings in 1975 (pre-treatment)- `re78`: real earnings in 1978 (outcome)If you want to brush up your knowledge on propensity scores and observational studies, we highly recommend Rosenbaum's excellent book on the ["Design of Observational Studies"](http://www.stewartschultz.com/statistics/books/Design%20of%20observational%20studies.pdf). Even just reading the first chapter (18 pages) will help you a lot. 1. A naive analysisCompare the distribution of the outcome variable (`re78`) between the two groups, using plots and numbers.To summarize and compare the distributions, you may use the techniques we discussed in lectures 4 ("Read the stats carefully") and 6 ("Data visualization").What might a naive "researcher" conclude from this superficial analysis? 2. A closer look at the dataYou're not naive, of course (and even if you are, you've learned certain things in ADA), so you aren't content with a superficial analysis such as the above.You're aware of the dangers of observational studies, so you take a closer look at the data before jumping to conclusions.For each feature in the dataset, compare its distribution in the treated group with its distribution in the control group, using plots and numbers.As above, you may use the techniques we discussed in class for summarizing and comparing the distributions.What do you observe?Describe what your observations mean for the conclusions drawn by the naive "researcher" from his superficial analysis. 3. A propsensity score modelUse logistic regression to estimate propensity scores for all points in the dataset.You may use `sklearn` to fit the logistic regression model and apply it to each data point to obtain propensity scores:```pythonfrom sklearn import linear_modellogistic = linear_model.LogisticRegression()```Recall that the propensity score of a data point represents its probability of receiving the treatment, based on its pre-treatment features (in this case, age, education, pre-treatment income, etc.).To brush up on propensity scores, you may read chapter 3.3 of the above-cited book by Rosenbaum or [this article](https://drive.google.com/file/d/0B4jctQY-uqhzTlpBaTBJRTJFVFE/view).Note: you do not need a train/test split here. Train and apply the model on the entire dataset. If you're wondering why this is the right thing to do in this situation, recall that the propensity score model is not used in order to make predictions about unseen data. Its sole purpose is to balance the dataset across treatment groups.(See p. 74 of Rosenbaum's book for an explanation why slight overfitting is even good for propensity scores.If you want even more information, read [this article](https://drive.google.com/file/d/0B4jctQY-uqhzTlpBaTBJRTJFVFE/view).) 4. Balancing the dataset via matchingUse the propensity scores to match each data point from the treated group with exactly one data point from the control group, while ensuring that each data point from the control group is matched with at most one data point from the treated group.(Hint: you may explore the `networkx` package in Python for predefined matching functions.)Your matching should maximize the similarity between matched subjects, as captured by their propensity scores.In other words, the sum (over all matched pairs) of absolute propensity-score differences between the two matched subjects should be minimized.After matching, you have as many treated as you have control subjects.Compare the outcomes (`re78`) between the two groups (treated and control).Also, compare again the feature-value distributions between the two groups, as you've done in part 2 above, but now only for the matched subjects.What do you observe?Are you closer to being able to draw valid conclusions now than you were before? 5. Balancing the groups furtherBased on your comparison of feature-value distributions from part 4, are you fully satisfied with your matching?Would you say your dataset is sufficiently balanced?If not, in what ways could the "balanced" dataset you have obtained still not allow you to draw valid conclusions?Improve your matching by explicitly making sure that you match only subjects that have the same value for the problematic feature.Argue with numbers and plots that the two groups (treated and control) are now better balanced than after part 4. 6. A less naive analysisCompare the outcomes (`re78`) between treated and control subjects, as you've done in part 1, but now only for the matched dataset you've obtained from part 5.What do you conclude about the effectiveness of the job training program?___ Question 2: Applied MLWe are going to build a classifier of news to directly assign them to 20 news categories. Note that the pipeline that you will build in this exercise could be of great help during your project if you plan to work with text!1. Load the 20newsgroup dataset. It is, again, a classic dataset that can directly be loaded using sklearn ([link](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html)). [TF-IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf), short for term frequency-inverse document frequency, is of great help when if comes to compute textual features. Indeed, it gives more importance to terms that are more specific to the considered articles (TF) but reduces the importance of terms that are very frequent in the entire corpus (IDF). Compute TF-IDF features for every article using [TfidfVectorizer](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html). Then, split your dataset into a training, a testing and a validation set (10% for validation and 10% for testing). Each observation should be paired with its corresponding label (the article category).2. Train a random forest on your training set. Try to fine-tune the parameters of your predictor on your validation set using a simple grid search on the number of estimator "n_estimators" and the max depth of the trees "max_depth". Then, display a confusion matrix of your classification pipeline. Lastly, once you assessed your model, inspect the `feature_importances_` attribute of your random forest and discuss the obtained results.
###Code
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
import networkx as nx
from networkx.algorithms import bipartite
%matplotlib inline
###Output
_____no_output_____
###Markdown
Question 1 Part 1: A naive analysisIn this part we will compare the distribution of the outcome variable (re78 column) using:* Pandas' `describe` function to get a rough idea of the distribution (mainly mean, standard deviation, median and quantiles)* Box plots* HistogramsWe didn't find any annotation regarding the meaning of zeros both in the web page on which the dataset was published and in the original paper we'll assume that they're not used to indicate missing data but that the subjects were unemployed.In order to make plotting the data of the two groups easier we split the dataframe in two depending on the `treat` variable.
###Code
# load data
df = pd.read_csv('lalonde.csv')
# Create a new column for white subjects (anyone who is not hispanic or black)
df['white'] = ((df.black==0)&(df.hispan==0)).astype(int)
df.head()
# Split into two dataframes to make plotting the two groups easier
treated = df[df.treat==1]
non_treated = df[df.treat==0]
def describe_outcomes(treated_df, control_df, control_name):
"""Use DataFrame.describe() to compare the distribution of the 1978 real income of two groups
Return the results in a new DataFrame."""
return pd.DataFrame({'Treated': treated_df.re78.describe(), control_name: control_df.re78.describe()})
describe_outcomes(treated, non_treated, 'Non treated')
###Output
_____no_output_____
###Markdown
We can see that the mean is greater than the median in both cases and that both the mean and the median are greater in the control group. There are many more subjects in the control group than in the treated group. We can also see that the lower and upper quantile are closer to the median in the treated group but the maximum income in the treated group is very large, more than twice as high as the highest value in the control group. The standard deviation of the data is very large (larger than the mean in both cases) but since the median and the mean do not coincide we can deduce that the distribution of the data is not symmetric and therefore not normal.Since we assumed that a real earning of $0 means that the subject is unemployed we can also compute an unemployment rate for each group.
###Code
# Unemployment rate
print('Unemployment rate in the treated group:', (treated.re78==0).sum()/treated.re78.shape[0])
print('Unemployment rate in the control group:', (non_treated.re78==0).sum()/non_treated.re78.shape[0])
def box_plot_outcomes(treated_df, control_df, control_name):
fig, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)
fig.set_size_inches((13,5))
ax1.set_title('Treated')
treated_df[['re78']].boxplot(vert=False, ax=ax1, showfliers=True)
ax2.set_title(control_name)
control_df[['re78']].boxplot(vert=False, ax=ax2, showfliers=True)
# boxplot of salaries of two groups
box_plot_outcomes(treated, non_treated, 'Non treated')
###Output
_____no_output_____
###Markdown
The box plots show us that while most of the real incomes of the treated groups tend to lie closer to the median, there are many more large outliers in that group than in the control group, as evidenced by the presence of multiple _fliers_.
###Code
# histogram of salary for employed people in the two groups
fig = plt.figure(figsize=(16,6))
ax = plt.subplot(121)
ax.set_title('Treated')
treated.re78.hist(ax=ax, bins=50)
ax = plt.subplot(122)
ax.set_title('Non treated')
non_treated.re78.hist(ax=ax, bins=50)
###Output
_____no_output_____
###Markdown
From these histograms we can clearly see that the distribution of the data is not normal and in fact it looks closer to a long-tailed distribution. We can use a log-log plot to verify whether the data follows a power law.
###Code
# log-log histogram
treated_no_zeros = treated[treated.re78 != 0]
non_treated_no_zeros = non_treated[non_treated.re78 != 0]
# Use custom bins for a logarithmic x axis
bins_treated = np.logspace(np.log10(min(treated_no_zeros.re78)), np.log10(max(treated_no_zeros.re78)), 20)
bins_non_treated = np.logspace(np.log10(min(non_treated_no_zeros.re78)), np.log10(max(non_treated_no_zeros.re78)), 20)
# Draw the plots
fig = plt.figure(figsize=(16,6))
ax = plt.subplot(121)
ax.set_title('Treated')
treated_no_zeros.re78.hist(ax=ax, log=True, bins=bins_treated)
ax.set_xscale('log')
ax = plt.subplot(122)
ax.set_title('Non treated')
non_treated_no_zeros.re78.hist(ax=ax, log=True, bins=bins_non_treated)
ax.set_xscale('log')
###Output
_____no_output_____
###Markdown
We can see that the data doesn't follow a power law, as the log-log plot doesn't display a linear decrease. We can also try to plot a histogram of the logarithm of the real incomes for both groups.
###Code
# histogram of log-salary
fig = plt.figure(figsize=(16,6))
ax = plt.subplot(121)
np.log(treated_no_zeros.re78).hist(ax=ax, bins=15)
ax = plt.subplot(122)
np.log(non_treated_no_zeros.re78).hist(ax=ax, bins=15)
###Output
_____no_output_____
###Markdown
ObservationsThe median salary of the treated groups is lower than that of the control group by about $600 which could suggest at the treatment is not helpful but on the contrary it tends to make the subjects perform worse. Another significant difference between the groups is that the treated groups has many outliers with very large income that are absent from the control group. Part 2: A closer look at the dataWe will now compare the distribution of the other features in the two groups by plotting a histogram or pie chart for each group and feature: in order for the experiment to be meaningful all features need to have the same distriution in both groups.First of all let's define some visualization helper functions.
###Code
def pie_treated_vs_control(treated_series, control_series, control_name, **kwargs):
"""Compare the value frequencies of two series using pie charts"""
# Combining the two series in a single DataFrame produces more consistent coloring
comp_df = pd.DataFrame({'Treated': treated_series, control_name: control_series})
comp_df.plot.pie(**kwargs)
def hist_treated_vs_control(treated_series, control_series, title, control_name, ax=None, **kwargs):
"""Compare the value frequencies of two series using histograms"""
if ax is None:
_, ax = plt.subplots()
ax.hist([treated_series.values, control_series.values],
weights = [[1/len(treated_series)]*len(treated_series),
[1/len(control_series)]*len(control_series)],
label=['Treated', control_name], **kwargs)
ax.legend(prop={'size': 10})
ax.set_title(title)
ax.set_ylabel('Density')
def feature_comparison(treated_df, control_df, control_title):
"""Compare the distribution of features between two groups"""
treated_race = (treated_df.black + 2 * treated_df.hispan).replace({0: 'White', 1: 'Black', 2: 'Hispanic'})
control_race = (control_df.black + 2 * control_df.hispan).replace({0: 'White', 1: 'Black', 2: 'Hispanic'})
pie_treated_vs_control(treated_race.value_counts(), control_race.value_counts(), control_title,
subplots=True, title='Race', legend=False)
treated_married = treated_df.married.replace({0: 'Not married', 1: 'Married'})
control_married = control_df.married.replace({0: 'Not married', 1: 'Married'})
pie_treated_vs_control(treated_married.value_counts(), control_married.value_counts(), control_title,
subplots=True, legend=False, title='Marital status')
treated_nodegree = treated_df.nodegree.replace({0: 'Degree', 1: 'No degree'})
control_nodegree = control_df.nodegree.replace({0: 'Degree', 1: 'No degree'})
pie_treated_vs_control(treated_nodegree.value_counts(), control_nodegree.value_counts(), control_title,
subplots=True, legend=False, title='Higher education')
fig = plt.figure(figsize=(13, 8))
ax1, ax2 = plt.subplot(221), plt.subplot(222)
hist_treated_vs_control(treated_df.age, control_df.age, 'Age', control_title, ax=ax1)
hist_treated_vs_control(treated_df.educ, control_df.educ, 'Length of education in years', control_title, ax=ax2)
ax3, ax4 = plt.subplot(223), plt.subplot(224)
hist_treated_vs_control(treated_df.re74, control_df.re74, 'Real income in 1974', control_title, ax=ax3)
hist_treated_vs_control(treated_df.re75, control_df.re75, 'Real income in 1975', control_title, ax=ax4)
###Output
_____no_output_____
###Markdown
We chose to use pie charts for our categorical features (race, marital status and degree) and histogams for all others.Now we can compare the distribution of the features between the treated group and the control group.
###Code
feature_comparison(treated, non_treated, 'Non treated')
###Output
_____no_output_____
###Markdown
ObservationsIt's clear that the test subjects are not well matched between the two groups, and this is especially evident when comparing the distribution of feature like race and marital status. Therefore it can be argued that any results obtained by simply comparing the treated group with the control group are invalid because any differences could be due to factors other than the treatment itself. Part 3: A propsensity score model We'll use logistic regression to compute a propensity score based on all pre-treatment features for all subjects. This is an estimation of the probability that a subject will receive the treatment. We need to use one-hot encoding (i.e. encode each of them using a group of binary features, with only one active at a time for each group). In this case the only columns that we need to add are a `degree` column, the complimentary of `nodegree` and a `non_married`, complimentary of `married`, because the subjects' race is already using one-hot encoding.
###Code
# One-hot encoding for degree and marital status
df['degree'] = 1 - df.nodegree
df['non_married'] = 1 - df.married
# Feature columns
tx = df[['age', 'educ', 'black', 'hispan', 'white', 'non_married', 'married', 'degree', 'nodegree', 're74', 're75']]
# Label column
y = df['treat']
# Fit a logistic model to the data
logistic = linear_model.LogisticRegression()
logistic.fit(tx, y)
# Use the model to predict a propensity score
prop_score = logistic.predict_proba(tx)
# Add the propensity score to a copy of our original dataframe
with_propensity = df.copy()
with_propensity['propensity_score'] = prop_score[..., 1]
# Dataframes for treated and control groups
treated_with_propensity = with_propensity[with_propensity.treat == 1]
non_treated_with_propensity = with_propensity[with_propensity.treat == 0]
with_propensity.head()
###Output
_____no_output_____
###Markdown
Part 4: Balancing the dataset via matching We will now use NetworkX to create an undirected graph where each node corresponds to a subject in the experiment and the edges only connect nodes belonging to two different groups. This is known as a _bipartite graph_.After that we will assign to each edge a weight equal to minus the absolute value of the difference in propensity score of the nodes it connects. This way we'll be able to to select the best candidates for our new control group by selecting the set of edges that maximize the sum of their weights (implemented in NetworkX as `max_weight_matching`).For this to work it is important that each node is connected to each member of the opposite group by exactly one edge (_complete bipartite graph_).
###Code
def make_propensity_graph(treated_df, control_df):
"""Create a new complete bipartite graph for the two groups"""
treated_len = treated_df.shape[0]
non_treated_len = non_treated_with_propensity.shape[0]
# Create the graph
G = nx.complete_bipartite_graph(treated_len, non_treated_len)
set_edge_weights(G, treated_df, control_df)
return G
def set_edge_weights(G, treated_df, control_df):
"""
Assign a weight to each edge of the graph according to the difference
between the two nodes' propensity score
"""
treated_len = treated_df.shape[0]
weights = {}
# Compute a weight for each edge
for edge in G.edges():
edge_wt = treated_df.iloc[edge[0]]['propensity_score'] - \
control_df.iloc[edge[1] - treated_len]['propensity_score']
# The algorithm *maximizes* the sum of the weights and we want the
# difference in propensity score to be as small as possible so we
# need to use negative values
weights[edge] = -abs(edge_wt)
# The algorithm requires each edge to have a 'weight' attribute
nx.set_edge_attributes(G, weights, 'weight')
def make_matched_groups(G, treated_df, control_df):
"""
Use the weights assigned to the edges to find the subset
of the control group that best matches the treated group
"""
treated_len = treated_df.shape[0]
# Returns a dictionary mapping nodes to nodes
match = nx.max_weight_matching(G, maxcardinality=True)
# In NetworkX each node of the bipartite graph has an integer label
# so we need to use that as an index into the dataframe.
# Indices in the second dataframe are shifted up by the length of the first one.
# E.g. treated_len + 1 corresponds to the second element of the control dataframe.
matched_control_df = pd.DataFrame([
control_df.iloc[match[i] - treated_len] for i in range(treated_len) if i in match
])
matched_treated_df = pd.DataFrame([
treated_df.iloc[i] for i in range(treated_len) if i in match
])
return matched_control_df, matched_treated_df
###Output
_____no_output_____
###Markdown
Now let's create the graph and find the best match
###Code
graph = make_propensity_graph(treated_with_propensity, non_treated_with_propensity)
control_match, _ = make_matched_groups(graph, treated_with_propensity, non_treated_with_propensity)
control_match.head()
# Verify that the two groups have the same number of members
control_match.shape[0] == treated.shape[0]
###Output
_____no_output_____
###Markdown
This is the subset of the control group that best matches the treated group in terms of difference in propensity score.Let's use the income of this group in 1978 to evaluate the effectiveness of the program.
###Code
describe_outcomes(treated, control_match, 'Matched control group')
box_plot_outcomes(treated, control_match, 'Matched control group')
hist_treated_vs_control(treated.re78, control_match.re78, 'Real income in 1978', 'Matched control group', bins=20)
###Output
_____no_output_____
###Markdown
After doing propensity score matching the median income of the subjects who received treatment is actually higher than those who didn't, and looking at the histogram suggest that unemployment is higher in the control group. However before we can draw any conclusion we have to verify how well our matching algorithm really worked.
###Code
feature_comparison(treated, control_match, 'Matched control group')
###Output
_____no_output_____
###Markdown
Even though propensity score matching made the distribution of most feature more similar between groups, the distribution of race (and to a lesser degree age) are still different. We still cannot draw meaningful conclusions by comparing the incomes of the two groups. Part 5: Balancing the groups further Idea: we can improve our result by removing edges that connect two subjects whose race is different because the algorithm we are using will only match subjects that are connected by an edge.Problem: there are more black subjects in the treated group than there are in the control group and so we need to remove part of the treated subjects.Other ideas:* If the race of the two subjects is different drop the edge with a fixed probability.* Assign a very negative weight to such edges.While the latter two ideas would have allowed us to not remove any subjects from the treated group we found that they both failed to make the distribution of features of the two groups acceptably similar. Therefore we decided to go with the first approach even though this forced us to sacrifice some of the data.
###Code
def prune_edges(G, treated_df, control_df):
"""Return a copy of the graph where all edges where
the race of the two subjects is different removed"""
G2 = G.copy()
treated_len = treated_df.shape[0]
control_len = control_df.shape[0]
# All edges that connect two subjects having different race
edges_to_remove = [
(i, j + treated_len)
for i in range(treated_len)
for j in range(control_len)
if treated_df.black.iloc[i] != control_df.black.iloc[j] or
treated_df.hispan.iloc[i] != control_df.hispan.iloc[j]
]
G2.remove_edges_from(edges_to_remove)
return G2
graph2 = prune_edges(graph, treated_with_propensity, non_treated_with_propensity)
# New groups
(control_match_2, treated_match_2) = make_matched_groups(graph2, treated_with_propensity, non_treated_with_propensity)
# Check how many subjects are in each group and that the size of the groups matches
control_match_2.shape[0], control_match_2.shape[0] == treated_match_2.shape[0]
# Compare the distribution of features
feature_comparison(treated_match_2, control_match_2, 'Re-matched control group')
###Output
_____no_output_____
###Markdown
We can see that the age distribution is still not a perfect match but removing even more edges from the graph would have left us with very little data and assigning a very large negative weight to pairs with very different ages didn't result in a better match. The degree to which all other features are matched is satisfactory. Part 6: A less naive analysisWe can finally draw more meaningful conclusions about the effectiveness of the job training program. As before let's first have a look at some descriptive statistic. We already know that we cannot use mean and standard deviation so we'll focus on the quantiles instead.
###Code
describe_outcomes(treated_match_2, control_match_2, 'Re-matched control group')
###Output
_____no_output_____
###Markdown
Contrary to our very first analysis, these number suggests that the training program was in fact very effective, with the median salary of the treated group in 1978 being more than twice as high than the median salary of the control group.Visualizing the distribution with box plots and histograms will give us additional information
###Code
box_plot_outcomes(treated_match_2, control_match_2, 'Re-matched control group')
hist_treated_vs_control(treated_match_2.re78, control_match_2.re78, 'Real income in 1978', 'Re-matched control group', bins=20)
###Output
_____no_output_____
###Markdown
We can see from the box plots that even if we disregard the outliers the income of the treated group is decidedly higher: the lower quartile, medium, and upper quartile of the treated group are all higher than that of the control group. We can also see from the histogram that subjects who received the treatment are less likely to be unemployed or have a very low salary. Therefore we can conclude that after matching, unlike what our initial analysis suggested, the job training program leads to overall higher income. Question 2Load the 20newsgroup dataset. It is, again, a classic dataset that can directly be loaded using sklearn ([link](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html)). [TF-IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf), short for term frequency-inverse document frequency, is of great help when if comes to compute textual features. Indeed, it gives more importance to terms that are more specific to the considered articles (TF) but reduces the importance of terms that are very frequent in the entire corpus (IDF). Compute TF-IDF features for every article using [TfidfVectorizer](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html). Then, split your dataset into a training, a testing and a validation set (10% for validation and 10% for testing). Each observation should be paired with its corresponding label (the article category). Strategy: Part 1 Dataset Preparation1. We prepare the 20newsgroup dataset by loading the documents and labels into a dataframe. 2. We split the data into train (80%), validation (10%), and test (10%) sets. We will use the training set to train our classifier, the validation set to optimize the parameters for our classifier, and the test set to evaluate our classifier. 3. Using the TFIDFVectorizer module from sklearn, we calculate the term frequency-inverse document frequency for our word features for every document. Part 2 Train a Random Forest Classifier (and make improvements by finding the best parameters)1. We create the default classifier and evaluate our classifier using the test set. 2. We use grid search to find the best input values for the parameters n_estimators and max_depth3. We create another classifier using the best parameters and compare this to our original classifier.4. We observe and analyze the confusion matrix Further improvements: feature reduction1. We observe the feature importances attribute of our random forest classifier, and see the effects of reducing our feature vector. Dataset Preparation:1). We first prepare the 20newsgroup dataset by loading the documents and labels into a dataframe.
###Code
# Import the necessary modules
import pandas as pd
import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from scipy.sparse import vstack
import matplotlib.pyplot as plt
%matplotlib inline
# Load the 20newsgroups dataset into a dataframe
twenty_news = fetch_20newsgroups(subset = 'all')
news = pd.DataFrame({'Document': twenty_news.data,
'Label': twenty_news.target})
news.Label.replace(range(20), twenty_news.target_names, inplace=True)
news.head()
###Output
Downloading 20news dataset. This may take a few minutes.
Downloading dataset from https://ndownloader.figshare.com/files/5975967 (14 MB)
###Markdown
2). We split the dataset into three sets: Training Set (80%), Validation Set (10%), and Test Set(10%). We will also plot the distribution of classes for each set.
###Code
# Split the dataset/dataframe into train, valid, and test set
train, testval = train_test_split(news, test_size=0.2, random_state = 1)
test, valid = train_test_split(testval, test_size=0.5, random_state = 1)
# Plot the distribution of documents among the categories for the three sets
fig, axs = plt.subplots(1,3, figsize = (14, 3))
plt.tight_layout()
# Training set distribution
axs[0].set_title('Train Set Distribution')
train_distr_norm = train.groupby('Label').size()/train.shape[0]
train_distr_norm.plot(kind = 'bar', ax = axs[0])
# Test set distribution
axs[1].set_title('Test Set Distribution')
test_distr_norm = test.groupby('Label').size()/test.shape[0]
test_distr_norm.plot(kind = 'bar', ax = axs[1])
# Validation set distribution
axs[2].set_title('Validation Set Distribution')
valid_distr_norm = valid.groupby('Label').size()/valid.shape[0]
valid_distr_norm.plot(kind = 'bar', ax = axs[2])
plt.show()
size = train.groupby('Label').size()
print("No. Documents in smallest class: ", size.loc[size == size.min()].index[0], size.min())
print("No. Documents in largest class: ", size.loc[size == size.max()].index[0], size.max())
###Output
No. Documents in smallest class: talk.religion.misc 529
No. Documents in largest class: rec.sport.baseball 809
###Markdown
Observations:There are only small differences in the distributions of the train, test, and validation sets. In addition, the distribution over the classes in the train set are generally well distributed with the smallest training class being talk.religion.misc with 529 training documents, and the largest training class being rec.sport.baseball with 809 training documents. 3). Using the TFIDFVectorizer module from sklearn, we calculate the term frequency-inverse document frequency for our word features for every document.
###Code
# Compute TF-IDF feature of every document
count_vect = TfidfVectorizer()
# Learn the vocabulary and inverse document frequency (idf) from the training set,
# then transform the documents in the training set to a document-term matrix
X_train_counts = count_vect.fit_transform(train.Document)
# Using the vocabulary and idf learned from the training set, transform the validation and
# test set documents to a document-term matrix
X_valid_counts = count_vect.transform(valid.Document)
X_test_counts = count_vect.transform(test.Document)
# Have a look at the one of the training document
token_map = count_vect.get_feature_names()
feature = X_train_counts[10,:].toarray().flatten()
index = np.argsort(feature)
print('Top 10 tokens with largest TF-IDF:\n')
print('{:<20} {}'.format('Token', 'TF-IDF'))
for i in range(-1,-10,-1):
print('{:<20} {}'.format(token_map[index[i]], feature[index[i]]))
print('\nTarget:', train.Label.iloc[10])
print('Document:\n')
print(train.Document.iloc[10])
###Output
Top 10 tokens with largest TF-IDF:
Token TF-IDF
rubin 0.3162154064438425
cis 0.22777957961994075
ohio 0.2035299273271303
cycles 0.20274909719778142
hut 0.19076250929210406
gamma 0.18735589336133643
controller 0.1519878915821879
software 0.14846052383257052
fi 0.14691808429372372
Target: sci.electronics
Document:
From: [email protected] (Mika Iisakkila)
Subject: Re: what to do with old 256k SIMMs?
In-Reply-To: [email protected]'s message of 17 Apr 1993 14:05:06 -0400
Nntp-Posting-Host: gamma.hut.fi
Organization: Helsinki University of Technology, Finland
<[email protected]>
Lines: 15
[email protected] (Daniel J Rubin) writes:
>How hard would it be to somehow interface them to some of the popular
>Motorola microcontrollers.
Not hard, you can do the refreshing and access cycles by software, but
this hogs most of the available CPU cycles on a low-end controller.
I've seen some application note from Philips that used one of their
8051 derivatives as a printer buffer, with up to 1MB of dynamic ram
that was accessed and refreshed with software bit-banging.
Another alternative would be to use one of those nice DRAM controller
chips that "create static RAM appearance" and all that, but they may
be too expensive to make it worthwhile.
--
Segmented Memory Helps Structure Software
###Markdown
Observations:TF-IDF is a weight often used to evaluate how important a word is to a document in a corpus. It measures how frequently a term appears in a document downweighted by how often the term appears among the documents in the corpus. From this document we can see that the term frequencies are being calculated as expected, with the sender's email and affiliation being among the most frequent tokens. In addition, we can see that tokens that describe the electronics, such as 'controller', 'cycles', 'software' are also among the top TFIDF scores. Question 2, Part 2Train a random forest on your training set. Try to fine-tune the parameters of your predictor on your validation set using a simple grid search on the number of estimator "n_estimators" and the max depth of the trees "max_depth". Then, display a confusion matrix of your classification pipeline. Lastly, once you assessed your model, inspect the `feature_importances_` attribute of your random forest and discuss the obtained results.
###Code
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.model_selection import ParameterGrid
from sklearn.metrics import classification_report
from sklearn.metrics import precision_recall_fscore_support
###Output
_____no_output_____
###Markdown
Train a Random Forest Classifier (and make improvements by finding the best parameters)1). We create the default classifier and evaluate our classifier using the test set.
###Code
# Create a random forest classifier using the default parameters: n_estimators = 10, max_depth = None
rfc = RandomForestClassifier(random_state = 10)
# Train on the train set
rfc.fit(X_train_counts,train.Label)
# Predict on test set
predicted = rfc.predict(X_test_counts)
print("Default Random Forest Classifier Evaluation")
print(classification_report(test.Label, predicted))
print("Accuracy = ", accuracy_score(test.Label, predicted))
###Output
Default Random Forest Classifier Evaluation
precision recall f1-score support
alt.atheism 0.57 0.72 0.63 71
comp.graphics 0.39 0.58 0.46 99
comp.os.ms-windows.misc 0.50 0.62 0.56 109
comp.sys.ibm.pc.hardware 0.44 0.53 0.48 106
comp.sys.mac.hardware 0.50 0.61 0.55 93
comp.windows.x 0.67 0.67 0.67 98
misc.forsale 0.66 0.73 0.69 103
rec.autos 0.64 0.67 0.65 97
rec.motorcycles 0.78 0.75 0.76 102
rec.sport.baseball 0.69 0.73 0.71 84
rec.sport.hockey 0.85 0.77 0.81 111
sci.crypt 0.86 0.84 0.85 96
sci.electronics 0.59 0.45 0.51 93
sci.med 0.72 0.56 0.63 103
sci.space 0.86 0.73 0.79 101
soc.religion.christian 0.73 0.75 0.74 109
talk.politics.guns 0.78 0.69 0.73 89
talk.politics.mideast 0.89 0.83 0.86 90
talk.politics.misc 0.72 0.35 0.47 83
talk.religion.misc 0.75 0.38 0.50 48
avg / total 0.68 0.66 0.66 1885
Accuracy = 0.656233421751
###Markdown
Observations:We see that our accuracy (65.6%) for the default classifier is decent but could possibly be improved. In addition, if we look at the specific classes, some classes have low f1 scores and some have high. For example, talk.religion.misc has an f1 score of 0.5. The classifier has a harder time labeling documents in this class. We know that this class had the least training documents, but in addition, perhaps, the training features overlapped with those of the class soc.religion.christian. In that case, many talk.religion.misc documents in our test set could have been mislabeled as soc.religion.christian documents. On the other hand, the classifier performed the best at classifying documents of the talk.politics.mideast category with very high precision and high recall. This could be due to the fact that there are many tokens/features that are specific to this category. 2). We use grid search to find the best input values for the parameters n_estimators and max_depth
###Code
# Values of parameters to test
params_grid = {"n_estimators" : [10, 20, 50, 100, 120, 150],
"max_depth" : [20, 50, 100, 120, 150]}
# Initialize classifier and varibles to store the results
rfc = RandomForestClassifier(random_state = 10)
best_score, best_params = 0, None
# Use ParameterGrid() to create all combinations of settings
for kwarg in ParameterGrid(params_grid):
rfc.set_params(**kwarg)
rfc.fit(X_train_counts, train.Label)
predicted = rfc.predict(X_valid_counts)
score = accuracy_score(valid.Label, predicted)
# Keep the best setting
if(score>best_score):
best_score, best_params = score, kwarg
print('Score: {:.10f}, Parameters: {}'.format(score, kwarg))
print('\nBest settings:')
print('Score: {:.10f}, Parameters: {}'.format(best_score, best_params))
###Output
Score: 0.5177718833, Parameters: {'max_depth': 20, 'n_estimators': 10}
Score: 0.6196286472, Parameters: {'max_depth': 20, 'n_estimators': 20}
Score: 0.7395225464, Parameters: {'max_depth': 20, 'n_estimators': 50}
Score: 0.7766578249, Parameters: {'max_depth': 20, 'n_estimators': 100}
Score: 0.7851458886, Parameters: {'max_depth': 20, 'n_estimators': 120}
Score: 0.7846153846, Parameters: {'max_depth': 20, 'n_estimators': 150}
Score: 0.6270557029, Parameters: {'max_depth': 50, 'n_estimators': 10}
Score: 0.7331564987, Parameters: {'max_depth': 50, 'n_estimators': 20}
Score: 0.8063660477, Parameters: {'max_depth': 50, 'n_estimators': 50}
Score: 0.8381962865, Parameters: {'max_depth': 50, 'n_estimators': 100}
Score: 0.8371352785, Parameters: {'max_depth': 50, 'n_estimators': 120}
Score: 0.8413793103, Parameters: {'max_depth': 50, 'n_estimators': 150}
Score: 0.6763925729, Parameters: {'max_depth': 100, 'n_estimators': 10}
Score: 0.7740053050, Parameters: {'max_depth': 100, 'n_estimators': 20}
Score: 0.8318302387, Parameters: {'max_depth': 100, 'n_estimators': 50}
Score: 0.8594164456, Parameters: {'max_depth': 100, 'n_estimators': 100}
Score: 0.8594164456, Parameters: {'max_depth': 100, 'n_estimators': 120}
Score: 0.8594164456, Parameters: {'max_depth': 100, 'n_estimators': 150}
Score: 0.6705570292, Parameters: {'max_depth': 120, 'n_estimators': 10}
Score: 0.7628647215, Parameters: {'max_depth': 120, 'n_estimators': 20}
Score: 0.8249336870, Parameters: {'max_depth': 120, 'n_estimators': 50}
Score: 0.8530503979, Parameters: {'max_depth': 120, 'n_estimators': 100}
Score: 0.8535809019, Parameters: {'max_depth': 120, 'n_estimators': 120}
Score: 0.8525198939, Parameters: {'max_depth': 120, 'n_estimators': 150}
Score: 0.6790450928, Parameters: {'max_depth': 150, 'n_estimators': 10}
Score: 0.7681697613, Parameters: {'max_depth': 150, 'n_estimators': 20}
Score: 0.8249336870, Parameters: {'max_depth': 150, 'n_estimators': 50}
Score: 0.8530503979, Parameters: {'max_depth': 150, 'n_estimators': 100}
Score: 0.8572944297, Parameters: {'max_depth': 150, 'n_estimators': 120}
Score: 0.8583554377, Parameters: {'max_depth': 150, 'n_estimators': 150}
Best settings:
Score: 0.8594164456, Parameters: {'max_depth': 100, 'n_estimators': 100}
###Markdown
Observations: Here, we wanted to evaluate the best parameters for max_depth, and n_estimators so we performed a grid search. Our best parameters are max_depth = 100 and n_estimators = 100. If we expand the nodes of the trees past a depth of 100, the classifier accuracy does not really improve. In addition, increasing the number of trees in the forest past 100, decreases the accuracy.
###Code
from scipy.sparse import vstack
import matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
3). We create another classifier using the best parameters and compare this to our original classifier.
###Code
# Create a classifier with parameters obtained from grid search
rfc = RandomForestClassifier(**best_params, random_state = 10)
# Train on the train set
rfc.fit(X_train_counts,train.Label)
# Predict on test set
predicted = rfc.predict(X_test_counts)
print("Improved Random Forest Classifier Evaluation")
print(classification_report(test.Label, predicted))
print("Accuracy = ", accuracy_score(test.Label, predicted))
###Output
Improved Random Forest Classifier Evaluation
precision recall f1-score support
alt.atheism 0.86 0.85 0.85 71
comp.graphics 0.70 0.77 0.73 99
comp.os.ms-windows.misc 0.76 0.87 0.81 109
comp.sys.ibm.pc.hardware 0.76 0.73 0.74 106
comp.sys.mac.hardware 0.85 0.85 0.85 93
comp.windows.x 0.85 0.81 0.83 98
misc.forsale 0.69 0.87 0.77 103
rec.autos 0.89 0.80 0.84 97
rec.motorcycles 0.90 0.92 0.91 102
rec.sport.baseball 0.94 0.90 0.92 84
rec.sport.hockey 0.96 0.97 0.97 111
sci.crypt 0.90 0.95 0.92 96
sci.electronics 0.75 0.68 0.71 93
sci.med 0.87 0.83 0.85 103
sci.space 0.88 0.92 0.90 101
soc.religion.christian 0.78 0.89 0.83 109
talk.politics.guns 0.87 0.88 0.87 89
talk.politics.mideast 0.97 0.97 0.97 90
talk.politics.misc 1.00 0.63 0.77 83
talk.religion.misc 0.75 0.50 0.60 48
avg / total 0.84 0.84 0.84 1885
Accuracy = 0.83925729443
###Markdown
Observations:We created a second classifier with the best parameters found with the grid search algorithm. All metrics (accuracy, precision, recall, f1) improved. If we look at the specific classes, we still see that talk.relgion.misc has a lower f1 score compared to the other classes. Specifically, there is high precision but low recall. This means that the majority of test documents labeled as talk.religion.misc were actually correctly labeled; however, of all the documents that are truly talk.religion.misc, we only labeled 50% of them. As mentioned for the default classifier, this could be due to the fact that there are overlapping features that represent soc.religion.christian and talk.religion.misc, so many talk.religion.misc could be mislabeled as soc.religion.christian. We can see that this is possible because in soc.religion.christian, precision isn't as high as recall, so some documents labeled as soc.religion.christian were not labeled correctly.Our average (weighted) F1 score is 0.84 which is a good improvement from 0.66. 4). We observe and analyze the confusion matrix
###Code
# Plot confusion matrix
cm = confusion_matrix(test.Label, predicted)
ax = plt.matshow(cm)
plt.gcf().set_size_inches((15,5))
plt.xlabel('Predicted Labels')
plt.ylabel('True Labels')
plt.xticks(range(20), twenty_news.target_names, rotation=90, fontsize=14)
plt.yticks(range(20), twenty_news.target_names, fontsize=14)
plt.gca().xaxis.set_ticks_position('bottom')
_=plt.colorbar()
###Output
_____no_output_____
###Markdown
Observations: As we mentioned in previous observations, there could be overlapping features that are highly indicative of multiple classes. In other words, the tokens that are representative (in terms of TFIDF) of sci.electronics could overlap with those representative of comp.* classes. The confusion matrix demonstrates this because a fraction of sci.electronics documents are being mislabeled as comp.graphics, comp.sys.ibm.pc.hardware, comp.sys.mac.hardware, etc. We also see this with the ongoing example of talk.religion.misc. As suspected, many talk.religion.misc documents are being mislabeled as alt.atheism and soc.religion.christian. The documents under the classes starting with comp. are being mislabeled as each other (because the topic domains of the classes are similar). Further improvements: feature reduction1. We observe the feature importances attribute of our random forest classifier, and see the effects of reducing our feature vector.
###Code
# Investigate feature importance
index = np.argsort(rfc.feature_importances_)[::-1]
importance = rfc.feature_importances_
importance_std = np.std([tree.feature_importances_ for tree in rfc.estimators_],
axis=0)
print("Top 10 features")
for i in range(10):
print('Importance: {:.6f} +- {:.6f}, {}'.format(importance[index[i]],
importance_std[index[i]],
token_map[index[i]]))
print("Bottom 10 features")
for i in range(index.shape[0]-10, index.shape[0]):
print('Importance: {:.6f} +- {:.6f}, {}'.format(importance[index[i]],
importance_std[index[i]],
token_map[index[i]]))
###Output
Top 10 features
Importance: 0.004903 +- 0.006005, windows
Importance: 0.004488 +- 0.006738, dod
Importance: 0.004106 +- 0.007367, clipper
Importance: 0.003912 +- 0.004491, car
Importance: 0.003513 +- 0.006603, sale
Importance: 0.003448 +- 0.005363, bike
Importance: 0.002867 +- 0.002400, re
Importance: 0.002795 +- 0.004363, god
Importance: 0.002743 +- 0.004011, cars
Importance: 0.002612 +- 0.003720, space
Bottom 10 features
Importance: 0.000000 +- 0.000000, izer
Importance: 0.000000 +- 0.000000, izetbegovic
Importance: 0.000000 +- 0.000000, izf
Importance: 0.000000 +- 0.000000, izf0
Importance: 0.000000 +- 0.000000, izfm
Importance: 0.000000 +- 0.000000, izh
Importance: 0.000000 +- 0.000000, izi
Importance: 0.000000 +- 0.000000, izk
Importance: 0.000000 +- 0.000000, izkgt
Importance: 0.000000 +- 0.000000, ÿhooked
###Markdown
Observations:The importance measured in the `feature_importance_` attribute by default is called "Gini importance". It is defined as the decrease of impurity contributed by a feature averaged over all decision trees in the forest.While there is a "re" on the top list that does not have a direct link to any topics, most of the top 10 important features are clearly related to a certain class: Windows, dod, clipper, car/caars, sale, bike, space directly relate to the topics comp.os.ms-windows.misc, talk.politics.guns, sci.electronics, rec.autos, misc.forsale, rec.motorcycles, sci.space respectively. God is definitely related to religion and corresponds to the 3 religious classes. This result is reasonable because these are the keywords of topics and should be helpful for classifying documents.This is a clear contrast to the bottom of the list. The features there are not even real words: they could be e-mail address, misspelled words, or some abbrivation that do not appear frequently. The (almost) zero importance implies that either these words are useless for classification or that they are never used in the algorithm.
###Code
# Feature selection based on feature importance
from sklearn.feature_selection import SelectFromModel
sfm = SelectFromModel(rfc, threshold='mean')
sfm.fit(X_train_counts, train.Label)
sel_train = sfm.transform(X_train_counts)
sel_valid = sfm.transform(X_valid_counts)
sel_test = sfm.transform(X_test_counts)
print(X_train_counts.shape)
print(sel_train.shape)
# Create a classifier with selected features
sel_rfc = RandomForestClassifier(**best_params, random_state = 10)
# Train on the train set
sel_rfc.fit(sel_train, train.Label)
# Predict on test set
predicted = sel_rfc.predict(sel_test)
print("Improved Random Forest Classifier Evaluation with Feature reduction")
print(classification_report(test.Label, predicted))
print("Accuracy = ", accuracy_score(test.Label, predicted))
# Investigate feature importance based on selected features
sel_index = sfm.get_support(indices=True)
index = np.argsort(sel_rfc.feature_importances_)[::-1]
importance = sel_rfc.feature_importances_
importance_std = np.std([tree.feature_importances_ for tree in sel_rfc.estimators_],
axis=0)
print("Top 10 features")
for i in range(10):
print('Importance: {:.6f} +- {:.6f}, {}'.format(importance[index[i]],
importance_std[index[i]],
token_map[sel_index[index[i]]]))
print("Bottom 10 features")
for i in range(index.shape[0]-10, index.shape[0]):
print('Importance: {:.6f} +- {:.6f}, {}'.format(importance[index[i]],
importance_std[index[i]],
token_map[sel_index[index[i]]]))
###Output
Top 10 features
Importance: 0.010257 +- 0.007890, windows
Importance: 0.009047 +- 0.008352, dod
Importance: 0.008308 +- 0.008154, sale
Importance: 0.008296 +- 0.006019, car
Importance: 0.006106 +- 0.006229, bike
Importance: 0.005923 +- 0.005219, space
Importance: 0.005659 +- 0.007191, clipper
Importance: 0.005630 +- 0.005889, hockey
Importance: 0.005448 +- 0.004752, cars
Importance: 0.005298 +- 0.004973, god
Bottom 10 features
Importance: 0.000000 +- 0.000000, communion
Importance: 0.000000 +- 0.000000, lucifer
Importance: 0.000000 +- 0.000000, heinous
Importance: 0.000000 +- 0.000000, randal
Importance: 0.000000 +- 0.000000, lud
Importance: 0.000000 +- 0.000000, 5366
Importance: 0.000000 +- 0.000000, 5363
Importance: 0.000000 +- 0.000000, orbiter
Importance: 0.000000 +- 0.000000, brashear
Importance: 0.000000 +- 0.000000, catching
|
frozen-lake 8x8 numpy.ipynb | ###Markdown
[['right' 'up' 'right' 'right' 'right' 'right' 'right' 'right'] ['up' 'up' 'up' 'up' 'up' 'up' 'right' 'right'] ['up' 'up' 'left' 'left' 'right' 'up' 'right' 'right'] ['up' 'up' 'up' 'up' 'left' 'left' 'right' 'right'] ['left' 'up' 'up' 'left' 'right' 'down' 'up' 'right'] ['left' 'left' 'left' 'right' 'up' 'left' 'left' 'right'] ['left' 'left' 'down' 'left' 'left' 'right' 'left' 'right'] ['right' 'down' 'left' 'left' 'right' 'down' 'down' 'left']]
###Code
import matplotlib.pyplot as plt
%matplotlib inline
# Number of visits per episode:
plt.plot(visits/num_episodes)
num_episodes/visits
###Output
_____no_output_____
###Markdown
Test Run
###Code
def moving_average(a, n=100) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
env.monitor.start('recordings', force=True)
num_episodes = 20000
R = []
model.r_prob = 0 # ensure that only the optimal solution is used
for n in xrange(num_episodes):
newstate = env.reset()
done = False
while not done:
# Current state
oldstate = newstate
# Perform epsilon-greedy action:
action = model.epsilon_greedy_action(oldstate)
# Take action and observe state and reward
newstate, reward, done, info = env.step(action)
R.append(reward)
if n % 1000 == 101:
MA = np.max(moving_average(R))
print 'step: ' + str(n) + '\t MRA: ' + str(MA)
if MA > 0.99:
break
env.monitor.close()
print len(R)
print np.min([n,100])
print moving_average(R, n = np.min([n,100]))
def moving_average(a, n=100) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
MA = moving_average(R)
np.max(MA)
gym.upload('/notebooks/hjem/RL/recordings', api_key='sk_znZbtlUTlu1nJNqFLRIyA')
###Output
_____no_output_____ |
Fall-19/Problem Set 3/Assignment 3 R.ipynb | ###Markdown
Big Assignment 3 BackgroundThe data for this exercise were used in Ebonya Washington's paper: "Female Socialization: How Daughters Affect Their Legislator Fathers' Voting on Women's Issues." published in the American Economic Review in 2008. The paper asks whether having daughters influences the voting behavior of members of the US Congress. The hypothesis is that having (more) daughters makes legislators more likely to vote liberally on issues concerning women.For this exercise, we will focus on votes that took place in the 108th Congress, which held session in 2003/04. As a measure of a liberal voting record, we use scores assigned by the American Association of University Women (AAUW), a liberal group that concerns itself with issues of interest to women. For the 108th Congress, the AAUW selected 9 pieces of legislation in the areas of education, equality and reproductive rights. The AAUW then assigned a score to each member of Congress. The scores range from 0 to 100 and measure the percentage of times the legislator voted in favor of the position held by the AAUW. The dataset `legislators.dta` contains the following characteristics for 320 members of the 108th Congress: * $ngirls$ number of daughters * $totchi$ number of children * $age$ Age * $female$ indicator for being female * $repub$ indicator for being a Republican * $moredef$ proportion of people in the legislator's district who are in favor of "more spending ondefense" * $aauw$ AAUW score (a) Estimate and report results for the following regression models:Load in the data set `legislators.dta`. Remember, you will first need to call the `haven` package to do so.Generate a variable `age2` $=\text{age}^2$Generate an interaction variable `repubage` $= \text{repub}*\text{age}$Generate an interaction variable `repubage2` $=\text{repub}*\text{age2}$Estimate the following three regression models:\begin{align}aauw&=\beta_0 +\beta_1female+\beta_2repub+\beta_3age+u ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (1) \\aauw&=\beta_0 +\beta_1female+\beta_2repub+\beta_3age+\beta_4 age2+u ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(2) \\aauw&=\beta_0 + \beta_1female+\beta_2repub+\beta_3age+\beta_4 age2+\beta_5 repubage+\beta_6 repubage2+u\ \ \ (3) \end{align}
###Code
# Add Code for part (a) here.
###Output
_____no_output_____
###Markdown
(b) Suggest which model is the best fit to the data Add your written answer for part (b) here. (c) Interpret the effect of `age` on `aauw` in each model Add your written answer for part (c) here. (d) Test whether there is an effect of age on aauw scores using the second model. Be sure to describe carefully the null and alternative hypothesis. Step 1: Estimate the restricted model.Step 2: Calculate the sum of squared residuals from the restricted and unrestricted models.Step 3: Apply the F-stat formula.Alternative (easier):Step 2 (alternative): Find the $R^2$ in the summary of the restricted and unrestricted models.Step 3 (alternative): Apply the $R^2$ version of the F-stat formula.
###Code
#Add code for part d here.
###Output
_____no_output_____
###Markdown
(e) Using the third model, predict the aauw score for a female republican who is 65 years old, and suggest a $95\%$ CI for that predicted value.Hint: See part 2-A of section notes 7. Add your written answer for part (e) here. (f) Suppose you learn that a 65 year-old female republican is about to be elected for the first time. Generate a $95\%$ CI for her voting score.Hint: See part 2-B of section notes 7. Add your written answer for part (f) here. (g) Interpret the coeffcient $\beta_2$ from model (3). Add your written answer for part (g) here. (h) Suppose you think republicans and non-republicans may have different gender patterns in voting. That is, republican men may vote differently than republican women, who may vote differently thandemocratic women who may vote differently than democratic men. Write down an estimation equaiton to test whether republican women, democratic women, and democratic men vote differently than republican men. Add your written answer to part (h) here. (i) Implement your test. Interpret each coeffcient.
###Code
#Add your code for part i here
###Output
_____no_output_____
###Markdown
(j) Adapt your regression to test whether democratic women vote differently than republican women. Please report your results (write out the estimating equations).
###Code
#Add your code for part j here
###Output
_____no_output_____ |
ECE445F18--Exercise#1.ipynb | ###Markdown
Mini Jupyter Exercise 1We first create arrays containing GDP data and years. In this solution, the arrays are being created as `numpy` arrays since we will be performing computations on these arrays. We then plot the data as a line graph (with markers) using the `pyplot` module within the `matplotlib` library. Plotting of GDP Data
###Code
import numpy as np
from matplotlib import pyplot as plt
# input GDP and Years data
year = np.array([1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010])
gdp = np.array([1.015, 1.33, 2.29, 3.26, 4.951, 6.759, 9.366, 13.131, 15.599])
# plot
plt.plot(year, gdp, color='red', marker='o', linestyle='dashed')
plt.title('Real US GDP (in trillions)')
plt.xlabel('Year')
plt.ylabel('Trillions of $')
plt.savefig("GDP_vs_Yr", dpi=300)
plt.show()
###Output
_____no_output_____
###Markdown
Discussion and Analysis*Note:* The following discussion and analysis is meant to convey a comprehensive approach to solving this **regression** problem. Regression will be formally studied in the class and most students are in fact *not* expected to have gotten close to this solution. Students' submissions will primarily be evaluated based on their effort and the final set of plots (regardless of their accuracy). Basic Mathematical ModelingLet us denote the year as $x$ and the GDP for the year as $y$. Note that we need to think of *year* as starting from 0, as the relationship should be independent of the absolute number. Looking at the plot above, it **appears** that the relationship between $y$ and $x$ is exponential and we can model this relationship as follows:$$y = f(x) \qquad \Leftrightarrow \qquad y = \theta^x. \qquad (1)$$> **Caution:** Strictly speaking, we should be stating that $y = f(x) + \epsilon$, where $\epsilon$ is referred to as the additive modeling error in regression analysis. Only if the data actually comes from the class of functions that we are considering will the modeling error $\epsilon$ be zero. We will, however, ignore this modeling error in the following for simplicity. Please consult with your instructor if you have trouble understanding this concept.In other words, we are saying that the class of models that we should consider for the relationship between GDP and years is exponential, given by:$$\mathcal{F} = \{f : \mathbb{R} \rightarrow \mathbb{R} \ | \ f(x) = \theta^x, \theta > 0\}. \qquad (2)$$> **Note:** Please make sure you are comfortable reading the mathematical notation given in (2). You can reach out to your instructor if you have trouble doing so.We also have access to nine data samples: $(y_i, x_i), i=1,\dots,9.$ In other words, we have $N = 9$. Setting-up and Solving the ProblemOur goal is to learn an $\widehat{f}$ such that $\widehat{f}$ is as close to $f$ as possible. Since the class of functions in this problem is described by a single parameter $\theta$, we can equivalently think of the problem as obtaining an estimate $\widehat{\theta}$ that is as close to $\theta$ as possible. While this problem might seem challenging, it can be simplified by taking $\log$ (in any base) on both sides of (1), which results in:$$\log(y) = x \log(\theta). \qquad (3)$$If we now define new variables $\tilde{y} = \log(y)$ and $\tilde{\theta} = \log(\theta)$ then we effectively have the following *linear* relationship between the transformed variables:$$\tilde{y} = x \tilde{\theta}. \qquad (4)$$Notice that knowing $\tilde{\theta}$ is equivalent to knowing $\theta$, since $\theta = \exp(\tilde{\theta})$, where we have assumed that the $\log$ is in base $e$. We also have $N=9$ data points in this transformed problem, given by $\{(\tilde{y}_i, x_i)\}_{i=1}^9$ with $\tilde{y}_i = \log(y_i)$. We now form two vectors $\tilde{\mathbf{y}} \in \mathbb{R}^9$ and $\mathbf{x} \in \mathbb{R}^9$ as follows:$$\tilde{\mathbf{y}} = \begin{bmatrix}\tilde{y}_1\\ \tilde{y}_2\\ \vdots\\ \tilde{y}_9\end{bmatrix}, \quad \text{and} \quad \mathbf{x} = \begin{bmatrix}x_1\\ x_2\\ \vdots\\ x_9\end{bmatrix}. \qquad (5)$$We then have from (4) and (5) the following equation:$$\tilde{\mathbf{y}} = \mathbf{x} \tilde{\theta}. \qquad (6)$$We have $\tilde{\theta}$ as unknown in (6), which is an overdetermined linear system of equations with one unknown. One way to solve (6) for $\tilde{\theta}$ is using the least squares formulation, which focuses on the so-called $\ell_2$-loss function:$$\hat{\tilde{\theta}} = \arg\min_{\tilde{\theta}} \|\mathbf{x} \tilde{\theta} - \tilde{\mathbf{y}}\|_2^2. \qquad (7)$$> **Note:** The notation $\|\mathbf{v}\|_2$ for a vector $\mathbf{v} \in \mathbb{R}^N$ is defined as: $\|\mathbf{v}\|_2 = \sqrt{v_1^2 + \dots + v_N^2}$. This is called the $\ell_2$-norm of a vector and is effectively the length of a vector in the conventional sense. Note also that $\mathbf{v}^T \mathbf{v} = \|\mathbf{v}\|_2^2$.In linear algebra, the solution to (7) is given by:$$\hat{\tilde{\theta}} = \mathbf{x}^T \tilde{\mathbf{y}}/(\mathbf{x}^T \mathbf{x}) = \mathbf{x}^T \tilde{\mathbf{y}}/\|\mathbf{x}\|_2^2. \qquad (8)$$Finally, we obtain:$$\widehat{\theta} = \exp(\hat{\tilde{\theta}}). \qquad (9)$$Combining (8) and (9), we see that:$$\widehat{f}(x) = \left(\exp\left(\frac{\mathbf{x}^T \tilde{\mathbf{y}}}{\|\mathbf{x}\|_2^2}\right)\right)^x. \qquad (10)$$ RecappingThis is a very simple example of a machine learning (and statistics) regression problem. The four main ingredients of this problem, as discussed in class, are:1. **Mathematical model:** Here, the mathematical model is taken to be exponential, as given by (1) and (2).2. **Data:** Here, we are given $N=9$ data samples in terms of pairs; note, however, that we will need to do some *preprocessing* of these samples to account for the fact that the year needs to start from 0.3. **Loss function:** The loss function being considered here is based on loss between the actual and the estimated values of the transformed GDP data; the loss function is known as $\ell_2$ loss here (see, e.g., (7)).4. **Computational algorithm:** While we could have used a computational algorithm to solve (7), this is such a simple example that we can in fact reach a closed-form solution, which is given by (8). Final Calculations and Plot
###Code
from IPython.display import display, Latex
# preprocessing and transformation of data
base_yr = 1930 # Base year
x = year - base_yr # subtraction of base year to ensure that the first year is '0'
y_tilde = np.log(gdp) # transformation of GDP data
# estimation of theta_tilde (effectively, theta in the log domain)
theta_tilde_hat = x.dot(y_tilde)/(x.dot(x))
# estimation of theta
theta_hat = np.exp(theta_tilde_hat)
# plot
plt.plot(year, gdp, color='red', marker='o', linestyle='dashed')
plt.plot(year, theta_hat**x, color='green', linestyle='dotted')
plt.title('Real US GDP (in trillions)')
plt.xlabel('Year')
plt.ylabel('Trillions of $')
plt.legend(('Actual GDP data', 'Predicted GDP data'))
plt.show()
# final display
display(Latex(r'Solution: $\widehat\theta$ = {}, which translates into {}$\%$ GDP growth per year.'
.format(round(theta_hat,3),round((theta_hat-1)*100,2))))
display(Latex(r'According to this analysis, the real US GDP in 2020 should be \${} trillions.'
.format(round(theta_hat**(2020-1930),3))))
###Output
_____no_output_____ |
filter_design/fir_filter.ipynb | ###Markdown
Sascha Spors,Professorship Signal Theory and Digital Signal Processing,Institute of Communications Engineering (INT),Faculty of Computer Science and Electrical Engineering (IEF),University of Rostock,Germany Tutorial Digital Signal Processing**FIR Filter**,Winter Semester 2021/22 (Master Course 24505)- lecture: https://github.com/spatialaudio/digital-signal-processing-lecture- tutorial: https://github.com/spatialaudio/digital-signal-processing-exercisesFeel free to contact lecturer [email protected]
###Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.markers import MarkerStyle
from matplotlib.patches import Circle
from scipy import signal
def zplane_plot(ax, z, p, k):
"""Plot pole/zero/gain plot of discrete-time, linear-time-invariant system.
Note that the for-loop handling might be not very efficient
for very long FIRs
z...array of zeros in z-plane
p...array of poles in z-zplane
k...gain factor
taken from own work
URL = ('https://github.com/spatialaudio/signals-and-systems-exercises/'
'blob/master/sig_sys_tools.py')
currently we don't use the ax input parameter, we rather just plot
in hope for getting an appropriate place for it from the calling function
"""
# draw unit circle
Nf = 2**7
Om = np.arange(Nf) * 2*np.pi/Nf
plt.plot(np.cos(Om), np.sin(Om), 'C7')
try: # TBD: check if this pole is compensated by a zero
circle = Circle((0, 0), radius=np.max(np.abs(p)),
color='C7', alpha=0.15)
plt.gcf().gca().add_artist(circle)
except ValueError:
print('no pole at all, ROC is whole z-plane')
zu, zc = np.unique(z, return_counts=True) # find and count unique zeros
for zui, zci in zip(zu, zc): # plot them individually
plt.plot(np.real(zui), np.imag(zui), ms=8,
color='C0', marker='o', fillstyle='none')
if zci > 1: # if multiple zeros exist then indicate the count
plt.text(np.real(zui), np.imag(zui), zci)
pu, pc = np.unique(p, return_counts=True) # find and count unique poles
for pui, pci in zip(pu, pc): # plot them individually
plt.plot(np.real(pui), np.imag(pui), ms=8,
color='C0', marker='x')
if pci > 1: # if multiple poles exist then indicate the count
plt.text(np.real(pui), np.imag(pui), pci)
plt.text(0, +1, 'k={0:f}'.format(k))
plt.text(0, -1, 'ROC for causal: white')
plt.axis('square')
plt.xlabel(r'$\Re\{z\}$')
plt.ylabel(r'$\Im\{z\}$')
plt.grid(True, which="both", axis="both",
linestyle="-", linewidth=0.5, color='C7')
def bode_plot(b, N=2**10, fig=None): # we use this here for FIRs only
if fig is None:
fig = plt.figure()
a = np.zeros(len(b)) # some scipy packages need len(a)==len(b)
a[0] = 1
z, p, gain = signal.tf2zpk(b, a)
W, Hd = signal.freqz(b, a, N, whole=True)
print('number of poles:', len(p), '\npole(s) at:', p,
'\nnumber of zeros:', len(z), '\nzero(s) at:', z)
gs = fig.add_gridspec(2, 2)
# magnitude
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(W/np.pi, np.abs(Hd), "C0",
label=r'$|H(\Omega)|$)',
linewidth=2)
ax1.set_xlim(0, 2)
ax1.set_xticks(np.arange(0, 9)/4)
ax1.set_xlabel(r'$\Omega \,/\, \pi$', color='k')
ax1.set_ylabel(r'$|H|$', color='k')
ax1.set_title("Magnitude response", color='k')
ax1.grid(True, which="both", axis="both",
linestyle="-", linewidth=0.5, color='C7')
# phase
ax2 = fig.add_subplot(gs[1, 0])
ax2.plot(W/np.pi, (np.angle(Hd)*180/np.pi), "C0",
label=r'$\mathrm{angle}(H('r'\omega))$',
linewidth=2)
ax2.set_xlim(0, 2)
ax2.set_xticks(np.arange(0, 9)/4)
ax2.set_xlabel(r'$\Omega \,/\, \pi$', color='k')
ax2.set_ylabel(r'$\angle(H)$ / deg', color='k')
ax2.set_title("Phase response", color='k')
ax2.grid(True, which="both", axis="both",
linestyle="-", linewidth=0.5, color='C7')
# zplane
ax3 = fig.add_subplot(gs[0, 1])
zplane_plot(ax3, z, p, gain)
# impulse response
N = 2**3 # here specially chosen for the examples below
k = np.arange(N)
x = np.zeros(N)
x[0] = 1 # create a Dirac
h = signal.lfilter(b, a, x)
ax4 = fig.add_subplot(gs[1, 1])
ax4.stem(k, h, linefmt='C0', markerfmt='C0o',
basefmt='C0:', use_line_collection=True)
ax4.set_xlabel(r'$k$')
ax4.set_ylabel(r'$h[k]$')
ax4.set_title('Impulse Response')
ax4.grid(True, which="both", axis="both", linestyle="-",
linewidth=0.5, color='C7')
def plot_windowed_FIR_design():
hw = h*w
W = np.arange(0, 2**10) * 2*np.pi / 2**10
[_, H] = signal.freqz(h, a=1, worN=W)
[_, Hw] = signal.freqz(hw, a=1, worN=W)
plt.figure(figsize=(10, 10))
plt.subplot(2, 1, 1)
plt.plot(k, h, 'C3o-', label='rectangular windowed FIR h[k]')
plt.plot(k, w, 'C7o-', label='Kaiser Bessel window w[k]')
plt.plot(k, hw, 'C0o-', label='Kaiser-Bessel windowed FIR hw[k]')
plt.xlabel('k')
plt.title('Impulse responses and window')
plt.legend()
plt.grid(True)
plt.subplot(2, 1, 2)
plt.plot([W[0]/np.pi, W[-1]/np.pi], [0, 0], 'C7')
plt.plot([W[0]/np.pi, W[-1]/np.pi], [-6, -6], 'C1')
plt.plot([W[0]/np.pi, W[-1]/np.pi], [-21, -21], 'C3:')
plt.plot([W[0]/np.pi, W[-1]/np.pi],
[StopBandMaxLevel, StopBandMaxLevel], 'C0:')
plt.plot([Wc/np.pi, Wc/np.pi], [StopBandMaxLevel, 0],
'C1', label=r'-6dB @ $\Omega_c$')
plt.plot(W/np.pi, 20*np.log10(np.abs(H)), color='C3',
label='rectangular windowed FIR')
plt.plot(W/np.pi, 20*np.log10(np.abs(Hw)), color='C0',
label='Kaiser-Bessel windowed FIR')
plt.xlim((0, 2))
plt.yticks(np.arange(-6-12*8, 12, 12))
plt.xlabel(r'$\Omega \,/\, \pi$')
plt.ylabel(r'$20\lg|H(\Omega)|$ / dB')
plt.title('Level response')
plt.legend()
plt.grid(True)
# some defaults for the upcoming code:
figsize = (12, 9)
###Output
_____no_output_____
###Markdown
Filter FundamentalsThe transfer function of digital filters can be generally expressed in the $z$-domain as\begin{equation}H(z)=\frac{Y(z)}{X(z)} = \frac{\sum\limits_{m=0}^M b_mz^{-m}}{\sum\limits_{n=0}^N a_nz^{-n}}=\frac{b_0z^0+b_1z^{-1}+b_2z^{-2}+...+b_Mz^{-M}}{a_0z^0+a_1z^{-1}+a_2z^{-2}+...+a_Nz^{-N}}\end{equation}with input $X(z)$ and output $Y(z)$.Real input signals $x[k]$ that should end up as real output signals $y[k]$ (in terms of signal processing fundamentals this is a special case, though most often needed in practice) require real coefficients $b,a\in\mathbb{R}$.This is only achieved with- single or multiple **real** valued- single or multiple **complex conjugate** pairsof zeros and poles.Furthermore, in practice we most often aim at (i) causal and (ii) bounded input, bound output (BIBO) stable LTI systems, which requires (i) $M \leq N$ and (ii) poles inside the unit circle.If all poles **and** zeros are **inside** the unit circle then the system is **minimum-phase** and thus $H(z)$ is straightforwardly **invertible**.Further concepts related to the transfer function are:- Analysis of the transfer characteristics is done by the DTFT$H(z=\mathrm{e}^{\mathrm{j}\Omega})$, i.e. evaluation on the unit circle.- We use $a_0=1$ according to convention in many textbooks.- The convention for arraying filter coefficients is straightforward with Python index starting at zero:$b_0=b[0]$, $b_1=b[1]$, $b_2=b[2]$, ..., $a_0=a[0]=1$, $a_1=a[1]$, $a_2=a[2]$. Filtering Process- A **non-recursive** system with $a_1,a_2,...,a_N=0$ always exhibits a **finiteimpulse response** (FIR), note: $a_0=1$ for output though. Due to the finite length impulse response, a non-recursive system is always stable.- The output signal of a **non-recursive** system in practice can be calculated by **linearconvolution** \begin{equation}y[k] = \sum\limits_{m=0}^{M} h[m] x[-m+k]\end{equation}of the finite impulse response $h[m]=[b_0, b_1, b_2,...,b_M]$ and the input signal $x[k]$.- A **recursive system** exhibits at least one $a_{n\geq1}\neq0$. Becauseof the feedback of the output into the system, a potentially **infinite impulseresponse** (IIR) and a potentially non-stable system results.- For a **recursive** system, in practice the **difference equation**\begin{equation}y[k] = b_0 x[k] + b_1 x[k-1] + b_2 x[k-2] + ... + b_M x[k-M] -a_1 y[k-1] - a_2 y[k-2] - a_3 y[k-3] - ... - a_N y[k-N]\end{equation}needs to be implemented.- A **pure non-recursive** system is obtained by ignoring the feedback paths, i.e. setting $a_1,a_2,...,a_N=0$.- A **pure recursive** system is obtained by ignoring the forward paths, i.e. setting $b_0,b_1,...,b_M=0$. Then, the values of the state variables $z^{-1}, z^{-2}, ..., z^{-M}$ alone determine how the system starts to perform at $k=0$, since the system has no input actually. This system type can be used to generate (damped) oscillations.Please note: A recursive system can have a finite impulse response, but this is very rarely the case.Therefore, literature usually refers to- an FIR filter when dealing with a non-recursive system- an IIR filter when dealing with a recursive system Signal Flow Chart of Direct Form IFor example, the signal flow for a **second order** ($M=N=2$), system with- a non-recursive part (feedforward paths, left $z^{-}$-path)- a recursive part (feedback paths, left $z^{-}$-path)is depicted below (graph taken from Wikimedia Commons) as straightforward **direct form I**, i.e. directly following the difference equation.Such as second order section is usually termed a biquad. FIR FilterIf all coefficients $a_{1,...,N}=0$, the feedback paths are not existent in the signal flow chart above.This yields a non-recursive system and has transfer function\begin{equation}H(z) = \frac{Y(z)}{X(z)} = \sum\limits_{m=0}^M b_mz^{-m}=b_0z^0+b_1z^{-1}+b_2z^{-2}+...+b_Mz^{-M}.\end{equation}with the difference equation \begin{equation}y[k] = b_0 x[k] + b_1 x[k-1] + b_2 x[k-2] + ... + b_M x[k-M],\end{equation}from which we can directly observe that the impulse response (i.e. for $x[k] = \delta[k]$) is\begin{equation}h[k] = b_0 \delta[k] + b_1 \delta[k-1] + b_2 \delta[k-2] + ... + b_M \delta[k-M].\end{equation}This constitutes $h[k]$ as the coefficients $b_k$ at sample instances $k$.The impulse response for this non-recursive system has always finite length of $M+1$ samples.Usually this filter type is referred to as finite impulse response (FIR) filter in literature.Very special recursive systems/filters can produce FIRs as well. This is however so rare, thatthe common link FIR filter == non-recursive system is predominantly made.The filter **order** is $M$, the **number of coefficients** $b$ is $M+1$. Be cautious here and consistent with the naming, it sometimes gets confusing. Especially for linear phase filters (see below) it is really important if $M$ or $M+1$ is either even or odd.Sometimes the **number of taps** $M+1$ is stated (rather than calling this number of coefficients). This refers to tapping $M+1$ delayed instances of the signal input signal $x$ to calculate the filtered output signal $y$. Note however, that tapping the signal for the first coefficient $b_0$ involves non-delayed $x[k]$.For FIR filters the magnitude at $\Omega=0$ and $\Omega=\pi$ can be straightforwardly evaluated with the following equations. The DC magnitude is obtained by \begin{align}g_0 = \sum_{k=0}^{M} h[k].\end{align}The magnitude at $\Omega=\pi$ (i.e. at half the sampling frequency) is obtained by \begin{align}g_\pi = \sum_{k=0}^{M} (-1)^k h[k].\end{align} Poles / Zeros of FIR FilterTo calculate poles and zeros of the transfer function $H(z)$ it is meaningful to rewrite\begin{equation}H(z) = \sum\limits_{m=0}^M b_mz^{-m} \frac{z^M}{z^M}=(b_0z^0+b_1z^{-1}+b_2z^{-2}+...+b_Mz^{-M}) \frac{z^M}{z^M}.\end{equation}This reveals that FIR filters have an $M$-fold pole at $z_\infty = 0$. This is always the case for non-recursive systems and besides the finite impulse response explains why these systems are always stable: poles in the origin are harmless, since they equally contribute to all frequencies.For the zeros, the equation\begin{equation}\sum\limits_{m=0}^M b_m z^{-m} z^M = b_M z^M+b_1 z^{M-1}+b_2 z^{M-2}+...+b_M = 0\end{equation}needs to be solved. The $M$-th order polynomial has $M$ zeros. Recall from above, that for $b\in\mathbb{R}$ only real or complex conjugate zeros can occur, but never single complex zeros. Essence of FIR Filter DesignThe fundamental concept (just as was it with window design for the DFT) is to place the $M$ available zeros in the $z$-plane such that a target magnitude **and** phase response results, which suits the desired filter characteristics.It is important to note that (contrary to IIR filters) the **magnitude** and **phase** response can be **separately controlled** with FIR filters.In the referenced [english monographs](../index.ipynb) we can find information on specific FIR design techniques such as- FIR design with windowing method- FIR design as minimax least-squares optimization problem- FIR design of frequency sampling a DTFT spectrumThese are well covered in Python's Scipy and Matlab. We will later discuss the windowing method. A Note on FIR Filtering vs. DFT WindowingConsider an input signal $x[k]$.An FIR filter $h[k]$ is used for convolution (i.e. filtering process)\begin{align}x[k] \ast h[k] \circ-\bullet X(\mathrm{e}^{\mathrm{j}\Omega}) \cdot H(\mathrm{e}^{\mathrm{j}\Omega}),\end{align}whereas the DFT windowing process involves a multiplication with a window $w[k]$\begin{align}x[k] \cdot w[k] \circ-\bullet \frac{1}{2\pi} X(\mathrm{e}^{\mathrm{j}\Omega}) \circledast_{2\pi} W(\mathrm{e}^{\mathrm{j}\Omega}).\end{align}In the DTFT domain this results in multiplication and circular convolution, respectively.So, for the finite-length sequences $h[k]$ and $w[k]$ the same design fundamentals hold: we must put zeros at suitable locations in the z-plane to realize a certain desired DTFT spectrum, either $H(\mathrm{e}^{\mathrm{j}\Omega})$ or $W(\mathrm{e}^{\mathrm{j}\Omega})$. Depending on the application, filtering or windowing, the DTFT design criteria might be very different, since the DTFT spectrum acts as multiplication or convolution onto the input signal's DTFT spectrum. However, the design concepts and algorithms itself are basically the same, this is sometimes not so obvious in textbooks. FIR Examples with M=1 and M=2It is meaningful to discuss a very simple case of FIR in detail in the first place.Once getting familiar with the underlying principles and concepts it is comparably easy to increase the FIR filter order and see how complexity evolves.Almost all important issues on FIRs can be explained with- the filter order $M=1$, thus number of coefficients is $M+1=2$ and with- the filter order $M=2$, thus number of coefficients is $M+1=3$.The calculus of zeros is not too tedious and can be still performed manually. Furthermore, the impact of $M$ zeros in the $z$-plain is comparably easy linked to the magnitude and phase response.So, let's play around with some simple coefficient settings. Example FIR M=1, b0=1, b1=1This is the most simple case of an FIR (actually the most simple FIR would be using only $b_0$, which is a pure gain/attenuation for input signal).The squared magnitude response can be given analytically as (try yourself, make use of $\mathrm{e}^{-\mathrm{j}\Omega}=\cos(\Omega)-\mathrm{j}\sin(\Omega)$ ) \begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})|^2 = |1 + \mathrm{e}^{-\mathrm{j}\Omega}|^2 = 2 \cos(\Omega) + 2 = 4 \cos^2(\frac{\Omega}{2}).\end{equation}Thus the magnitude response is \begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})| = 2 |\cos(\frac{\Omega}{2})|,\end{equation}which is confirmed by the below plot (left, top). The magnitude response exhibits lowpass characteristics.The impulse response is simply\begin{align}h[k] = b_0 \delta[k] + b_1\delta[k-1],\end{align}confirmed by the plot (right, bottom).For the $M$-th order polynomial the $M=1$ zero is easy to evaluate\begin{equation}b_0 z^1+b_1 z^{0} = z+1 = 0\to z_{0,1} = -1\end{equation}There is $M=1$ pole in the origin, i.e. $z_{\infty,1} = 0$. Zero and pole are shown in the $z$-plane (right, top).This FIR has special characteristics on the phase response, namely it is linear phase (type II), see discussion below.In the present case DC magnitude is $g_0=2$ and $f_s/2$-magnitude is $g_\pi=0$.
###Code
b = [1, 1] # linear phase FIR Type II
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example FIR M=1, b0=1, b1=-1\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})|^2 = 4 \sin^2(\frac{\Omega}{2}).\end{equation}\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})| = 2 |\sin(\frac{\Omega}{2})|.\end{equation}$z_{\infty,1}=0$,$z_{0,1}=1$$g_0=0$,$g_\pi=2$Linear phase type IVThis is a simple **highpass**, it performs the difference between two adjacent samples (see the impulse response).
###Code
b = [1, -1] # linear phase FIR Type IV
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example FIR M=2, b0=1, b1=0, b2=1Filter order $M=2$, number of coefficients $M+1=3$, although one coefficient is zero, namely $b_1=0$.\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})|^2 = 4 \cos^2(\Omega).\end{equation}\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})| = 2 |\cos(\Omega)|.\end{equation}double pole in origin $z_{\infty,1,2}=0$conjugate-complex pair $z_{0,1,2}=\pm \mathrm{j}$$g_0=2$,$g_\pi=2$Linear phase type IThis is a simple **bandstop**.
###Code
b = [1, 0, 1] # linear phase FIR Type I, the zero in between counts as coeff
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example FIR M=2, b0=1, b1=0, b2=-1Filter order $M=2$, number of coefficients $M+1=3$, although one coefficient is zero, namely $b_1=0$.\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})|^2 = 4 \sin^2(\Omega).\end{equation}\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})| = 2 |\sin(\Omega)|.\end{equation}double pole in origin $z_{\infty,1,2}=0$two single real zeros $z_{0,1,2}=\pm 1$$g_0=0$,$g_\pi=0$Linear phase type IIIThis is a simple **bandpass**.
###Code
b = [1, 0, -1] # linear phase FIR Type III, the zero in between counts as coeff
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example FIR M=2, b0=1, b1=2, b2=1Filter order $M=2$, number of coefficients $M+1=3$.The manual derivation of analytic magnitude response starts to get tedious, however:\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})|^2 = 16 \cos^4(\Omega).\end{equation}\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})| = 4 \cos^2(\Omega).\end{equation}double pole in origin $z_{\infty,1,2}=0$double real zero $z_{0,1,2}=-1$$g_0=4$,$g_\pi=0$Linear phase type IThis is a simple **lowpass**, with a little smoother characteristics.
###Code
b = [1, 2, 1] # linear phase FIR Type I
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example FIR M=2, b0=1, b1=-2, b2=1By reversing the sign for $b_1$ compared to the just discussed lowpass we obtain a highpass.Filter order $M=2$, number of coefficients $M+1=3$.\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})|^2 = 16 \sin^4(\Omega).\end{equation}\begin{equation}|H(\mathrm{e}^{\mathrm{j}\Omega})| = 4 \sin^2(\Omega).\end{equation}double pole in origin $z_{\infty,1,2}=0$double real zero $z_{0,1,2}=0$$g_0=0$,$g_\pi=4$Linear phase type IThis **highpass** has also slightly smoother characteristics.
###Code
b = [1, -2, 1] # linear phase FIR Type I
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example FIR M=2, b0=1, b1=1, b2=1/2So, far all zeros were aligned **on** the unit circle. We are not restricted to those locations, as long as we ensure positioning only real and complex-conjugate pairs in the $z$-plane.However, recall that we discussed so called optimum window design for DFT-based spectral analysis.There, zeros **on** the unit circle was a good idea, since the zero has most impact to shape the amplitude of the sidelobes. If a window has all zeros on the unit circle, we called this **optimum window**.Back to our FIR design example:Filter order $M=2$, number of coefficients $M+1=3$.double pole in origin $z_{\infty,1,2}=0$conjugate-complex pair $z_{0,1,2}=-\frac{1}{2}\pm \frac{1}{2}\mathrm{j}$$g_0=\frac{5}{2}$,$g_\pi=\frac{1}{2}$This 2nd order FIR **lowpass** becomes a little more complicated and has a ripple in the stopband. Most important, since the zeros are **not** on the unit circle the magnitude response exhibits **no** exact zeros. Second morst important: the impulse response does not have a symmetry of linear-phase filter types I-IV, thus it is a **non-linear-phase** FIR. In fact, since poles and zeros are all within unit circle, the filter is minimum-phase.Try to find and plot the inverse transfer function $H(z)^{-1}$. Why this must be a minimum phase filter as well and why is this an IIR filter. The code in Jupyter notebook `iir_filter.ipynb` might be helpful.
###Code
b = [1, 1, 1/2] # NON linear phase FIR, since there is no symmetry in the IR
# minimum phase since all poles and zeros are inside unit circle
# this system has a stable inverse (pole/zero reversal, 1/gain factor)
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example FIR M=2, b0=1/2, b1=1, b2=1We can even align zeros outside the unit circle, since contrary to poles this has no impact on stability.Filter order $M=2$, number of coefficients $M+1=3$.double pole in origin $z_{\infty,1,2}=0$conjugate-complex pair $z_{0,1,2}=-1\pm \mathrm{j}$$g_0=\frac{5}{2}$,$g_\pi=\frac{1}{2}$This 2nd order FIR **lowpass** has the same magnitude response as the above lowpass. This is due to the fact that in both cases their zeros have same distance to the unit circle.Obviously, this filter is also non-linear-phase, but also **not minimum-phase**. In fact, the filter is **maximum-phase**, i.e. the largest phase excess for the given magnitude response. Due to its maximum-phase, this FIR cannot simply be inverted, since then poles would lie outside the unit circle, yielding a non-stable system.
###Code
b = [0.5, 1, 1] # NON linear phase FIR, since there is no symmetry in the IR
# same magnitude as b = [1, 1, 1/2]
# but also NON minimum phase since zeros outside unit-circle
# rather maximum-phase
# this system has NO stable inverse
bode_plot(b, fig=plt.figure(figsize=figsize))
###Output
_____no_output_____
###Markdown
Example PlaygroundTry some other coefficient settings by yourself, use larger $M$. Note that the plot of $h[k]$ is hard coded up to $k=7$ only.For example, how about a lowpass filter where the coefficients come from the Kaiser-Bessel window?!?!Do you see the link to the [Pole/Zeros Plots of Window Functions](https://nbviewer.jupyter.org/github/spatialaudio/digital-signal-processing-exercises/blob/outputs/dft/window_zplane_frequency_response.ipynb) Jupyter notebook?
###Code
# 7 coeff, beta such that DC gain about 5
b = signal.kaiser(7, beta=2.15, sym=True)
bode_plot(b, fig=plt.figure(figsize=figsize))
np.sum(b)
###Output
_____no_output_____
###Markdown
Or another lowpass using the rectangular window. Yes, the rectangular window has lowpass characteristics, in literature this is known as the most simplest form of running average. In the example below, the last 7 samples are taken into account for averaging with equal weights.
###Code
# 7 coeff, DC gain = 5
b = np.ones(7)/7*5
bode_plot(b, fig=plt.figure(figsize=figsize))
np.sum(b)
###Output
_____no_output_____
###Markdown
FIR Filters with Linear PhaseIn the above examples a very important concept of FIR filters was already included, which we did not discuss in detail so far. We do this here: the **linear phase**. In practice we can realize this only in digital signal processing, since analog circuits do not have the precision that would be required to shape the required impulse response characteristics (we talk about certain symmetries here as we will see below).A linear-phase FIR filter exhibits the DTFT spectrum\begin{equation}H(\mathrm{e}^{\mathrm{j}\Omega}) = A(\mathrm{e}^{\mathrm{j}\Omega})\,\mathrm{e}^{-\mathrm{j}\,\alpha\,\Omega}\,\mathrm{e}^{\mathrm{j}\,\beta}\end{equation}with the magnitude spectrum $A(\mathrm{e}^{\mathrm{j}\Omega})\in\mathbb{R}$ and the phase $\mathrm{e}^{-\mathrm{j}\,\alpha\,\Omega}\,\mathrm{e}^{\mathrm{j}\,\beta}$ with $\alpha,\beta\in\mathbb{R}^+$.There are four different basic types of linear-phase FIR filters that differ by the symmetry of the impulse response and the length of the finite impulse response.The constant group delay in samples for all FIR filter types is $\frac{M}{2}=\text{const}$, which leads to half sample values for odd $M$. Most books follow this numbering, although this is not a strict standardization, so please be careful and rather check the FIR characteristics rather than the type number! FIR Type I- filter order $M$ even, odd number $M+1$ of filter coefficients $b$- even symmetry of the impulse response $h[k]=h[M-k]$- $\beta=0,\,\pi$- No fixed zeros, therefore all filter types are possible FIR Type II- filter order $M$ odd, even number $M+1$ of filter coefficients $b$- even symmetry of the impulse response $h[k]=h[M-k]$- $\beta=0,\,\pi$- Fixed zero $H(z=-1)=0$, i.e. zero at $\Omega=\pi$, $f=\frac{f_s}{2}$.- Therefore, only a lowpass or a bandpass can be realized properly. FIR Type III- filter order $M$ even, odd number $M+1$ of filter coefficients $b$- odd symmetry of the impulse response $h[k]=-h[M-k]$- $\beta=\frac{\pi}{2},\,\frac{3}{2}\pi$- Fixed zeros $H(z=1)=0$ and $H(z=-1)=0$, i.e. zeros at $\Omega=0$, $f=0$ and$\Omega=\pi$, $f=\frac{f_s}{2}$.- Therefore, only a bandpass can be realized properly. FIR Type IV- filter order $M$ odd, even number $M+1$ of filter coefficients $b$- odd symmetry of the impulse response $h[k]=-h[M-k]$- $\beta=\frac{\pi}{2},\,\frac{3}{2}\pi$- Fixed zero $H(z=1)=0$, i.e. zero at $\Omega=0$, $f=0$.- Therefore, only a highpass or a bandpass can be realized properly.Bandpasses are possible with all four FIR filter types.Since FIR type I has no restrictions it might be the favorable choice, except you wish to place zeros explicitly at $\Omega=0,\pi$. Then the other types might be of interest. Windowed FIR Design Low-PassNow, let us discuss one potential FIR design method that is straightforward and comes typically first in teaching & learning DSP. It is still used in practice, especially when low computational complexity is aimed for.The basic idea is to cut a suitable finite-length sequence out of an infinite impulse response of the ideal filter and to apply a window onto the finite-length sequence in order to reduce certain artifacts. The most simple case is using the rect window.So, let's discuss the technique with the ideal lowpass filter: the ideal lowpass (i.e. zero-phase and infinite impulse response) with cutoff frequency $0 < \Omega_c < \pi$ is given by inverse DTFT as\begin{equation}h[k] = \frac{1}{2 \pi} \int\limits_{-\Omega_c}^{+\Omega_c} 1 \cdot \mathrm{e}^{+\mathrm{j} \Omega k} \mathrm{d}\Omega.\end{equation}The analytic solution is\begin{equation}h[k]=\frac{\sin\left(\Omega_c k \right)}{\pi k} = \frac{\Omega_c}{\pi}\frac{\sin\left(\Omega_c k \right)}{\Omega_c k},\end{equation}i.e. a weighted sinc-function. We should have expected a sinc-like shape, since rect and sinc correspond in terms of the Fourier transform. In order to obtain a practical (finite order M) and causal (peak at M/2) we can shift this impulse response by $M/2$ (time delay)\begin{equation}h[k]=\frac{\sin\left(\Omega_c\left(k-\frac{M}{2}\right)\right)}{\pi\left(k-\frac{M}{2}\right)}\end{equation}and consider only the values for $0\leq k \leq M$, so filter order $M$, filter length $M+1$. Furthermore, we require that $M$ is even to obtain a linear-phase type I FIR filter. Then we can simplify\begin{equation}h[k]=\begin{cases}\frac{\sin\left(\Omega_c\left(k-\frac{M}{2}\right)\right)}{\pi\left(k-\frac{M}{2}\right)} &\quad k\neq \frac{M}{2}\\\frac{\Omega_c}{\pi} &\quad k=\frac{M}{2}.\end{cases}\end{equation}The plain cut out (i.e. a rectangular window) towards a FIR yields- on the one hand, the steepest roll-off for $\Omega>\Omega_c$ towards the first zero in the magnitude response- but on the other hand also the worst stop band damping in the magnitude response (maximum stopband level is only about -21 dB)Most often, larger maximum stopband level is desired under acceptance of less steep initial roll-off. This can be achieved with other window functions. A very well suited window for this filter design task is the Kaiser-Bessel window. Kaiser figured out that a certain maximum stopband level (usually this is here the first side lobe) can be controlled by the parameter $\beta$. This of course holds only if $M$ is chosen large enough to obtain such a damping at all.For a maximum stopband level $\gamma<-50$ in dB, the approximation\begin{equation}\beta_\mathrm{Kaiser-Bessel-Window} = -0.1102\,(\gamma+8.7)\end{equation}was invented.Then, with an accordingly designed window for $0\leq k \leq M$, the improved FIR is given as\begin{equation}h_w[k] = w[k] \cdot h[k],\end{equation}hence the design method's naming.In the examples below we use a Kaiser-Bessel window to control that stopband level does not exceed -54 dB.We design linear-phase type I FIR filters with the windowing method. Note, that contrary to the typical -3dB cut-off frequency definition for analog filters, here the **cut-off frequency is defined at -6 dB**!
###Code
# we require even! FIR order
# thus odd number of coefficients, linear-phase type I
M = 2**5 # -> 33 coeff
k = np.arange(M+1)
Wc = 2*np.pi * 1/4 # desired cut-off frequency
StopBandMaxLevel = -54 # < -50
beta = -0.1102*(StopBandMaxLevel+8.7)
# beta = 0 # beta = 0 is equal to the rectangular window!
print('beta =', beta)
w = signal.kaiser(M+1, beta, sym=True)
h = np.sin(Wc*(k-M//2)) / (np.pi*(k-M//2))
h[M//2] = Wc / np.pi
plot_windowed_FIR_design()
###Output
_____no_output_____
###Markdown
Windowed FIR Design High-PassWe can do the same approach for the ideal highpass filter:The ideal highpass (i.e. zero-phase and infinite impulse response) with cutoff frequency $0 < \Omega_c < \pi$ is given by inverse DTFT as\begin{equation}h[k] = \frac{1}{2 \pi} \int\limits_{\Omega_c}^{2\pi-\Omega_c} 1 \cdot \mathrm{e}^{+\mathrm{j} \Omega k} \mathrm{d}\Omega.\end{equation}The analytic solution is\begin{equation}h[k]=\frac{\sin\left(\pi k \right)}{\pi k}-\frac{\sin\left(\Omega_c k\right)}{\pi k}.\end{equation}In order to obtain a practical (finite order M) and causal (peak at M/2) we can shift this impulse response by $M/2$ (time delay)\begin{equation}h[k]=\frac{\sin\left(\pi\left(k-\frac{M}{2}\right)\right)}{\pi\left(k-\frac{M}{2}\right)}-\frac{\sin\left(\Omega_c\left(k-\frac{M}{2}\right)\right)}{\pi\left(k-\frac{M}{2}\right)}\end{equation}and consider only the values for $0\leq k \leq M$, so filter order $M$, filter length $M+1$. Furthermore, we require that $M$ is even to obtain linear-phase type I. Then we can simplify\begin{equation}h[k]=\begin{cases}-\frac{\sin\left(\Omega_c\left(k-\frac{M}{2}\right)\right)}{\pi\left(k-\frac{M}{2}\right)} &\quad k\neq \frac{M}{2}\\1-\frac{\Omega_c}{\pi} &\quad k=\frac{M}{2}.\end{cases}\end{equation}Again, with an accordingly designed window for $0\leq k \leq M$, the improved FIR is given as\begin{equation}h_w[k] = w[k] \cdot h[k].\end{equation}Kaiser-Bessel window is also perfectly suited for the highpass. So we use precisely the same window as for the lowpass.
###Code
h = - np.sin(Wc*(k-M//2)) / (np.pi*(k-M//2))
h[M//2] = 1 - Wc/np.pi
plot_windowed_FIR_design()
###Output
_____no_output_____ |
notebooks/3.7 gcn_news_quarterly_prediction.ipynb | ###Markdown
imports
###Code
import os
import sys
sys.path.append('../')
from glob import glob
import torch
import numpy as np
import pandas as pd
###Output
_____no_output_____
###Markdown
get and split data
###Code
from spug.dataset import DatasetGenerator
data_root = '../data'
sotck_path = os.path.join(
data_root, 'raw', 'stock', 'raw.csv'
)
sec_path = os.path.join(
data_root, 'raw', 'sec'
)
output_path = os.path.join(
data_root, 'processed'
)
data_list = sorted(glob(
os.path.join(
data_root, 'raw', 'news', '*q*.npy'
)
))
dg = DatasetGenerator(
data_list = data_list,
stock_path=sotck_path,
sec_path=sec_path,
freq='quarter'
)
###Output
_____no_output_____
###Markdown
model definition
###Code
from spug.model import GCN
###Output
_____no_output_____
###Markdown
model training
###Code
import argparse
from torch_geometric_temporal.signal import temporal_signal_split
from spug.utils import Trainer
dataset = dg.process()
train_dataset, test_dataset = temporal_signal_split(dataset, train_ratio=0.8)
INPUT_SHAPE = next(iter(train_dataset)).x.shape[1]
model = GCN(input_size = INPUT_SHAPE, hidden_dims=64)
args = argparse.Namespace(
num_epochs = 500,
learning_rate = 1e-3,
device = "cpu",
val_size = .1,
verbose = False
)
trainer = Trainer(model, train_dataset, args, test_dataset)
model = trainer.train()
###Output
100%|███████████████████████████████████████████████████████████████████████████| 500/500 [00:09<00:00, 52.25it/s] |
2/1-3/stack/Reverse Polish notation.ipynb | ###Markdown
Reverse Polish Notation**Reverse Polish notation**, also referred to as **Polish postfix notation** is a way of laying out operators and operands. When making mathematical expressions, we typically put arithmetic operators (like `+`, `-`, `*`, and `/`) *between* operands. For example: `5 + 7 - 3 * 8`However, in Reverse Polish Notation, the operators come *after* the operands. For example: `3 1 + 4 *`The above expression would be evaluated as `(3 + 1) * 4 = 16`The goal of this exercise is to create a function that does the following:* Given a *postfix* expression as input, evaluate and return the correct final answer. **Note**: In Python 3, the division operator `/` is used to perform float division. So for this problem, you should use `int()` after every division to convert the answer to an integer.
###Code
class LinkedListNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.num_elements = 0
self.head = None
def push(self, data):
new_node = LinkedListNode(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
self.num_elements += 1
def pop(self):
if self.is_empty():
return None
temp = self.head.data
self.head = self.head.next
self.num_elements -= 1
return temp
def top(self):
if self.head is None:
return None
return self.head.data
def size(self):
return self.num_elements
def is_empty(self):
return self.num_elements == 0
def evaluate_post_fix(input_list):
"""
Evaluate the postfix expression to find the answer
Args:
input_list(list): List containing the postfix expression
Returns:
int: Postfix expression solution
"""
# TODO: Iterate over elements
# TODO: Use stacks to control the element positions
stack = Stack()
for i in input_list:
if i in ['*', '/', '+', '-']: # To restrict insecure operations
# Define numbers
second = stack.pop()
first = stack.pop()
first, second = float(first), float(second) # To restrict insecure operations
# Define expression
expression = f'{first} {i} {second}'
global_scope = {"__builtins__": {}} # To restrict global operations
local_scope = {'first': first, 'i': i, 'second': second} # To restrict local operations
# Calculate the expression
output = eval(expression, global_scope, local_scope) # To restrict insecure operations
# Push output
stack.push(int(output))
else:
stack.push(int(i)) # If not notation, push the number
return stack.pop() # Return the result
def test_function(test_case):
output = evaluate_post_fix(test_case[0])
print(output)
if output == test_case[1]:
print("Pass")
else:
print("Fail")
test_case_1 = [["3", "1", "+", "4", "*"], 16]
test_function(test_case_1)
test_case_2 = [["4", "13", "5", "/", "+"], 6]
test_function(test_case_2)
test_case_3 = [["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"], 22]
test_function(test_case_3)
###Output
22
Pass
|
rosalind_workbook/probability.ipynb | ###Markdown
ProbabilityThe mathematical study of the chance of occurrence of random events, or the chance with which a specific event will occur.Rosalind link: [Probability](http://rosalind.info/problems/topics/probability/) Import modules
###Code
import os
import sys
from itertools import permutations
import numpy as np
import pandas as pd
from Bio.Seq import Seq
from Bio import SeqIO
from Bio.Alphabet import generic_rna
print('DONE!')
###Output
_____no_output_____
###Markdown
Mendel's First LawRosalind link: [Mendel's First Law](http://rosalind.info/problems/iprb/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Calculating Expected OffspringRosalind link: [Calculating Expected Offspring](http://rosalind.info/problems/iev/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Independent AllelesRosalind link: [Independent Alleles](http://rosalind.info/problems/lia/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Introduction to Random StringsRosalind link: [Introduction to Random Strings](http://rosalind.info/problems/prob/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Matching Random MotifsRosalind link: [Matching Random Motifs](http://rosalind.info/problems/rstr/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Expected Number of Restriction SitesRosalind link: [Expected Number of Restriction Sites](http://rosalind.info/problems/eval/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Independent Segregation of ChromosomesRosalind link: [Independent Segregation of Chromosomes](http://rosalind.info/problems/indc/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Counting Disease CarriersRosalind link: [Counting Disease Carriers](http://rosalind.info/problems/afrq/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Inferring Genotype from a PedigreeRosalind link: [Inferring Genotype from a Pedigree](http://rosalind.info/problems/mend/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Sex-Linked InheritanceRosalind link: [Sex-Linked Inheritance](http://rosalind.info/problems/sexl/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
The Wright-Fisher Model of Genetic DriftRosalind link: [The Wright-Fisher Model of Genetic Drift](http://rosalind.info/problems/wfmd/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
Wright-Fisher's Expected BehaviorRosalind link: [Wright-Fisher's Expected Behavior](http://rosalind.info/problems/ebin/)
###Code
# TODO
###Output
_____no_output_____
###Markdown
The Founder Effect and Genetic DriftRosalind link: [The Founder Effect and Genetic Drift](http://rosalind.info/problems/foun/)
###Code
# TODO
###Output
_____no_output_____ |
.ipynb_checkpoints/The Annotated Transformer-checkpoint.ipynb | ###Markdown
The Transformer from ["Attention is All You Need"](https://arxiv.org/abs/1706.03762) has been on a lot of people's minds over the last year. Besides producing major improvements in translation quality, it provides a new architecture for many other NLP tasks. The paper itself is very clearly written, but the conventional wisdom has been that it is quite difficult to implement correctly. In this post I present an "annotated" version of the paper in the form of a line-by-line implementation. I have reordered and deleted some sections from the original paper and added comments throughout. This document itself is a working notebook, and should be a completely usable implementation. In total there are 400 lines of library code which can process 27,000 tokens per second on 4 GPUs. To follow along you will first need to install [PyTorch](http://pytorch.org/). The complete notebook is also available on [github](https://github.com/harvardnlp/annotated-transformer) or on Google [Colab](https://drive.google.com/file/d/1xQXSv6mtAOLXxEMi8RvaW8TW-7bvYBDF/view?usp=sharing). Note this is merely a starting point for researchers and interested developers. The code here is based heavily on our [OpenNMT](http://opennmt.net) packages. (If helpful feel free to [cite](conclusion).) For other full-sevice implementations of the model check-out [Tensor2Tensor](https://github.com/tensorflow/tensor2tensor) (tensorflow) and [Sockeye](https://github.com/awslabs/sockeye) (mxnet).- Alexander Rush ([@harvardnlp](https://twitter.com/harvardnlp) or [email protected]) Prelims
###Code
# !pip install http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl numpy matplotlib spacy torchtext seaborn
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math, copy, time
from torch.autograd import Variable
import matplotlib.pyplot as plt
import seaborn
seaborn.set_context(context="talk")
%matplotlib inline
###Output
_____no_output_____
###Markdown
Background The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU, ByteNet and ConvS2S, all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention.Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations. End-to-end memory networks are based on a recurrent attention mechanism instead of sequencealigned recurrence and have been shown to perform well on simple-language question answering andlanguage modeling tasks.To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence aligned RNNs or convolution. Model Architecture Most competitive neural sequence transduction models have an encoder-decoder structure [(cite)](https://arxiv.org/abs/1409.0473). Here, the encoder maps an input sequence of symbol representations $(x_1, ..., x_n)$ to a sequence of continuous representations $\mathbf{z} = (z_1, ..., z_n)$. Given $\mathbf{z}$, the decoder then generates an output sequence $(y_1,...,y_m)$ of symbols one element at a time. At each step the model is auto-regressive [(cite)](https://arxiv.org/abs/1308.0850), consuming the previously generated symbols as additional input when generating the next.
###Code
class EncoderDecoder(nn.Module):
"""
A standard Encoder-Decoder architecture. Base for this and many
other models.
"""
def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):
super(EncoderDecoder, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.src_embed = src_embed
self.tgt_embed = tgt_embed
self.generator = generator
def forward(self, src, tgt, src_mask, tgt_mask):
"Take in and process masked src and target sequences."
return self.decode(self.encode(src, src_mask), src_mask,
tgt, tgt_mask)
def encode(self, src, src_mask):
return self.encoder(self.src_embed(src), src_mask)
def decode(self, memory, src_mask, tgt, tgt_mask):
return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)
class Generator(nn.Module):
"Define standard linear + softmax generation step."
def __init__(self, d_model, vocab):
super(Generator, self).__init__()
self.proj = nn.Linear(d_model, vocab)
def forward(self, x):
return F.log_softmax(self.proj(x), dim=-1)
###Output
_____no_output_____
###Markdown
The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.
###Code
Image(filename='images/ModalNet-21.png')
###Output
_____no_output_____
###Markdown
Encoder and Decoder Stacks EncoderThe encoder is composed of a stack of $N=6$ identical layers.
###Code
def clones(module, N):
"Produce N identical layers."
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
class Encoder(nn.Module):
"Core encoder is a stack of N layers"
def __init__(self, layer, N):
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
"Pass the input (and mask) through each layer in turn."
for layer in self.layers:
x = layer(x, mask)
return self.norm(x)
###Output
_____no_output_____
###Markdown
We employ a residual connection [(cite)](https://arxiv.org/abs/1512.03385) around each of the two sub-layers, followed by layer normalization [(cite)](https://arxiv.org/abs/1607.06450).
###Code
class LayerNorm(nn.Module):
"Construct a layernorm module (See citation for details)."
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
###Output
_____no_output_____
###Markdown
That is, the output of each sub-layer is $\mathrm{LayerNorm}(x + \mathrm{Sublayer}(x))$, where $\mathrm{Sublayer}(x)$ is the function implemented by the sub-layer itself. We apply dropout [(cite)](http://jmlr.org/papers/v15/srivastava14a.html) to the output of each sub-layer, before it is added to the sub-layer input and normalized. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension $d_{\text{model}}=512$.
###Code
class SublayerConnection(nn.Module):
"""
A residual connection followed by a layer norm.
Note for code simplicity the norm is first as opposed to last.
"""
def __init__(self, size, dropout):
super(SublayerConnection, self).__init__()
self.norm = LayerNorm(size)
self.dropout = nn.Dropout(dropout)
def forward(self, x, sublayer):
"Apply residual connection to any sublayer with the same size."
return x + self.dropout(sublayer(self.norm(x)))
###Output
_____no_output_____
###Markdown
Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-wise fully connected feed-forward network.
###Code
class EncoderLayer(nn.Module):
"Encoder is made up of self-attn and feed forward (defined below)"
def __init__(self, size, self_attn, feed_forward, dropout):
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 2)
self.size = size
def forward(self, x, mask):
"Follow Figure 1 (left) for connections."
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward)
###Output
_____no_output_____
###Markdown
DecoderThe decoder is also composed of a stack of $N=6$ identical layers.
###Code
class Decoder(nn.Module):
"Generic N layer decoder with masking."
def __init__(self, layer, N):
super(Decoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, memory, src_mask, tgt_mask):
for layer in self.layers:
x = layer(x, memory, src_mask, tgt_mask)
return self.norm(x)
###Output
_____no_output_____
###Markdown
In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization.
###Code
class DecoderLayer(nn.Module):
"Decoder is made of self-attn, src-attn, and feed forward (defined below)"
def __init__(self, size, self_attn, src_attn, feed_forward, dropout):
super(DecoderLayer, self).__init__()
self.size = size
self.self_attn = self_attn
self.src_attn = src_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 3)
def forward(self, x, memory, src_mask, tgt_mask):
"Follow Figure 1 (right) for connections."
m = memory
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))
x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))
return self.sublayer[2](x, self.feed_forward)
###Output
_____no_output_____
###Markdown
We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position $i$ can depend only on the known outputs at positions less than $i$.
###Code
def subsequent_mask(size):
"Mask out subsequent positions."
attn_shape = (1, size, size)
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
return torch.from_numpy(subsequent_mask) == 0
###Output
_____no_output_____
###Markdown
> Below the attention mask shows the position each tgt word (row) is allowed to look at (column). Words are blocked for attending to future words during training.
###Code
plt.figure(figsize=(5,5))
plt.imshow(subsequent_mask(20)[0])
None
###Output
_____no_output_____
###Markdown
Attention An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key. We call our particular attention "Scaled Dot-Product Attention". The input consists of queries and keys of dimension $d_k$, and values of dimension $d_v$. We compute the dot products of the query with all keys, divide each by $\sqrt{d_k}$, and apply a softmax function to obtain the weights on the values.
###Code
Image(filename='images/ModalNet-19.png')
###Output
_____no_output_____
###Markdown
In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix $Q$. The keys and values are also packed together into matrices $K$ and $V$. We compute the matrix of outputs as: $$ \mathrm{Attention}(Q, K, V) = \mathrm{softmax}(\frac{QK^T}{\sqrt{d_k}})V $$
###Code
def attention(query, key, value, mask=None, dropout=None):
"Compute 'Scaled Dot Product Attention'"
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
p_attn = F.softmax(scores, dim = -1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn, value), p_attn
###Output
_____no_output_____
###Markdown
The two most commonly used attention functions are additive attention [(cite)](https://arxiv.org/abs/1409.0473), and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of $\frac{1}{\sqrt{d_k}}$. Additive attention computes the compatibility function using a feed-forward network with a single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code. While for small values of $d_k$ the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of $d_k$ [(cite)](https://arxiv.org/abs/1703.03906). We suspect that for large values of $d_k$, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients (To illustrate why the dot products get large, assume that the components of $q$ and $k$ are independent random variables with mean $0$ and variance $1$. Then their dot product, $q \cdot k = \sum_{i=1}^{d_k} q_ik_i$, has mean $0$ and variance $d_k$.). To counteract this effect, we scale the dot products by $\frac{1}{\sqrt{d_k}}$.
###Code
Image(filename='images/ModalNet-20.png')
###Output
_____no_output_____
###Markdown
Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this. $$ \mathrm{MultiHead}(Q, K, V) = \mathrm{Concat}(\mathrm{head_1}, ..., \mathrm{head_h})W^O \\ \text{where}~\mathrm{head_i} = \mathrm{Attention}(QW^Q_i, KW^K_i, VW^V_i) $$ Where the projections are parameter matrices $W^Q_i \in \mathbb{R}^{d_{\text{model}} \times d_k}$, $W^K_i \in \mathbb{R}^{d_{\text{model}} \times d_k}$, $W^V_i \in \mathbb{R}^{d_{\text{model}} \times d_v}$ and $W^O \in \mathbb{R}^{hd_v \times d_{\text{model}}}$. In this work we employ $h=8$ parallel attention layers, or heads. For each of these we use $d_k=d_v=d_{\text{model}}/h=64$. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.
###Code
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
"Take in model size and number of heads."
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
# We assume d_v always equals d_k
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
def forward(self, query, key, value, mask=None):
"Implements Figure 2"
if mask is not None:
# Same mask applied to all h heads.
mask = mask.unsqueeze(1)
nbatches = query.size(0)
# 1) Do all the linear projections in batch from d_model => h x d_k
query, key, value = \
[l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for l, x in zip(self.linears, (query, key, value))]
# 2) Apply attention on all the projected vectors in batch.
x, self.attn = attention(query, key, value, mask=mask,
dropout=self.dropout)
# 3) "Concat" using a view and apply a final linear.
x = x.transpose(1, 2).contiguous() \
.view(nbatches, -1, self.h * self.d_k)
return self.linears[-1](x)
###Output
_____no_output_____
###Markdown
Applications of Attention in our Model The Transformer uses multi-head attention in three different ways: 1) In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [(cite)](https://arxiv.org/abs/1609.08144). 2) The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder. 3) Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to $-\infty$) all values in the input of the softmax which correspond to illegal connections. Position-wise Feed-Forward Networks In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.$$\mathrm{FFN}(x)=\max(0, xW_1 + b_1) W_2 + b_2$$ While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is $d_{\text{model}}=512$, and the inner-layer has dimensionality $d_{ff}=2048$.
###Code
class PositionwiseFeedForward(nn.Module):
"Implements FFN equation."
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.w_2(self.dropout(F.relu(self.w_1(x))))
###Output
_____no_output_____
###Markdown
Embeddings and Softmax Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension $d_{\text{model}}$. We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [(cite)](https://arxiv.org/abs/1608.05859). In the embedding layers, we multiply those weights by $\sqrt{d_{\text{model}}}$.
###Code
class Embeddings(nn.Module):
def __init__(self, d_model, vocab):
super(Embeddings, self).__init__()
self.lut = nn.Embedding(vocab, d_model)
self.d_model = d_model
def forward(self, x):
return self.lut(x) * math.sqrt(self.d_model)
###Output
_____no_output_____
###Markdown
Positional Encoding Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension $d_{\text{model}}$ as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [(cite)](https://arxiv.org/pdf/1705.03122.pdf). In this work, we use sine and cosine functions of different frequencies: $$PE_{(pos,2i)} = sin(pos / 10000^{2i/d_{\text{model}}})$$$$PE_{(pos,2i+1)} = cos(pos / 10000^{2i/d_{\text{model}}})$$ where $pos$ is the position and $i$ is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from $2\pi$ to $10000 \cdot 2\pi$. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset $k$, $PE_{pos+k}$ can be represented as a linear function of $PE_{pos}$. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of $P_{drop}=0.1$.
###Code
class PositionalEncoding(nn.Module):
"Implement the PE function."
def __init__(self, d_model, dropout, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
# Compute the positional encodings once in log space.
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2) *
-(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
x = x + Variable(self.pe[:, :x.size(1)],
requires_grad=False)
return self.dropout(x)
###Output
_____no_output_____
###Markdown
> Below the positional encoding will add in a sine wave based on position. The frequency and offset of the wave is different for each dimension.
###Code
plt.figure(figsize=(15, 5))
pe = PositionalEncoding(20, 0)
y = pe.forward(Variable(torch.zeros(1, 100, 20)))
plt.plot(np.arange(100), y[0, :, 4:8].data.numpy())
plt.legend(["dim %d"%p for p in [4,5,6,7]])
None
###Output
_____no_output_____
###Markdown
We also experimented with using learned positional embeddings [(cite)](https://arxiv.org/pdf/1705.03122.pdf) instead, and found that the two versions produced nearly identical results. We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training. Full Model> Here we define a function from hyperparameters to a full model.
###Code
def make_model(src_vocab, tgt_vocab, N=6,
d_model=512, d_ff=2048, h=8, dropout=0.1):
"Helper: Construct a model from hyperparameters."
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
position = PositionalEncoding(d_model, dropout)
model = EncoderDecoder(
Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),
Decoder(DecoderLayer(d_model, c(attn), c(attn),
c(ff), dropout), N),
nn.Sequential(Embeddings(d_model, src_vocab), c(position)),
nn.Sequential(Embeddings(d_model, tgt_vocab), c(position)),
Generator(d_model, tgt_vocab))
# This was important from their code.
# Initialize parameters with Glorot / fan_avg.
for p in model.parameters():
if p.dim() > 1:
nn.init.xavier_uniform(p)
return model
# Small example model.
tmp_model = make_model(10, 10, 2)
None
###Output
_____no_output_____
###Markdown
TrainingThis section describes the training regime for our models. > We stop for a quick interlude to introduce some of the tools needed to train a standard encoder decoder model. First we define a batch object that holds the src and target sentences for training, as well as constructing the masks. Batches and Masking
###Code
class Batch:
"Object for holding a batch of data with mask during training."
def __init__(self, src, trg=None, pad=0):
self.src = src
self.src_mask = (src != pad).unsqueeze(-2)
if trg is not None:
self.trg = trg[:, :-1]
self.trg_y = trg[:, 1:]
self.trg_mask = \
self.make_std_mask(self.trg, pad)
self.ntokens = (self.trg_y != pad).data.sum()
@staticmethod
def make_std_mask(tgt, pad):
"Create a mask to hide padding and future words."
tgt_mask = (tgt != pad).unsqueeze(-2)
tgt_mask = tgt_mask & Variable(
subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data))
return tgt_mask
###Output
_____no_output_____
###Markdown
> Next we create a generic training and scoring function to keep track of loss. We pass in a generic loss compute function that also handles parameter updates. Training Loop
###Code
def run_epoch(data_iter, model, loss_compute):
"Standard Training and Logging Function"
start = time.time()
total_tokens = 0
total_loss = 0
tokens = 0
for i, batch in enumerate(data_iter):
out = model.forward(batch.src, batch.trg,
batch.src_mask, batch.trg_mask)
loss = loss_compute(out, batch.trg_y, batch.ntokens)
total_loss += loss
total_tokens += batch.ntokens
tokens += batch.ntokens
if i % 50 == 1:
elapsed = time.time() - start
print("Epoch Step: %d Loss: %f Tokens per Sec: %f" %
(i, loss / batch.ntokens, tokens / elapsed))
start = time.time()
tokens = 0
return total_loss / total_tokens
###Output
_____no_output_____
###Markdown
Training Data and BatchingWe trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding, which has a shared source-target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary.Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens. > We will use torch text for batching. This is discussed in more detail below. Here we create batches in a torchtext function that ensures our batch size padded to the maximum batchsize does not surpass a threshold (25000 if we have 8 gpus).
###Code
global max_src_in_batch, max_tgt_in_batch
def batch_size_fn(new, count, sofar):
"Keep augmenting batch and calculate total number of tokens + padding."
global max_src_in_batch, max_tgt_in_batch
if count == 1:
max_src_in_batch = 0
max_tgt_in_batch = 0
max_src_in_batch = max(max_src_in_batch, len(new.src))
max_tgt_in_batch = max(max_tgt_in_batch, len(new.trg) + 2)
src_elements = count * max_src_in_batch
tgt_elements = count * max_tgt_in_batch
return max(src_elements, tgt_elements)
###Output
_____no_output_____
###Markdown
Hardware and Schedule We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models, step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days). OptimizerWe used the Adam optimizer [(cite)](https://arxiv.org/abs/1412.6980) with $\beta_1=0.9$, $\beta_2=0.98$ and $\epsilon=10^{-9}$. We varied the learning rate over the course of training, according to the formula: $$ lrate = d_{\text{model}}^{-0.5} \cdot \min({step\_num}^{-0.5}, {step\_num} \cdot {warmup\_steps}^{-1.5}) $$ This corresponds to increasing the learning rate linearly for the first $warmup\_steps$ training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used $warmup\_steps=4000$. > Note: This part is very important. Need to train with this setup of the model.
###Code
class NoamOpt:
"Optim wrapper that implements rate."
def __init__(self, model_size, factor, warmup, optimizer):
self.optimizer = optimizer
self._step = 0
self.warmup = warmup
self.factor = factor
self.model_size = model_size
self._rate = 0
def step(self):
"Update parameters and rate"
self._step += 1
rate = self.rate()
for p in self.optimizer.param_groups:
p['lr'] = rate
self._rate = rate
self.optimizer.step()
def rate(self, step = None):
"Implement `lrate` above"
if step is None:
step = self._step
return self.factor * \
(self.model_size ** (-0.5) *
min(step ** (-0.5), step * self.warmup ** (-1.5)))
def get_std_opt(model):
return NoamOpt(model.src_embed[0].d_model, 2, 4000,
torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))
###Output
_____no_output_____
###Markdown
> Example of the curves of this model for different model sizes and for optimization hyperparameters.
###Code
# Three settings of the lrate hyperparameters.
opts = [NoamOpt(512, 1, 4000, None),
NoamOpt(512, 1, 8000, None),
NoamOpt(256, 1, 4000, None)]
plt.plot(np.arange(1, 20000), [[opt.rate(i) for opt in opts] for i in range(1, 20000)])
plt.legend(["512:4000", "512:8000", "256:4000"])
None
###Output
_____no_output_____
###Markdown
Regularization Label SmoothingDuring training, we employed label smoothing of value $\epsilon_{ls}=0.1$ [(cite)](https://arxiv.org/abs/1512.00567). This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score. > We implement label smoothing using the KL div loss. Instead of using a one-hot target distribution, we create a distribution that has `confidence` of the correct word and the rest of the `smoothing` mass distributed throughout the vocabulary.
###Code
class LabelSmoothing(nn.Module):
"Implement label smoothing."
def __init__(self, size, padding_idx, smoothing=0.0):
super(LabelSmoothing, self).__init__()
self.criterion = nn.KLDivLoss(size_average=False)
self.padding_idx = padding_idx
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.size = size
self.true_dist = None
def forward(self, x, target):
assert x.size(1) == self.size
true_dist = x.data.clone()
true_dist.fill_(self.smoothing / (self.size - 2))
true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)
true_dist[:, self.padding_idx] = 0
mask = torch.nonzero(target.data == self.padding_idx)
if mask.dim() > 0:
true_dist.index_fill_(0, mask.squeeze(), 0.0)
self.true_dist = true_dist
return self.criterion(x, Variable(true_dist, requires_grad=False))
###Output
_____no_output_____
###Markdown
> Here we can see an example of how the mass is distributed to the words based on confidence.
###Code
#Example of label smoothing.
crit = LabelSmoothing(5, 0, 0.4)
predict = torch.FloatTensor([[0, 0.2, 0.7, 0.1, 0],
[0, 0.2, 0.7, 0.1, 0],
[0, 0.2, 0.7, 0.1, 0]])
v = crit(Variable(predict.log()),
Variable(torch.LongTensor([2, 1, 0])))
# Show the target distributions expected by the system.
plt.imshow(crit.true_dist)
None
###Output
_____no_output_____
###Markdown
> Label smoothing actually starts to penalize the model if it gets very confident about a given choice.
###Code
crit = LabelSmoothing(5, 0, 0.1)
def loss(x):
d = x + 3 * 1
predict = torch.FloatTensor([[0, x / d, 1 / d, 1 / d, 1 / d],
])
#print(predict)
return crit(Variable(predict.log()),
Variable(torch.LongTensor([1]))).data[0]
plt.plot(np.arange(1, 100), [loss(x) for x in range(1, 100)])
None
###Output
_____no_output_____
###Markdown
A First Example> We can begin by trying out a simple copy-task. Given a random set of input symbols from a small vocabulary, the goal is to generate back those same symbols. Synthetic Data
###Code
def data_gen(V, batch, nbatches):
"Generate random data for a src-tgt copy task."
for i in range(nbatches):
data = torch.from_numpy(np.random.randint(1, V, size=(batch, 10)))
data[:, 0] = 1
src = Variable(data, requires_grad=False)
tgt = Variable(data, requires_grad=False)
yield Batch(src, tgt, 0)
###Output
_____no_output_____
###Markdown
Loss Computation
###Code
class SimpleLossCompute:
"A simple loss compute and train function."
def __init__(self, generator, criterion, opt=None):
self.generator = generator
self.criterion = criterion
self.opt = opt
def __call__(self, x, y, norm):
x = self.generator(x)
loss = self.criterion(x.contiguous().view(-1, x.size(-1)),
y.contiguous().view(-1)) / norm
loss.backward()
if self.opt is not None:
self.opt.step()
self.opt.optimizer.zero_grad()
return loss.data[0] * norm
###Output
_____no_output_____
###Markdown
Greedy Decoding
###Code
# Train the simple copy task.
V = 11
criterion = LabelSmoothing(size=V, padding_idx=0, smoothing=0.0)
model = make_model(V, V, N=2)
model_opt = NoamOpt(model.src_embed[0].d_model, 1, 400,
torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))
for epoch in range(10):
model.train()
run_epoch(data_gen(V, 30, 20), model,
SimpleLossCompute(model.generator, criterion, model_opt))
model.eval()
print(run_epoch(data_gen(V, 30, 5), model,
SimpleLossCompute(model.generator, criterion, None)))
###Output
Epoch Step: 1 Loss: 3.023465 Tokens per Sec: 403.074173
Epoch Step: 1 Loss: 1.920030 Tokens per Sec: 641.689380
1.9274832487106324
Epoch Step: 1 Loss: 1.940011 Tokens per Sec: 432.003378
Epoch Step: 1 Loss: 1.699767 Tokens per Sec: 641.979665
1.657595729827881
Epoch Step: 1 Loss: 1.860276 Tokens per Sec: 433.320240
Epoch Step: 1 Loss: 1.546011 Tokens per Sec: 640.537198
1.4888023376464843
Epoch Step: 1 Loss: 1.682198 Tokens per Sec: 432.092305
Epoch Step: 1 Loss: 1.313169 Tokens per Sec: 639.441857
1.3485562801361084
Epoch Step: 1 Loss: 1.278768 Tokens per Sec: 433.568756
Epoch Step: 1 Loss: 1.062384 Tokens per Sec: 642.542067
0.9853351473808288
Epoch Step: 1 Loss: 1.269471 Tokens per Sec: 433.388727
Epoch Step: 1 Loss: 0.590709 Tokens per Sec: 642.862135
0.5686767101287842
Epoch Step: 1 Loss: 0.997076 Tokens per Sec: 433.009746
Epoch Step: 1 Loss: 0.343118 Tokens per Sec: 642.288427
0.34273059368133546
Epoch Step: 1 Loss: 0.459483 Tokens per Sec: 434.594030
Epoch Step: 1 Loss: 0.290385 Tokens per Sec: 642.519464
0.2612409472465515
Epoch Step: 1 Loss: 1.031042 Tokens per Sec: 434.557008
Epoch Step: 1 Loss: 0.437069 Tokens per Sec: 643.630322
0.4323212027549744
Epoch Step: 1 Loss: 0.617165 Tokens per Sec: 436.652626
Epoch Step: 1 Loss: 0.258793 Tokens per Sec: 644.372296
0.27331129014492034
###Markdown
> This code predicts a translation using greedy decoding for simplicity.
###Code
def greedy_decode(model, src, src_mask, max_len, start_symbol):
memory = model.encode(src, src_mask)
ys = torch.ones(1, 1).fill_(start_symbol).type_as(src.data)
for i in range(max_len-1):
out = model.decode(memory, src_mask,
Variable(ys),
Variable(subsequent_mask(ys.size(1))
.type_as(src.data)))
prob = model.generator(out[:, -1])
_, next_word = torch.max(prob, dim = 1)
next_word = next_word.data[0]
ys = torch.cat([ys,
torch.ones(1, 1).type_as(src.data).fill_(next_word)], dim=1)
return ys
model.eval()
src = Variable(torch.LongTensor([[1,2,3,4,5,6,7,8,9,10]]) )
src_mask = Variable(torch.ones(1, 1, 10) )
print(greedy_decode(model, src, src_mask, max_len=10, start_symbol=1))
###Output
1 2 3 4 5 6 7 8 9 10
[torch.LongTensor of size 1x10]
###Markdown
A Real World Example> Now we consider a real-world example using the IWSLT German-English Translation task. This task is much smaller than the WMT task considered in the paper, but it illustrates the whole system. We also show how to use multi-gpu processing to make it really fast.
###Code
#!pip install torchtext spacy
#!python -m spacy download en
#!python -m spacy download de
###Output
_____no_output_____
###Markdown
Data Loading> We will load the dataset using torchtext and spacy for tokenization.
###Code
# For data loading.
from torchtext import data, datasets
if True:
import spacy
spacy_de = spacy.load('de')
spacy_en = spacy.load('en')
def tokenize_de(text):
return [tok.text for tok in spacy_de.tokenizer(text)]
def tokenize_en(text):
return [tok.text for tok in spacy_en.tokenizer(text)]
BOS_WORD = '<s>'
EOS_WORD = '</s>'
BLANK_WORD = "<blank>"
SRC = data.Field(tokenize=tokenize_de, pad_token=BLANK_WORD)
TGT = data.Field(tokenize=tokenize_en, init_token = BOS_WORD,
eos_token = EOS_WORD, pad_token=BLANK_WORD)
MAX_LEN = 100
train, val, test = datasets.IWSLT.splits(
exts=('.de', '.en'), fields=(SRC, TGT),
filter_pred=lambda x: len(vars(x)['src']) <= MAX_LEN and
len(vars(x)['trg']) <= MAX_LEN)
MIN_FREQ = 2
SRC.build_vocab(train.src, min_freq=MIN_FREQ)
TGT.build_vocab(train.trg, min_freq=MIN_FREQ)
###Output
_____no_output_____
###Markdown
> Batching matters a ton for speed. We want to have very evenly divided batches, with absolutely minimal padding. To do this we have to hack a bit around the default torchtext batching. This code patches their default batching to make sure we search over enough sentences to find tight batches. Iterators
###Code
class MyIterator(data.Iterator):
def create_batches(self):
if self.train:
def pool(d, random_shuffler):
for p in data.batch(d, self.batch_size * 100):
p_batch = data.batch(
sorted(p, key=self.sort_key),
self.batch_size, self.batch_size_fn)
for b in random_shuffler(list(p_batch)):
yield b
self.batches = pool(self.data(), self.random_shuffler)
else:
self.batches = []
for b in data.batch(self.data(), self.batch_size,
self.batch_size_fn):
self.batches.append(sorted(b, key=self.sort_key))
def rebatch(pad_idx, batch):
"Fix order in torchtext to match ours"
src, trg = batch.src.transpose(0, 1), batch.trg.transpose(0, 1)
return Batch(src, trg, pad_idx)
###Output
_____no_output_____
###Markdown
Multi-GPU Training> Finally to really target fast training, we will use multi-gpu. This code implements multi-gpu word generation. It is not specific to transformer so I won't go into too much detail. The idea is to split up word generation at training time into chunks to be processed in parallel across many different gpus. We do this using pytorch parallel primitives:* replicate - split modules onto different gpus.* scatter - split batches onto different gpus* parallel_apply - apply module to batches on different gpus* gather - pull scattered data back onto one gpu. * nn.DataParallel - a special module wrapper that calls these all before evaluating.
###Code
# Skip if not interested in multigpu.
class MultiGPULossCompute:
"A multi-gpu loss compute and train function."
def __init__(self, generator, criterion, devices, opt=None, chunk_size=5):
# Send out to different gpus.
self.generator = generator
self.criterion = nn.parallel.replicate(criterion,
devices=devices)
self.opt = opt
self.devices = devices
self.chunk_size = chunk_size
def __call__(self, out, targets, normalize):
total = 0.0
generator = nn.parallel.replicate(self.generator,
devices=self.devices)
out_scatter = nn.parallel.scatter(out,
target_gpus=self.devices)
out_grad = [[] for _ in out_scatter]
targets = nn.parallel.scatter(targets,
target_gpus=self.devices)
# Divide generating into chunks.
chunk_size = self.chunk_size
for i in range(0, out_scatter[0].size(1), chunk_size):
# Predict distributions
out_column = [[Variable(o[:, i:i+chunk_size].data,
requires_grad=self.opt is not None)]
for o in out_scatter]
gen = nn.parallel.parallel_apply(generator, out_column)
# Compute loss.
y = [(g.contiguous().view(-1, g.size(-1)),
t[:, i:i+chunk_size].contiguous().view(-1))
for g, t in zip(gen, targets)]
loss = nn.parallel.parallel_apply(self.criterion, y)
# Sum and normalize loss
l = nn.parallel.gather(loss,
target_device=self.devices[0])
l = l.sum()[0] / normalize
total += l.data[0]
# Backprop loss to output of transformer
if self.opt is not None:
l.backward()
for j, l in enumerate(loss):
out_grad[j].append(out_column[j][0].grad.data.clone())
# Backprop all loss through transformer.
if self.opt is not None:
out_grad = [Variable(torch.cat(og, dim=1)) for og in out_grad]
o1 = out
o2 = nn.parallel.gather(out_grad,
target_device=self.devices[0])
o1.backward(gradient=o2)
self.opt.step()
self.opt.optimizer.zero_grad()
return total * normalize
###Output
_____no_output_____
###Markdown
> Now we create our model, criterion, optimizer, data iterators, and paralelization
###Code
# GPUs to use
devices = [0, 1, 2, 3]
if True:
pad_idx = TGT.vocab.stoi["<blank>"]
model = make_model(len(SRC.vocab), len(TGT.vocab), N=6)
model.cuda()
criterion = LabelSmoothing(size=len(TGT.vocab), padding_idx=pad_idx, smoothing=0.1)
criterion.cuda()
BATCH_SIZE = 12000
train_iter = MyIterator(train, batch_size=BATCH_SIZE, device=0,
repeat=False, sort_key=lambda x: (len(x.src), len(x.trg)),
batch_size_fn=batch_size_fn, train=True)
valid_iter = MyIterator(val, batch_size=BATCH_SIZE, device=0,
repeat=False, sort_key=lambda x: (len(x.src), len(x.trg)),
batch_size_fn=batch_size_fn, train=False)
model_par = nn.DataParallel(model, device_ids=devices)
None
###Output
_____no_output_____
###Markdown
> Now we train the model. I will play with the warmup steps a bit, but everything else uses the default parameters. On an AWS p3.8xlarge with 4 Tesla V100s, this runs at ~27,000 tokens per second with a batch size of 12,000 Training the System
###Code
#!wget https://s3.amazonaws.com/opennmt-models/iwslt.pt
if False:
model_opt = NoamOpt(model.src_embed[0].d_model, 1, 2000,
torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))
for epoch in range(10):
model_par.train()
run_epoch((rebatch(pad_idx, b) for b in train_iter),
model_par,
MultiGPULossCompute(model.generator, criterion,
devices=devices, opt=model_opt))
model_par.eval()
loss = run_epoch((rebatch(pad_idx, b) for b in valid_iter),
model_par,
MultiGPULossCompute(model.generator, criterion,
devices=devices, opt=None))
print(loss)
else:
model = torch.load("iwslt.pt")
###Output
_____no_output_____
###Markdown
> Once trained we can decode the model to produce a set of translations. Here we simply translate the first sentence in the validation set. This dataset is pretty small so the translations with greedy search are reasonably accurate.
###Code
for i, batch in enumerate(valid_iter):
src = batch.src.transpose(0, 1)[:1]
src_mask = (src != SRC.vocab.stoi["<blank>"]).unsqueeze(-2)
out = greedy_decode(model, src, src_mask,
max_len=60, start_symbol=TGT.vocab.stoi["<s>"])
print("Translation:", end="\t")
for i in range(1, out.size(1)):
sym = TGT.vocab.itos[out[0, i]]
if sym == "</s>": break
print(sym, end =" ")
print()
print("Target:", end="\t")
for i in range(1, batch.trg.size(0)):
sym = TGT.vocab.itos[batch.trg.data[i, 0]]
if sym == "</s>": break
print(sym, end =" ")
print()
break
###Output
Translation: <unk> <unk> . In my language , that means , thank you very much .
Target: <unk> <unk> . It means in my language , thank you very much .
###Markdown
Additional Components: BPE, Search, Averaging > So this mostly covers the transformer model itself. There are four aspects that we didn't cover explicitly. We also have all these additional features implemented in [OpenNMT-py](https://github.com/opennmt/opennmt-py). > 1) BPE/ Word-piece: We can use a library to first preprocess the data into subword units. See Rico Sennrich's [subword-nmt](https://github.com/rsennrich/subword-nmt) implementation. These models will transform the training data to look like this: ▁Die ▁Protokoll datei ▁kann ▁ heimlich ▁per ▁E - Mail ▁oder ▁FTP ▁an ▁einen ▁bestimmte n ▁Empfänger ▁gesendet ▁werden . > 2) Shared Embeddings: When using BPE with shared vocabulary we can share the same weight vectors between the source / target / generator. See the [(cite)](https://arxiv.org/abs/1608.05859) for details. To add this to the model simply do this:
###Code
if False:
model.src_embed[0].lut.weight = model.tgt_embeddings[0].lut.weight
model.generator.lut.weight = model.tgt_embed[0].lut.weight
###Output
_____no_output_____
###Markdown
> 3) Beam Search: This is a bit too complicated to cover here. See the [OpenNMT-py](https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/translate/Beam.py) for a pytorch implementation. > 4) Model Averaging: The paper averages the last k checkpoints to create an ensembling effect. We can do this after the fact if we have a bunch of models:
###Code
def average(model, models):
"Average models into model"
for ps in zip(*[m.params() for m in [model] + models]):
p[0].copy_(torch.sum(*ps[1:]) / len(ps[1:]))
###Output
_____no_output_____
###Markdown
ResultsOn the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big)in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model islisted in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base modelsurpasses all previously published models and ensembles, at a fraction of the training cost of any ofthe competitive models.On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0,outperforming all of the previously published single models, at less than 1/4 the training cost of theprevious state-of-the-art model. The Transformer (big) model trained for English-to-French useddropout rate Pdrop = 0.1, instead of 0.3.
###Code
Image(filename="images/results.png")
###Output
_____no_output_____
###Markdown
> The code we have written here is a version of the base model. There are fully trained version of this system available here [(Example Models)](http://opennmt.net/Models-py/).>> With the addtional extensions in the last section, the OpenNMT-py replication gets to 26.9 on EN-DE WMT. Here I have loaded in those parameters to our reimplemenation.
###Code
!wget https://s3.amazonaws.com/opennmt-models/en-de-model.pt
model, SRC, TGT = torch.load("en-de-model.pt")
model.eval()
sent = "▁The ▁log ▁file ▁can ▁be ▁sent ▁secret ly ▁with ▁email ▁or ▁FTP ▁to ▁a ▁specified ▁receiver".split()
src = torch.LongTensor([[SRC.stoi[w] for w in sent]])
src = Variable(src)
src_mask = (src != SRC.stoi["<blank>"]).unsqueeze(-2)
out = greedy_decode(model, src, src_mask,
max_len=60, start_symbol=TGT.stoi["<s>"])
print("Translation:", end="\t")
trans = "<s> "
for i in range(1, out.size(1)):
sym = TGT.itos[out[0, i]]
if sym == "</s>": break
trans += sym + " "
print(trans)
###Output
Translation: <s> ▁Die ▁Protokoll datei ▁kann ▁ heimlich ▁per ▁E - Mail ▁oder ▁FTP ▁an ▁einen ▁bestimmte n ▁Empfänger ▁gesendet ▁werden .
###Markdown
Attention Visualization> Even with a greedy decoder the translation looks pretty good. We can further visualize it to see what is happening at each layer of the attention
###Code
tgt_sent = trans.split()
def draw(data, x, y, ax):
seaborn.heatmap(data,
xticklabels=x, square=True, yticklabels=y, vmin=0.0, vmax=1.0,
cbar=False, ax=ax)
for layer in range(1, 6, 2):
fig, axs = plt.subplots(1,4, figsize=(20, 10))
print("Encoder Layer", layer+1)
for h in range(4):
draw(model.encoder.layers[layer].self_attn.attn[0, h].data,
sent, sent if h ==0 else [], ax=axs[h])
plt.show()
for layer in range(1, 6, 2):
fig, axs = plt.subplots(1,4, figsize=(20, 10))
print("Decoder Self Layer", layer+1)
for h in range(4):
draw(model.decoder.layers[layer].self_attn.attn[0, h].data[:len(tgt_sent), :len(tgt_sent)],
tgt_sent, tgt_sent if h ==0 else [], ax=axs[h])
plt.show()
print("Decoder Src Layer", layer+1)
fig, axs = plt.subplots(1,4, figsize=(20, 10))
for h in range(4):
draw(model.decoder.layers[layer].self_attn.attn[0, h].data[:len(tgt_sent), :len(sent)],
sent, tgt_sent if h ==0 else [], ax=axs[h])
plt.show()
###Output
Encoder Layer 2
|
online-nets/.ipynb_aml_checkpoints/online-nets-checkpoint2021-11-20-23-2-26Z.ipynb | ###Markdown
online nets
Deep learning is powerful but computationally expensive, frequently requiring massive compute budgets. In persuit of cost-effective-yet-powerful AI, this work explores and evaluates a heuristic which should lend to more-efficient use of data through online learning.
Goal: evaluate a deep learning alternative capable of true online learning. Solution requirements:
1. catastrophic forgetting should be impossible;
2. all data is integrated into sufficient statistics of fixed dimension;
3. and our solution should have predictive power comparable to deep learning.
modeling strategy
We will not attempt to derive sufficient statistics for an entire deep net, but instead leverage well-known sufficient statistics for least squares models,
so will have sufficient statistics per deep net layer. If this can be empirically shown effective, we'll build-out the theory afterwards.
Recognizing a deep net as a series of compositions, as follows.
$ Y + \varepsilon \approx \mathbb{E}Y = \sigma_3 \circ \beta_3^T \circ \sigma_2 \circ \beta_2^T \circ \sigma_1 \circ \beta_1^T X $
So, we can isolate invidivdual $\beta_j$ matrices using (psuedo-)inverses $\beta_j^{-1}$ like so.
$ \sigma_2^{-1} \circ \beta_3^{-1} \circ \sigma_3^{-1} (Y) \approx \beta_2^T \circ \sigma_1 \circ \beta_1^T X $
In this example, if we freeze all $\beta_j$'s except $\beta_2$, we are free to update $\hat \beta_2$ using $\tilde Y = \sigma_2^{-1} \circ \beta_3^{-1} \circ \sigma_3^{-1} (Y) $
and $\tilde X = \sigma_1 \circ \beta_1^T X $.
Using a least squares formulation for fitting to $\left( \tilde X, \tilde Y \right)$, we get sufficient statistics per layer. model code definitions
###Code
import torch
TORCH_TENSOR_TYPE = type(torch.tensor(1))
class OnlineDenseLayer:
'''
A single dense net, formulated as a least squares model.
'''
def __init__(self, p, q, activation=lambda x:x, activation_inverse=lambda x:x, lam=1.):
'''
inputs:
- p: input dimension
- q: output dimension
- activation: non-linear function, from R^p to R^q. Default is identity
- activation_inverse: inverse of the activation function. Default is identity.
- lam: regularization term
'''
self.__validate_inputs(p=p, q=q, lam=lam)
self.p = p
self.q = q
self.activation = activation
self.activation_inverse = activation_inverse
self.lam = lam
self.xTy = torch.zeros(p+1,q) # +1 for intercept
self.yTx = torch.zeros(q+1,p)
self.xTx_inv = torch.diag(torch.tensor([lam]*(p+1)))
self.yTy_inv = torch.diag(torch.tensor([lam]*(q+1)))
self.betaT_forward = torch.matmul(self.xTx_inv, self.xTy)
self.betaT_forward = torch.transpose(self.betaT_forward, 0, 1)
self.betaT_backward = torch.matmul(self.yTy_inv, self.yTx)
self.betaT_backward = torch.transpose(self.betaT_backward, 0, 1)
self.x_forward = None
self.y_forward = None
self.x_backward = None
self.y_backward = None
pass
def forward(self, x):
'creates and stores x_forward and y_forward, then returns activation(y_forward)'
self.__validate_inputs(x=x, p=self.p)
self.x_forward = x
x = torch.cat((torch.tensor([[1.]]), x), dim=0) # intercept
self.y_forward = torch.matmul(self.betaT_forward, x) # predict
return self.activation(self.y_forward)
def backward(self, y):
'creates and stores x_backward and y_backward, then returns y_backward'
y = self.activation_inverse(y)
self.__validate_inputs(y=y, q=self.q)
self.y_backward = y
y = torch.cat((torch.tensor([[1.]]), y), dim=0)
self.x_backward = torch.matmul(self.betaT_backward, y)
return self.x_backward
def forward_fit(self):
'uses x_forward and y_backward to update forward model, then returns Sherman Morrison denominator'
self.__validate_inputs(x=self.x_forward, y=self.y_backward, p=self.p, q=self.q)
x = torch.cat((torch.tensor([[1.]]), self.x_forward), dim=0)
self.xTx_inv, sm_denom = self.__sherman_morrison(self.xTx_inv, x, x)
self.xTy += torch.matmul(x, torch.transpose(self.y_backward, 0, 1))
self.betaT_forward = torch.matmul(self.xTx_inv, self.xTy)
self.betaT_forward = torch.transpose(self.betaT_forward, 0, 1)
return sm_denom
def backward_fit(self):
'uses x_backward and y_forward to update backward model, then returns Sherman Morrison denominator'
self.__validate_inputs(x=self.x_forward, y=self.y_backward, p=self.p, q=self.q)
y = torch.cat((torch.tensor([[1.]]), self.y_backward), dim=0)
self.yTy_inv, sm_denom = self.__sherman_morrison(self.yTy_inv, y, y)
self.yTx += torch.matmul(y, torch.transpose(self.x_backward, 0, 1))
self.betaT_backward = torch.matmul(self.yTy_inv, self.yTx)
self.betaT_backward = torch.transpose(self.betaT_backward, 0, 1)
return sm_denom
def __sherman_morrison(self, inv_mat, vec1, vec2):
'''
applies Sherman Morrison updates, (mat + vec1 vec2^T)^{-1}
inputs:
- inv_mat: an inverted matrix
- vec1: a column vector
- vec2: a column vector
returns:
- updated matrix
- the Sherman Morrison denominator, for tracking numerical stability
'''
v2t = torch.transpose(vec2, 0, 1)
denominator = 1. + torch.matmul(torch.matmul(v2t, inv_mat), vec1)
numerator = torch.matmul(torch.matmul(inv_mat, vec1), torch.matmul(v2t, inv_mat))
updated_inv_mat = inv_mat - numerator / denominator
return updated_inv_mat, float(denominator)
def __validate_inputs(self, p=None, q=None, lam=None, x=None, y=None):
'raises value exceptions if provided parameters are invalid'
if q is not None:
if not isinstance(q, int):
raise ValueError('`q` must be int!')
if q <= 0:
raise ValueError('`q` must be greater than zero!')
if p is not None:
if not isinstance(p, int):
raise ValueError('`p` must be int!')
if p <= 0:
raise ValueError('`p` must be greater than zero!')
if lam is not None:
if not (isinstance(lam, float) or isinstance(lam, int)):
raise ValueError('`lam` must be float or int!')
if lam < 0:
raise ValueError('`lam` must be non-negative!')
if x is not None and p is not None:
if type(x) != TORCH_TENSOR_TYPE:
raise ValueError('`x` must be of type `torch.tensor`!')
if list(x.shape) != [p,1]:
raise ValueError('`x.shape` must be `[p,1]`!')
if torch.isnan(x).any():
raise ValueError('`x` contains `nan`!')
pass
if y is not None and q is not None:
if type(y) != TORCH_TENSOR_TYPE:
raise ValueError('`y` must be of type `torch.tensor`!')
if list(y.shape) != [q,1]:
raise ValueError('`y.shape` must be `[q,1]`')
if torch.isnan(y).any():
raise ValueError('`y` contains `nan`!')
pass
pass
pass
class OnlineNet:
'online, sequential dense net'
def __init__(self, layer_list):
## validate inputs
if type(layer_list) != list:
raise ValueError('`layer_list` must be of type list!')
for layer in layer_list:
if not issubclass(type(layer), OnlineDenseLayer):
raise ValueError('each item in `layer_list` must be an instance of a subclass of `OnlineDenseLayer`!')
## assign
self.layer_list = layer_list
pass
def forward(self, x):
'predict forward'
for layer in self.layer_list:
x = layer.forward(x)
return x
def backward(self, y):
'predict backward'
for layer in reversed(self.layer_list):
y = layer.backward(y)
return y
def fit(self):
'assumes layers x & y targets have already been set. Returns Sherman Morrison denominators per layer in (forward, backward) pairs in a list'
sherman_morrison_denominator_list = []
for layer in self.layer_list:
forward_smd = layer.forward_fit()
backward_smd = layer.backward_fit()
sherman_morrison_denominator_list.append((forward_smd, backward_smd))
return sherman_morrison_denominator_list
def __reduce_sherman_morrison_denominator_list(self, smd_pair_list):
'returns the value closest to zero'
if type(smd_pair_list) != list:
raise ValueError('`smd_pair_list` must be of type `list`!')
if len(smd_pair_list) == 0:
return None
smallest_smd = None
for smd_pair in smd_pair_list:
if type(smd_pair) != tuple:
raise ValueError('`smd_pair_list` must be list of tuples!')
if smallest_smd is None:
smallest_smd = smd_pair[0]
if abs(smallest_smd) > abs(smd_pair[0]):
smallest_smd = smd_pair[0]
if abs(smallest_smd) > abs(smd_pair[1]):
smallest_smd = smd_pair[1]
return float(smallest_smd)
def __call__(self, x, y=None):
'''
If only x is given, a prediction is made and returned.
If x and y are given, then the model is updated, and returns
- the prediction
- the sherman morrison denominator closest to zero, for tracking numerical stability
'''
y_hat = self.forward(x)
if y is None:
return y_hat
self.backward(y)
self.layer_list[0].x_forward = x
self.layer_list[0].x_backward = x
self.layer_list[-1].y_forward = y
self.layer_list[-1].y_backward = y
smd_pair_list = self.fit()
smallest_smd = self.__reduce_sherman_morrison_denominator_list(smd_pair_list)
return y_hat, smallest_smd
###Output
_____no_output_____
###Markdown
first experiment: mnist classification
###Code
from tqdm import tqdm
from torchvision import datasets, transforms
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
dataset1 = datasets.MNIST('../../data', train=True, download=True, transform=transform)
dataset2 = datasets.MNIST('../../data', train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1)
test_loader = torch.utils.data.DataLoader(dataset2)
n_labels = 10
## activation functions
## torch.sigmoid
inv_sigmoid = lambda x: -torch.log((1/(x+1e-8))-1)
leaky_relu_alpha = .1
leaky_relu = lambda x: (x > 0)*x + (x <= 0)*x*leaky_relu_alpha
inv_leaky_relu = lambda x: (x > 0)*x + (x <= 0)*x/leaky_relu_alpha
model = OnlineNet(
[
#OnlineDenseLayer(p=1*1*28*28, q=1000, activation=torch.sigmoid, activation_inverse=inv_sigmoid),
#OnlineDenseLayer(p=1000, q=5000, activation=torch.sigmoid, activation_inverse=inv_sigmoid),
#OnlineDenseLayer(p=5000, q=100, activation=torch.sigmoid, activation_inverse=inv_sigmoid),
#OnlineDenseLayer(p=100, q=n_labels, activation=torch.sigmoid, activation_inverse=inv_sigmoid)
OnlineDenseLayer(p=3, q=2, activation=leaky_relu, activation_inverse=inv_leaky_relu),
OnlineDenseLayer(p=2, q=1)
]
)
def build_data(image, label):
'format data from iterator for model'
y = torch.tensor([1. if int(label[0]) == idx else 0. for idx in range(n_labels)]) ## one-hot representation
x = image.reshape([-1]) ## flatten
## shrink so sigmoid inverse is well-defined
y = y*.90 + .05
## reshape to column vectors
x = x.reshape([-1,1])
y = y.reshape([-1,1])
return x, y
def build_test_data():
x = torch.normal(mean=torch.zeros([3,1]))
y = torch.sigmoid(3. + 5.*x[0] - 10.*x[1])
y = y + 3*x[2]
y = y.reshape([-1,1])
return x, y
errs = []
pbar = tqdm(train_loader)
for [image, label] in pbar:
#x, y = build_data(image, label)
x, y = build_test_data()
## fit
y_hat, stability = model(x, y)
err = float((y - y_hat).abs().sum())
errs.append(err)
pbar.set_description(f'err: {err}, stab: {stability}')
## train error
## TODO
cs = torch.cumsum(torch.tensor(errs), dim=0)
ma = (cs[100:] - cs[:-100])/100.
list(ma)
###Output
_____no_output_____ |
.ipynb_checkpoints/0419 Sharpe Ratio and Heatmap-checkpoint.ipynb | ###Markdown
startDate: pd.to_datetime("2001-01-01")endDate: pd.to_datetime("2004-12-31")price_dir = "./from github/Stock-Trading-Environment/data"file_names = ["^BVSP_new", "^TWII_new", "^IXIC_new"]from CSVUtils import csv2dfdf_list = []for name in file_names: df = csv2df(price_dir, name+".csv", source="done") df = df[(df['Date']>=startDate)&(df['Date']<=endDate)].reset_index(drop = True) init_value = 100000 start_price = df['Actual Price'][0] inv_number = init_value/start_price df['BuyNHold'] = df['Actual Price']*inv_number df_list.append(df)buyNHold_totalValue = df_list[0]['BuyNHold'] +df_list[1]['BuyNHold']+df_list[2]['BuyNHold']
###Code
def getBuyNHold(startDate, endDate):
price_dir = "./from github/Stock-Trading-Environment/data"
file_names = ["^BVSP_new", "^TWII_new", "^IXIC_new"]
from CSVUtils import csv2df
df_list = []
for name in file_names:
df = csv2df(price_dir, name+".csv", source="done")
df = df[(df['Date']>=startDate)&(df['Date']<=endDate)].reset_index(drop = True)
init_value = 100000
start_price = df['Actual Price'][0]
inv_number = init_value/start_price
df['BuyNHold'] = df['Actual Price']*inv_number
df_list.append(df)
buyNHold_totalValue = df_list[0]['BuyNHold'] +df_list[1]['BuyNHold']+df_list[2]['BuyNHold']
return buyNHold_totalValue
def getSharpeRatio(netValue, startDate, endDate, tbill_df):
RISKFREE = 0.035
# print("startValue:", netValue.iloc[0]," ,endValue: ", netValue.iloc[-1])
ratioSeries = netValue/netValue.iloc[0]
riskFree = np.mean(tbill_df[(tbill_df["Date"]>=startDate) & (tbill_df["Date"]<=endDate)]['Price'])*0.01
finalReturn = (ratioSeries.iloc[-1]-ratioSeries.iloc[0]-riskFree)/ratioSeries.iloc[0]
return finalReturn/np.std(ratioSeries)
def getSharpeRatioByDate(startDate, endDate, tbill_df):
netValue = getBuyNHold(startDate, endDate)
return getSharpeRatio(netValue, startDate, endDate, tbill_df)
#Benchmark
buyNHold_fulldict = {}
buyNHold_finaldict = {}
for start in range(2000, 2016):
startDate = pd.to_datetime(str(start)+"-01-01")
for end in range(start+4, 2020):
endDate = pd.to_datetime(str(end)+"-12-31")
buyNHold_fulldict[(start, end)] = getBuyNHold(startDate, endDate)
buyNHold_finaldict[(start, end)] = getBuyNHold(startDate, endDate).iloc[-1]
print(start)
df_dict = []
for key in buyNHold_finaldict:
start = key[0]
end = key[1]
profit = (buyNHold_finaldict[key]-300000)/300000
df_dict.append({
"start": start,
"end":end,
"value": buyNHold_finaldict[key],
"profit": profit,
"log_profit": np.log(profit+1)
})
bnf_df = pd.DataFrame(df_dict)
bnf_df
DIR = "/Volumes/Seagate Backup Plus Drive/FYP/1010"
actual_profit_result = {}
nominal_profit_result = {}
for start in range(2000, 2016):
for end in range(start+4, 2020):
file_prefix = "0418-TEST_noCrisis_"+str(start)+"_"+str(end)+"--detailed-ModelNo_200000-"
actual_profit_list = []
nominal_profit_list = []
for i in range(10):
record = pickle.load(open(path.join(DIR,file_prefix+str(i)+".out"), "rb"))
df = pd.DataFrame(record)
actual_profit_rate = df['actual_profit'].iloc[-1]/df['buyNhold_balance'].iloc[-1]
nominal_profit_rate = (df['net_worth'].iloc[-1]-300000)/300000
actual_profit_list.append(actual_profit_rate)
nominal_profit_list.append(nominal_profit_rate)
actual_profit_result[(start,end)] = np.mean(actual_profit_list)
nominal_profit_result[(start,end)] = np.mean(nominal_profit_list)
print(start)
df_dict = []
for key in actual_profit_result:
start = key[0]
end = key[1]
df_dict.append({
"start": start,
"end":end,
"actual_profit": actual_profit_result[key],
"nominal_profit": nominal_profit_result[key],
"log_actual_profit": np.log(actual_profit_result[key]+1),
"log_nominal_profit": np.log(nominal_profit_result[key]+1),
})
model_df = pd.DataFrame(df_dict)
model_df
vmax = max(max(model_df['log_nominal_profit']), max(bnf_df['log_profit']))
vmin = min(min(model_df['log_nominal_profit']), min(bnf_df['log_profit']))
print(vmax, vmin)
import seaborn as sns
plt.figure(figsize=(10,8))
plt.title("Log Return of Buy-and-Hold")
sns.heatmap(bnf_df.pivot(index="start", columns="end", values="log_profit"),
annot=True, fmt=".2f", cmap="RdYlGn", vmax=vmax, vmin=vmin)
import seaborn as sns
plt.figure(figsize=(10,8))
plt.title("Log Nominal Return")
sns.heatmap(model_df.pivot(index="start", columns="end", values="log_nominal_profit"),
annot=True, fmt=".2f", cmap="RdYlGn", vmax=vmax, vmin=vmin)
import seaborn as sns
plt.figure(figsize=(10,8))
plt.title("Log Actual Return")
sns.heatmap(model_df.pivot(index="start", columns="end", values="log_actual_profit"),
annot=True, fmt=".2f", cmap="RdYlGn", center=0)
import seaborn as sns
plt.figure(figsize=(10,8))
plt.title("Actual Return")
sns.heatmap(model_df.pivot(index="start", columns="end", values="actual_profit"),
annot=True, fmt=".2f", cmap="RdYlGn", center=0)
np.mean(model_df['actual_profit'])
df
#Benchmark
startDate = pd.to_datetime("2015-01-01")
endDate = pd.to_datetime("2019-12-31")
getSharpeRatioByDate(startDate, endDate, tbill_df)
#Benchmark
startDate = pd.to_datetime("2007-01-01")
endDate = pd.to_datetime("2010-12-31")
getSharpeRatioByDate(startDate, endDate, tbill_df)
#Benchmark
startDate = pd.to_datetime("2001-01-01")
endDate = pd.to_datetime("2004-12-31")
getSharpeRatioByDate(startDate, endDate, tbill_df)
startDate = pd.to_datetime("2015-01-01")
endDate = pd.to_datetime("2019-12-31")
buyNhold = getBuyNHold(startDate, endDate)
(buyNhold.iloc[-1]-buyNhold.iloc[0])/buyNhold.iloc[0]
###Output
_____no_output_____ |
extractor-notebook.ipynb | ###Markdown
Line numbers for spectra headers are: 525nm : 4893, 308nm : 9769, 450nm : 14645, Spectrum Max Plot : 17 First need to load the file into python
###Code
from pathlib import Path
import numpy as np
input_file = Path.cwd() / "20220118-PCD-Ristretto-CAP1-1-Rep1.asc"
f = input_file.open()
lines = f.readlines()
for idx, ele in enumerate(lines):
lines[idx] = ele.strip('\n')
###Output
_____no_output_____
###Markdown
The above has loaded the files contents into a list and stripped the newline char.Now to search for the indexes
###Code
matches = [match for match, s in enumerate(lines) if "Spectrum Max Plot" in s]
matches2 = [match for match, s in enumerate(lines) if "nm" in s]
matches = matches + matches2
print(matches)
dict_list = []
for idx, val in enumerate(matches):
if idx + 1 < len(matches):
dict_list.append({ lines[val] : lines[val+1 : matches[idx+1]] })
if idx + 1 == len(matches):
dict_list.append({ lines[val] : lines[val+1:]})
## storing the data as a list of dicts
data_list = []
column_list = []
for idx, val in enumerate(matches):
if idx + 1 < len(matches):
data_list.append(lines[val+1 : matches[idx+1]])
column_list.append(lines[val])
if idx + 1 == len(matches):
data_list.append(lines[val+1:])
column_list.append(lines[val])
print(column_list[idx])
## storing the data as a list of lists
###Output
Spectrum Max Plot
1: 525 nm, 2 nm
2: 308 nm, 2 nm
Detector A-450 nm
###Markdown
The above code is generalised enough for any number of spectra in the file.Now to load the dicts into a DF.
###Code
import pandas as pd
df_list = []
for data_dict in dict_list: ## a work around as pandas wasnt reading the list of dicts properly.
df_list.append(pd.DataFrame(data_dict))
df = pd.concat(df_list)
df = df.apply(pd.to_numeric) ## converts all the data to numeric as readlines() reads everything as string.
import matplotlib.pyplot as plt
df.plot(subplots=True)
plt.tight_layout()
plt.show()
###Output
_____no_output_____ |
python-tuts/1-intermediate/01 - Sequences/05 - Slicing.ipynb | ###Markdown
Slicing Slices can actually be defined using the `slice()` function which creates a `slice` object:
###Code
s = slice(0, 2)
type(s)
s.start
s.stop
l = [1, 2, 3, 4, 5]
l[s]
###Output
_____no_output_____
###Markdown
This can be useful in practice to make code more readable.Suppose you are parsing fixed-width file. You would need to define the start/end column of each field in the rows of the file.So you might write something like this:
###Code
data = [] # a collection of rows, read from a file maybe
for row in data:
first_name = row[0:51]
last_name = row[51:101]
ssn = row[101:111]
# etc
###Output
_____no_output_____
###Markdown
Instead, you might write:
###Code
range_first_name = slice(0, 51)
range_last_name = slice(51, 101)
range_ssn = slice(101, 111)
###Output
_____no_output_____
###Markdown
These might even be defined in your global scope, or maybe a config file.Then in your code you would write this instead:
###Code
for row in data:
first_name = row[range_first_name]
last_name = row[range_last_name]
ssn = row[range_ssn]
###Output
_____no_output_____
###Markdown
Separating the slice definition from the code that uses the slice makes it now much easier to update your slice definitions in one place, rather than hunt for them all over the place. Slice Fundamentals Indexing is zero-based in Python, and slices are inclusive of their start-index, and exclusive of their end-index:
###Code
l = 'python'
l[0:1], l[0:6]
###Output
_____no_output_____
###Markdown
Additionally, extended slicing allows specifying a step value:
###Code
l = 'python'
l[0:6:2], l[0:6:3]
###Output
_____no_output_____
###Markdown
And extended slices can also be defined using `slice`:
###Code
s1 = slice(0, 6, 2)
s2 = slice(0, 6, 3)
l[s1], l[s2]
###Output
_____no_output_____
###Markdown
Unlike regular indexing (e.g. `l[n]`), it's OK for slice indexes to be "out of bounds":
###Code
l = [1, 2, 3, 4, 5, 6]
l[0:100]
l[-10:100]
###Output
_____no_output_____
###Markdown
But regular indexing will raise exceptions for out of bound errors:
###Code
l = [1, 2, 3, 4, 5, 6]
l[100]
###Output
_____no_output_____
###Markdown
In slicing, if we do not specify the start/end index, Python will automatically use the start/end of the sequence we are slicing:
###Code
l = [1, 2, 3, 4, 5, 6]
l[:4]
l[4:]
###Output
_____no_output_____
###Markdown
In fact, we can omit both:
###Code
l[:]
###Output
_____no_output_____
###Markdown
In addition to the start/stop values allowing for negative values, the step value can also be negative. This simply means the sequence will traversed in the opposite direction:
###Code
l = [0, 1, 2, 3, 4, 5]
l[3:0:-1]
###Output
_____no_output_____
###Markdown
Basically we started at `3` (inclusive) and went in steps of `-1`, ending at (but not including) `0`. If we wanted to include the `0` index element, we could do it by ommitting the end value:
###Code
l[3::-1]
###Output
_____no_output_____
###Markdown
We could also do the following:
###Code
l[3:-100:-1]
###Output
_____no_output_____
###Markdown
But this would not work as expected:
###Code
l[3:-1:-1]
###Output
_____no_output_____
###Markdown
Why? Remember from the lecture that this range equivalence would be:`3 --> 3``-1 max(-1, 6-1) --> max(-1, 5) --> 5`so equivalent range would be given by:
###Code
list(range(3, 5, -1))
###Output
_____no_output_____
###Markdown
which of course is an empty range! Easily Converting a Slice to a Range We can easily determine the effective range of a slice by using the `indices` method in the `slice` object. The only thing is that in order to do this we must know the length of the sequence we are slicing. For example, if our list has a length of 10:
###Code
slice(1, 5).indices(10)
list(range(1, 5, 1))
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l[1:5]
###Output
_____no_output_____
###Markdown
The `slice` object can also handle extended slicing:
###Code
slice(0, 100, 2).indices(10)
list(range(0, 10, 2))
l[0:100:2]
###Output
_____no_output_____
###Markdown
We can easily retrieve a list of indices from a slice by passing the unpacked tuple returned by the `indices` method to the range function's arguments and converting to a list:
###Code
list(range(*slice(None, None, -1).indices(10)))
###Output
_____no_output_____
###Markdown
As we can see from this example, using a slice such as `[::-1]` returns a sequence that is in reverse order from the original one.
###Code
l
l[::]
l[::-1]
###Output
_____no_output_____ |
Data/Moments/.ipynb_checkpoints/Plot_mom0_and_hst-checkpoint.ipynb | ###Markdown
Figure 1 of paper
###Code
%matplotlib notebook
import matplotlib.pylab as plt
from astropy.io import fits
from reproject import reproject_interp
from astropy.wcs import WCS
from astropy import units as u
from astropy.utils.data import get_pkg_data_filename
import numpy as np
from matplotlib.patches import Ellipse
import seaborn as sns
sns.set(style="dark")
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:90% !important; }</style>"))
from normalize import APLpyNormalize
def make_rgb_image(im_r,im_g,im_b,min_p=(3.,3.,3.),mid_p=(70.,70.,70.),max_p=(99.5,99.5,99.5),stretch='arcsinh',plot=False):
'''
Takes 3 images and makes an rgb image.
From David Carton.
Parameters:
-----------
im_r: array
red image
im_g: array
green image
im_b: array
blue image
min_p: float
percentile to calculate vmin of the image
mid_p: float
vmid
max_p: float
vmax
Returns
-----
image (array)
'''
valid = np.isfinite(im_r)
valid &= np.isfinite(im_g)
valid &= np.isfinite(im_b)
im_r[~valid] = 0.
im_g[~valid] = 0.
im_b[~valid] = 0.
vmin, vmid, vmax = np.percentile(im_r, [min_p[0], mid_p[0], max_p[0]])
norm = APLpyNormalize(stretch=stretch, vmin=vmin, vmax=vmax,
vmid=vmid)
im_r = norm(im_r, clip=True)
vmin, vmid, vmax = np.percentile(im_g, [min_p[1], mid_p[1], max_p[1]])
norm = APLpyNormalize(stretch=stretch, vmin=vmin, vmax=vmax,
vmid=vmid)
im_g = norm(im_g, clip=True)
vmin, vmid, vmax = np.percentile(im_b, [min_p[2], mid_p[2], max_p[2]])
norm = APLpyNormalize(stretch=stretch, vmin=vmin, vmax=vmax,
vmid=vmid)
im_b = norm(im_b, clip=True)
image = np.array([im_r, im_g, im_b])
image = np.rollaxis(image, 0, 3)
if plot:
ratio = float(image.shape[0]) / float(image.shape[1])
fig = plt.figure(figsize=(10.,10*ratio), frameon=False)
ax = fig.add_axes([0,0,1,1])
ax.set_axis_off()
ax.imshow(image, interpolation='nearest', origin='lower')
return image
###Output
_____no_output_____
###Markdown
AS1063 rebin cube
###Code
########## ALMA ###########
wcs_alma = WCS(fits.getheader('as1063_mom0.fits'))
mom0 = fits.getdata('as1063_mom0.fits')
mom1 = fits.getdata('as1063_mom1.fits')
alma = fits.open('as1063_mom0.fits')[0]
rms = 0.048026208
########## HST Image ############
HST_red,_ = reproject_interp('../HST/AS1063_F160w.fits',alma.header)
HST_green,_ = reproject_interp('../HST/AS1063_F814w.fits',alma.header)
HST_blue,_ = reproject_interp('../HST/AS1063_F435w.fits',alma.header)
rgb_as1063 = make_rgb_image(HST_red,HST_green,HST_blue,(5,5,5),(10,10,10),(99.95,99.96,99.95))
## MUSE ##
oii_vel, _ = reproject_interp('../MUSE/AS1063_model_atan.fits',alma.header)
oii_vel[np.where(oii_vel == 0)] = np.nan
####### Plot ############
fig, ax = plt.subplots(1,1,figsize=(4.5,6))
fig.subplots_adjust(top=0.99,bottom=0.01,left=0.01,right=0.99)
ax.imshow(rgb_as1063[550:830,590:780],origin='lower')
#ax.contour(mom0[550:830,590:780],levels= (0.1,0.15,0.25),cmap=plt.cm.gist_heat,linewidths=1.2)
ax.contourf(mom0[550:830,590:780],levels= (0.10,0.15,0.20),cmap='gist_heat',alpha=0.6)
###### Symbols and stuff #######
ax.add_artist(Ellipse(xy=(165,40), width=4.3442E-05/8.333E-06, height=3.8018E-05/8.333E-06, angle=7.287213897705E+01, facecolor='w'))
ax.annotate('beam',(157,30),color='w',fontsize=8)
ax.annotate('N',xy=(20, 230),xytext=(20, 260), arrowprops=dict(facecolor='w',arrowstyle='<|-',),color='w',ha='center')
ax.annotate('E',xy=(19, 231),xytext=(48, 231), arrowprops=dict(facecolor='w',arrowstyle='<|-',),color='w',va='center')
ax.hlines(y=20,xmin=140,xmax=140+(1/(8.3333333333333E-06 *3600)),color='w')
ax.annotate('1"',xy=(140, 25), color='w',fontsize=10)
ax.axis('off')
fig.savefig('../../Plots/AS1063_hst_and_alma_filled.pdf')
full resolution cube
###Output
_____no_output_____
###Markdown
A521
###Code
########## ALMA ###########
wcs_alma = WCS(fits.getheader('a521_mom0.fits'))
mom0 = fits.getdata('a521_mom0.fits')[635:1105,570:1090]
mom1 = fits.getdata('a521_mom1.fits')[635:1105,570:1090]
alma = fits.open('a521_mom0.fits')[0]
rms = 0.01903471
########## HST Image ############
HST_red,_ = reproject_interp('../HST/A521_F160w.fits',alma.header)
HST_green,_ = reproject_interp('../HST/A521_F105w.fits',alma.header)
HST_blue,_ = reproject_interp('../HST/A521_F390w.fits',alma.header)
rgb_a521 = make_rgb_image(HST_red,HST_green,HST_blue,(25,25,25),(50,50,50),(99.2,99.2,99.8),stretch='linear')[635:1105,570:1090]
## MUSE ##
oii_vel, _ = reproject_interp('../MUSE/A521_model_exp.fits',alma.header)
oii_vel[np.where(oii_vel == 0)] = np.nan
####### Plot ############
fig, ax = plt.subplots(1,1,figsize=(4.5,4.))
fig.subplots_adjust(top=0.99,bottom=0.01,left=0.01,right=0.99)
rgb_copy = np.zeros_like(rgb_a521)
rgb_copy[:,:] = rgb_a521
rgb_copy[30:230,77:295] = np.nan
ax.imshow(rgb_copy,origin='lower')
ax.contour(mom0,levels=(0.05,0.10,0.15),cmap='gist_heat',linewidths=1.)
#ax.contourf(mom0,levels=(0.05,0.10,0.15),cmap='gist_heat',linewidths=1.,alpha=0.6)
###### Symbols and stuff #######
ax.add_artist(Ellipse(xy=(24,70), width=5.642E-05/8.333E-06, height=4.733E-05/8.333E-06, angle=-7.125E+01, facecolor='w'))
ax.annotate('beam',(19,50),color='w',fontsize=8)
ax.hlines(y=20,xmin=20,xmax=20+(1/(8.3333333333333E-06 *3600)),color='w')
ax.annotate('1"',xy=(22, 25), color='w',fontsize=10)
ax.annotate('N',xy=(15+430, 400),xytext=(15+430, 445), arrowprops=dict(facecolor='w',arrowstyle='<|-',),color='w',ha='center')
ax.annotate('E',xy=(12+430, 402),xytext=(50+430, 402), arrowprops=dict(facecolor='w',arrowstyle='<|-',),color='w',va='center')
ax.axis('off')
fig.savefig('../../Plots/A521_hst_and_alma.pdf')
###Output
_____no_output_____
###Markdown
MACS1206
###Code
########## ALMA ###########
wcs_alma = WCS(fits.getheader('snake_mom0.fits'))
mom0 = fits.getdata('snake_mom0.fits')[280:740,410:580]
mom1 = fits.getdata('snake_mom1.fits')
alma = fits.open('snake_mom0.fits')[0]
########## HST Image ############
HST_red,_ = reproject_interp('../HST/snake_F160w.fits',alma.header)
HST_green,_ = reproject_interp('../HST/snake_F814w.fits',alma.header)
HST_blue,_ = reproject_interp('../HST/snake_F435w.fits',alma.header)
rgb_snake = make_rgb_image(HST_red,HST_green,HST_blue,(5,5,5),(10,10,10),(99.93,99.91,99.94))[280:740,410:580]
## MUSE ##
oii_vel, _ = reproject_interp('../MUSE/MACS1206_model_atan.fits',alma.header)
oii_vel[np.where(oii_vel == 0)] = np.nan
####### Plot ############
fig, ax = plt.subplots(1,1,figsize=(2.5,6))
fig.subplots_adjust(top=0.99,bottom=0.01,left=0.01,right=0.99)
ax.imshow(rgb_snake,origin='lower')
ax.contour(mom0,levels=(0.10,0.15,0.2),cmap='gist_heat',linewidths=1.)
#ax.contourf(mom0,levels=(0.10,0.15,0.2),cmap='gist_heat',linewidths=1.,alpha=0.6)
###### Symbols and stuff #######
ax.add_artist(Ellipse(xy=(24,70), width=5.98E-05/1.11E-05, height=5.084E-05/1.11E-05, angle=8.489570617676E+01, facecolor='w'))
ax.annotate('beam',(19,50),color='w',fontsize=8)
ax.hlines(y=20,xmin=20,xmax=20+(1/(1.111111111111E-05 *3600)),color='w')
ax.annotate('1"',xy=(22, 25), color='w',fontsize=10)
ax.annotate('N',xy=(20, 400),xytext=(20, 445), arrowprops=dict(facecolor='w',arrowstyle='<|-',),color='w',ha='center')
ax.annotate('E',xy=(18, 402),xytext=(55, 402), arrowprops=dict(facecolor='w',arrowstyle='<|-',),color='w',va='center')
ax.axis('off')
fig.savefig('../../Plots/snake_hst_and_alma.pdf')
###Output
_____no_output_____ |
kulo.ipynb | ###Markdown
Author: michaelpeterswa Setup Import geojsonAccording to Wikipedia, "GeoJSON is an open standard format designed for representing simple geographical features, along with their non-spatial attributes. It is based on the JSON format."
###Code
import geojson
###Output
_____no_output_____
###Markdown
Create load_data function to load geojson dataload_data(filename) is a simple wrapper around the Python File I/O that uses geojson to load the data into a dictionary
###Code
def load_data(filename):
"""
Loads GeoJson Data from "filename"
"""
with open(filename) as f:
data = geojson.load(f)
return data
###Output
_____no_output_____
###Markdown
Load data from WA DNR 1970-2007 fire statisticssource: https://data-wadnr.opendata.arcgis.com/datasets/dnr-fire-statistics-1970-2007-1
###Code
older_fire_data = load_data("data/DNR_Fire_Statistics_1970-2007.geojson")
###Output
_____no_output_____
###Markdown
Load data from WA DNR 2008-present fire statisticssource: https://data-wadnr.opendata.arcgis.com/datasets/dnr-fire-statistics-2008-present-1
###Code
newer_fire_data = load_data("data/DNR_Fire_Statistics_2008_-_Present.geojson")
###Output
_____no_output_____
###Markdown
Extract Data Pull out "features" section of data (that's where fire data is)
###Code
old_fire_data = older_fire_data["features"]
new_fire_data = newer_fire_data["features"]
###Output
_____no_output_____
###Markdown
Examine fire data and determine the parts we need.As we can see, each fire has a "geometry" and "properties" attribute. From these, we want to extract the "coordinates" from "geometry", "ACRES_BURNED" from "properties", and "START_DT" from "properties"
###Code
print(old_fire_data[1])
print(new_fire_data[1])
###Output
{"geometry": {"coordinates": [-120.916389, 45.904957], "type": "Point"}, "properties": {"ACRES_BURNED": 0.25, "BURNESCAPE_RSN_LABEL_NM": "Extinguish", "BURN_MERCH_AREA": null, "BURN_NONSTOCK_AREA": 0.25, "BURN_REPROD_AREA": null, "CONTROL_DT": "2017-05-23T00:00:00Z", "CONTROL_TM": "1935", "COUNTY_LABEL_NM": "KLICKITAT", "DSCVR_DT": "2017-05-23T00:00:00Z", "DSCVR_TM": "1650", "FIREEVENT_ID": 50035, "FIREEVNT_CLASS_CD": 1, "FIREEVNT_CLASS_LABEL_NM": "Classified", "FIREGCAUSE_LABEL_NM": "Debris Burn", "FIRESCAUSE_LABEL_NM": "None", "FIRE_OUT_DT": "2017-05-25T00:00:00Z", "FIRE_OUT_TM": "1300", "FIRE_RGE_DIR_FLG": "E", "FIRE_RGE_FRACT_NO": 0, "FIRE_RGE_WHOLE_NO": 15, "FIRE_SECT_NO": 22, "FIRE_TWP_FRACT_NO": 0, "FIRE_TWP_WHOLE_NO": 5, "INCIDENT_ID": 49868, "INCIDENT_NM": "Turkey Ranch", "INCIDENT_NO": 7, "LAT_COORD": 45.904947, "LON_COORD": -120.916377, "NON_DNR_RES_ORDER_NO": null, "OBJECTID": 2, "PROTECTION_TYPE": "DNR Protection FFPA", "REGION_NAME": "SOUTHEAST", "RES_ORDER_NO": "WA-SES-050", "SECTION_SUBDIV_PTS_ID": 372894, "SITE_ELEV": 2000, "START_DT": "2017-05-23T08:00:00Z", "START_JURISDICTION_AGENCY_NM": "DNR", "START_OWNER_AGENCY_NM": "Private", "START_TM": "1715"}, "type": "Feature"}
###Markdown
Ensure both datasets are imported by checking total number of fires Here, we see that the 1970-2007 data has nearly 40,000 fires, where the 2008-present set has just over 20,000. We want to combine these to get the full range of wildfire activity since 1970.
###Code
# get total number of fires
old_total = len(old_fire_data)
new_total = len(new_fire_data)
print(old_total, new_total, old_total + new_total)
###Output
38116 20703 58819
###Markdown
Make clean dataset from both pieces of data (only data-points we need)The data we need to extract is: Date, Acreage, Coordinates
###Code
cleaned_fire_data = []
for fire in old_fire_data:
date = fire["properties"]["START_DT"]
acres = fire["properties"]["ACRES_BURNED"]
lon = fire["geometry"]["coordinates"][0]
lat = fire["geometry"]["coordinates"][1]
cleaned_fire_data.append((date, acres, lat, lon))
for fire in new_fire_data:
date = fire["properties"]["START_DT"]
acres = fire["properties"]["ACRES_BURNED"]
lon = fire["geometry"]["coordinates"][0]
lat = fire["geometry"]["coordinates"][1]
cleaned_fire_data.append((date, acres, lat, lon))
print(len(cleaned_fire_data))
###Output
58819
###Markdown
Import csv (comma-separated values)The CSV package is used to write a comma-separated file of the cleaned data, for future use.
###Code
import csv
###Output
_____no_output_____
###Markdown
Save cleaned data to csvUsing csv.writer(), we write a single row at a time while iterating over the nearly 60,000 fires in Washington
###Code
with open('data/clean_fire_data.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile,)
writer.writerow(("date", "acres", "lat", "lon"))
for fire in cleaned_fire_data:
writer.writerow(fire)
###Output
_____no_output_____
###Markdown
Import numpy (for arrays and matrix math)We mostly need numpy for their np.array() function.
###Code
import numpy as np
###Output
_____no_output_____
###Markdown
Create numpy array from fire data
###Code
np_fire_data = np.array(cleaned_fire_data)
###Output
_____no_output_____
###Markdown
Access column from the np array using syntax belownp_fire_data\[:,1\] is the basic structure to extract all values from column 1 into a 1-d numpy array.
###Code
acres = np_fire_data[:,1]
acres = [float(acre) for acre in acres]
print(max(acres), min(acres))
###Output
250280.45 0.0
###Markdown
Convert ISO8601 format date to epochThe DNR datasets have the start date for each fire in the ISO8601 format. For use in matplotlib, we need to switch this to the epoch format and rebuild the 1-d numpy array.
###Code
import dateutil.parser as dp
dates = np_fire_data[:, 0]
new_dates = []
for date in dates:
new_dates.append(dp.parse(date).timestamp())
np_new_dates = np.array(new_dates)
print(np_new_dates)
###Output
[1.1874240e+09 1.5079680e+08 1.1416320e+08 ... 1.4992416e+09 1.5868512e+09
1.4653728e+09]
###Markdown
Get coordinate point columnsUsing the same strategy as above, albeit less complicated, extract the coordinate values into their own numpy arrays.
###Code
lats = np_fire_data[:,2]
print(lats)
longs = np_fire_data[:,3]
print(longs)
###Output
['46.473463' '47.837034' '47.837034' ... '47.552689' '48.672689'
'47.350066']
['-123.941779' '-117.078338' '-117.078338' ... '-117.182356' '-122.315778'
'-118.73053']
###Markdown
Plots/Analysis Import matplotlib (for visualizing data)From the Matplotlib website, "Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python."
###Code
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Import matplotlib dates (for plotting dates on histogram)The mdates.epoch2num() function converts a date in the epoch format to something a little more usable in matplotlib.
###Code
import matplotlib.dates as mdates
# convert the epoch format to matplotlib date format
mpl_dates = mdates.epoch2num(np_new_dates)
###Output
_____no_output_____
###Markdown
Plot "wildfires by year" in histogramHere, we use some of the features of pyplot, most importantly hist(), which generates a histogram. The x-axis is years, the y-axis is number of fires.In this plot, we see that there is a general upward trend that has occurred over the past 50 years, so it would seem that the date is important to take into account for our future predictions.
###Code
fig, ax = plt.subplots(1,1)
ax.hist(mpl_dates, bins=51, color='lightblue', edgecolor='grey')
locator = mdates.AutoDateLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
ax.set_title("Washington Wildfires by Year (since 1970)")
ax.set_xlabel('Year') # Add an x-label to the axes.
ax.set_ylabel('Number of Fires') # Add a y-label to the axes.
plt.savefig("img/fires_by_year.png", transparent=False, facecolor='w', edgecolor='w' )
plt.show()
###Output
_____no_output_____
###Markdown
Plots, cont.Here, we look at the distribution of acres across nearly 60,000 fires in our data set. We see that it is heavily skewed to the left, below 50,000 acres. This may not be the best way too look at the data, because even with a logarithmic y-axis, it's difficult to discern the trends in the smaller sized fires.
###Code
import matplotlib.ticker as plticker
fig, ax = plt.subplots(1,1)
ax.hist(acres, bins=60, color='lightblue', edgecolor='grey')
ax.set_title("Washington Wildfires by Acres (since 1970)")
ax.set_xlabel('Acres') # Add an x-label to the axes.
ax.set_ylabel('Number of Fires (logbase10)') # Add a y-label to the axes.
loc = plticker.AutoLocator() # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.yscale("log")
plt.savefig("img/fires_acres.png", transparent=False, facecolor='w', edgecolor='w' )
plt.show()
###Output
_____no_output_____
###Markdown
Narrowing down our examinationAs we saw in the previous histogram, there must be a better way to look at this data. We know there are a few larges fires (over 50,000 acres) that are significant outliers in our data. Let's take a closer look. What does it look like when we limit the largest fire to 30,000 acres?
###Code
lt30k = []
lt10k = []
for acre in acres:
if(acre < 10000):
lt10k.append(acre)
if(acre < 30000):
lt30k.append(acre)
fig, ax = plt.subplots(1,1)
ax.hist(lt30k, bins=60, color='lightblue', edgecolor='grey')
ax.set_title("Washington Wildfires by Acres (since 1970)")
ax.set_xlabel('Acres (less than 30,000)') # Add an x-label to the axes.
ax.set_ylabel('Number of Fires (logbase10)') # Add a y-label to the axes.
loc = plticker.AutoLocator() # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.yscale("log")
plt.savefig("img/fires_acres_lt30k.png", transparent=False, facecolor='w', edgecolor='w' )
plt.show()
###Output
_____no_output_____
###Markdown
What about 10,000 acres?
###Code
fig, ax = plt.subplots(1,1)
ax.hist(lt10k, bins=60, color='lightblue', edgecolor='grey')
ax.set_title("Washington Wildfires by Acres (since 1970)")
ax.set_xlabel('Acres (less than 10,000)') # Add an x-label to the axes.
ax.set_ylabel('Number of Fires (logbase10)') # Add a y-label to the axes.
loc = plticker.AutoLocator() # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.yscale("log")
plt.savefig("img/fires_acres_lt10k.png", transparent=False, facecolor='w', edgecolor='w' )
plt.show()
###Output
_____no_output_____
###Markdown
Now let's see what happens when we set a bottom limitSo we can see that there are nearly $10^{5}$ fires in the first bin of data. This was the main reason we used logarithmic scale. Let's set a minimum of 200 acres and then switch back to a linear scale over the y axis. Here we can get a much better idea about fires of a reasonably large size, and it's still left skewed (smaller fires are of course better), but we can get a more solid grasp on the data with this example.
###Code
reasonable_size = []
for acre in acres:
if(acre < 10000 and acre > 200):
reasonable_size.append(acre)
fig, ax = plt.subplots(1,1)
ax.hist(reasonable_size, bins=100, color='lightblue', edgecolor='grey')
ax.set_title("Washington Wildfires by Acres (since 1970)")
ax.set_xlabel('Acres (less than 10,000 but greater than 200)') # Add an x-label to the axes.
ax.set_ylabel('Number of Fires') # Add a y-label to the axes.
loc = plticker.AutoLocator() # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.yscale("linear")
plt.savefig("img/fires_acres_reasonable_size.png", transparent=False, facecolor='w', edgecolor='w' )
plt.show()
###Output
_____no_output_____
###Markdown
More Data Cleaning Time for NormalizationHere we write a normalization function which is essentially map() from the Arduino standard library. It takes a max and min from the original list, and conforms it to the max and min values that are supplied for outputs
###Code
# https://www.raspberrypi.org/forums/viewtopic.php?t=149371#p982264
def valmap(value, istart, istop, ostart, ostop):
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))
def normalize_list(lst, min_in, max_in, min_out, max_out):
normal_lst = []
for val in lst:
normal_lst.append(valmap(val, min_in, max_in, min_out, max_out))
# need to pass out scaling factor for regeneration coming out of the model
scale = (min_in, max_in, min_out, max_out)
return normal_lst, scale
###Output
_____no_output_____
###Markdown
Normalize time, acres, lats, and longs
###Code
# max(new_dates) + 315360000 signifies 10 years into the future
normalized_epoch_time, tscl = normalize_list(new_dates, min(new_dates), max(new_dates) + 315360000, 0, 1)
np_norm_e_time = np.array(normalized_epoch_time)
# print(np_norm_e_time)
normalized_acres, ascl = normalize_list(acres, min(acres), max(acres), 0, 1)
np_norm_acres = np.array(normalized_acres)
# print(np_norm_acres)
not_np_lats = [float(lat) for lat in lats]
normalized_lats, ltscl = normalize_list(not_np_lats, min(not_np_lats), max(not_np_lats), 0, 1)
np_norm_lats = np.array(normalized_lats)
# print(np_norm_lats)
not_np_longs = [float(longx) for longx in longs]
normalized_longs, lnscl = normalize_list(not_np_longs, min(not_np_longs), max(not_np_longs), 0, 1)
np_norm_longs = np.array(normalized_longs)
# print(np_norm_longs)
###Output
_____no_output_____
###Markdown
Join and reshape the data
###Code
norm_inp_data = np.vstack((np_norm_e_time, np_norm_acres, np_norm_lats, np_norm_longs))
dshape = norm_inp_data.shape
a, b = dshape
norm_inp_data = np.reshape(norm_inp_data, (b, a))
print("Normalized shape:\t", norm_inp_data.shape)
np.savetxt("data/norm_inp_data.csv", norm_inp_data, delimiter=",")
###Output
Normalized shape: (58819, 4)
###Markdown
Check scaling values
###Code
print("Time (epoch) scaling:\t", tscl)
print("Acres scaling:\t\t", ascl)
print("Latitude scaling:\t", ltscl)
print("Longitude scaling:\t", lnscl)
###Output
Time (epoch) scaling: (5040000.0, 1927699200.0, 0, 1)
Acres scaling: (0.0, 250280.45, 0, 1)
Latitude scaling: (45.556224, 49.00112, 0, 1)
Longitude scaling: (-124.716371, -116.94347, 0, 1)
###Markdown
Randomly shuffle the normalized input data
###Code
shuffled_data = np.copy(norm_inp_data)
np.random.shuffle(shuffled_data)
print(shuffled_data[2])
###Output
[0.33709726 0.75936458 0.96096341 0.66358259]
###Markdown
Split the data into inputs (X) and outputs (y)
###Code
# X_data is Time, Lat, Long
# y_data is Acres
X_data, y_data = shuffled_data[:,[0,2,3]], shuffled_data[:,1]
# print(X_data)
# print(y_data)
print(X_data.shape, y_data.shape)
train_rt = 0.7
test_rt = 0.15
validation_rt = 0.15
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X_data, y_data, test_size=1 - train_rt)
x_val, x_test, y_val, y_test = train_test_split(x_test, y_test, test_size=test_rt/(test_rt + validation_rt))
import datetime
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import TensorBoard
# define the keras model
model = Sequential()
model.add(Dense(12, input_dim=3, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the keras model
model.compile(loss='mse', optimizer='adam')
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)
history = model.fit(x_train, y_train, epochs=200, verbose=0, validation_data=(x_val, y_val), callbacks=[tensorboard_callback])
def plot_loss(history):
plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.xlabel('Epoch')
plt.ylabel('Percent (decimal)')
plt.legend()
plt.grid(True)
plt.show()
plot_loss(history)
model.save("kulo_model")
epochx = 0.13570134
latx = 0.11424612
longx = 0.40764424
npsample = np.array([(epochx, latx, longx)])
result = model.predict(npsample)
norm_pred_acres = result[0][0]
# (0.0, 250280.45, 0, 1)
prediction = normalize_list([norm_pred_acres], ascl[2], ascl[3], ascl[0], ascl[1])
print(prediction[0])
###Output
[64763.26423368156]
|
dataset_check.ipynb | ###Markdown
Dataset handling code
###Code
import os
from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt
labels_path = "./"
crack_imgs = [path for path in os.listdir(labels_path) if path.endswith("-c.png")]
delam_imgs = [path for path in os.listdir(labels_path) if not path.endswith("-c.jpg")]
all_imgs = [path for path in os.listdir(labels_path) if path.endswith(".jpg")]
len(all_imgs)
img = cv2.imread("cologne_000000_000019_gtFine_labelTrainIds.png")
img.shape
np.unique(img)
###Output
_____no_output_____
###Markdown
Image Mixing
###Code
images_dir = "./leftImg8bit/delamination/"
labels_dir = "./gtFine/delamination/"
save_dir = "./leftImg8bit/merged/"
save_dir_l = "./gtFine/merged/"
IMG_DIM = 256
images = [path for path in os.listdir(images_dir) if path.endswith(".png")]
labels = [path for path in os.listdir(labels_dir) if path.endswith(".png")]
np.random.shuffle(images)
print("no. of images: {}".format(len(images)))
# randomly choose 2000 images to make 500 images by combining 4 for each.
chosen_images = np.array(images[:4000])
# split the array to group of 4 each.
groups = np.array(np.split(chosen_images, 4)).T
1%2
for group in groups:
imgs = [cv2.resize(cv2.imread(images_dir + path), (IMG_DIM, IMG_DIM)) for path in group]
labels = [cv2.resize(cv2.imread(labels_dir + path), (IMG_DIM, IMG_DIM)) for path in group]
row1 = np.concatenate((imgs[0], imgs[1]), axis = 1)
row1_l = np.concatenate((labels[0], labels[1]), axis = 1)
row2 = np.concatenate((imgs[2], imgs[3]), axis = 1)
row2_l = np.concatenate((labels[2], labels[3]), axis = 1)
final = cv2.resize(np.concatenate((row1, row2), axis=0), (480, 480))
final_l = cv2.resize(np.concatenate((row1_l, row2_l), axis=0), (480, 480))
name = "mx-{}-{}-{}-{}.png".format(group[0][:-4], group[1][:-4],group[2][:-4],group[3][:-4])
cv2.imwrite(save_dir + name, final )
cv2.imwrite(save_dir_l + name, final_l)
#
plt.imshow(final)
plt.imshow(final_l)
img = cv2.imread(images_dir + images[0])
plt.imshow(img)
###Output
_____no_output_____
###Markdown
txt files generator
###Code
import random
output_file = "cityscapes_train_list"
folder = "GAN_del_augmented"
images = [path for path in os.listdir("./leftImg8bit/" + folder) if path.endswith(".png")]
images.sort()
random.shuffle(images)
print("length of images found: ", len(images))
images[:5] # names of first 5 images in folder
with open('cityscapes_train_list_{}.txt'.format(folder), 'w') as f:
for path in images:
str = "leftImg8bit/{}/{} gtFine/{}/{}\n".format(folder,path, folder, path)
f.write(str)
###Output
_____no_output_____
###Markdown
jpg to png only
###Code
for path in all_imgs:
img = np.asarray(cv2.imread(labels_path + path))
cv2.imwrite("./images/new2/" + path[:-3] + "png", img)
###Output
_____no_output_____
###Markdown
LABELS CLASS ASSOCIATION
###Code
labels_path="./gtFine/GAN_del_rgb/"
crack_imgs = [path for path in os.listdir(labels_path) if path.endswith(".png") or path.endswith(".jpg")]
print("crack images:", len(crack_imgs))
# change class symbols
# for path in crack_imgs:
# img = np.array(cv2.imread(labels_path + path, 0))
# # 0: del, 1: crack, 255: back
# img[img == 1] = 2
# img[img == 0] = 1
# # 1: del, 2:crack, 255: back
# path = "./gtFine/new/" + path
# cv2.imwrite(path, img)
###Output
_____no_output_____
###Markdown
This block replaces color with class ID
###Code
thresh = 10
CLASS = 1
for path in crack_imgs:
img = np.array(cv2.imread("./gtFine/GAN_del_rgb/" + path, 0))
img[img < thresh] = 0
img[img >= thresh] = CLASS
cv2.imwrite("./gtFine/GAN_del_rgb/labels/" + path[:-3] + "png", img)
print(np.unique(img, return_counts=True))
# plt.imshow(img)
# break
###Output
(array([0, 1], dtype=uint8), array([60414, 5122]))
(array([0, 1], dtype=uint8), array([54459, 11077]))
(array([0, 1], dtype=uint8), array([59177, 6359]))
(array([0, 1], dtype=uint8), array([54577, 10959]))
(array([0, 1], dtype=uint8), array([60130, 5406]))
(array([0, 1], dtype=uint8), array([57982, 7554]))
(array([0, 1], dtype=uint8), array([60421, 5115]))
(array([0, 1], dtype=uint8), array([59517, 6019]))
(array([0, 1], dtype=uint8), array([59865, 5671]))
(array([0, 1], dtype=uint8), array([57424, 8112]))
(array([0, 1], dtype=uint8), array([51618, 13918]))
(array([0, 1], dtype=uint8), array([61601, 3935]))
(array([0, 1], dtype=uint8), array([50470, 15066]))
(array([0, 1], dtype=uint8), array([53198, 12338]))
(array([0, 1], dtype=uint8), array([58771, 6765]))
(array([0, 1], dtype=uint8), array([53209, 12327]))
(array([0, 1], dtype=uint8), array([50876, 14660]))
(array([0, 1], dtype=uint8), array([58832, 6704]))
(array([0, 1], dtype=uint8), array([56493, 9043]))
(array([0, 1], dtype=uint8), array([50950, 14586]))
(array([0, 1], dtype=uint8), array([60786, 4750]))
(array([0, 1], dtype=uint8), array([57218, 8318]))
(array([0, 1], dtype=uint8), array([58522, 7014]))
(array([0, 1], dtype=uint8), array([60845, 4691]))
(array([0, 1], dtype=uint8), array([45096, 20440]))
(array([0, 1], dtype=uint8), array([59306, 6230]))
(array([0, 1], dtype=uint8), array([58951, 6585]))
(array([0, 1], dtype=uint8), array([58288, 7248]))
(array([0, 1], dtype=uint8), array([51138, 14398]))
(array([0, 1], dtype=uint8), array([58956, 6580]))
(array([0, 1], dtype=uint8), array([60614, 4922]))
(array([0, 1], dtype=uint8), array([55203, 10333]))
(array([0, 1], dtype=uint8), array([54234, 11302]))
(array([0, 1], dtype=uint8), array([51324, 14212]))
(array([0, 1], dtype=uint8), array([63993, 1543]))
(array([0, 1], dtype=uint8), array([57891, 7645]))
(array([0, 1], dtype=uint8), array([59130, 6406]))
(array([0, 1], dtype=uint8), array([58764, 6772]))
(array([0, 1], dtype=uint8), array([52906, 12630]))
(array([0, 1], dtype=uint8), array([59481, 6055]))
(array([0, 1], dtype=uint8), array([56516, 9020]))
(array([0, 1], dtype=uint8), array([62483, 3053]))
(array([0, 1], dtype=uint8), array([55417, 10119]))
(array([0, 1], dtype=uint8), array([59920, 5616]))
(array([0, 1], dtype=uint8), array([57600, 7936]))
(array([0, 1], dtype=uint8), array([37400, 28136]))
(array([0, 1], dtype=uint8), array([60930, 4606]))
(array([0, 1], dtype=uint8), array([60133, 5403]))
(array([0, 1], dtype=uint8), array([52356, 13180]))
(array([0, 1], dtype=uint8), array([50682, 14854]))
(array([0, 1], dtype=uint8), array([60233, 5303]))
(array([0, 1], dtype=uint8), array([60459, 5077]))
(array([0, 1], dtype=uint8), array([53286, 12250]))
(array([0, 1], dtype=uint8), array([50944, 14592]))
(array([0, 1], dtype=uint8), array([60267, 5269]))
(array([0, 1], dtype=uint8), array([63640, 1896]))
(array([0, 1], dtype=uint8), array([53002, 12534]))
(array([0, 1], dtype=uint8), array([53125, 12411]))
(array([0, 1], dtype=uint8), array([59977, 5559]))
(array([0, 1], dtype=uint8), array([53878, 11658]))
(array([0, 1], dtype=uint8), array([59757, 5779]))
(array([0, 1], dtype=uint8), array([49072, 16464]))
(array([0, 1], dtype=uint8), array([59076, 6460]))
(array([0, 1], dtype=uint8), array([59524, 6012]))
(array([0, 1], dtype=uint8), array([57183, 8353]))
(array([0, 1], dtype=uint8), array([50794, 14742]))
(array([0, 1], dtype=uint8), array([54904, 10632]))
(array([0, 1], dtype=uint8), array([54253, 11283]))
(array([0, 1], dtype=uint8), array([57923, 7613]))
(array([0, 1], dtype=uint8), array([57731, 7805]))
(array([0, 1], dtype=uint8), array([60635, 4901]))
(array([0, 1], dtype=uint8), array([47690, 17846]))
(array([0, 1], dtype=uint8), array([58080, 7456]))
(array([0, 1], dtype=uint8), array([57131, 8405]))
(array([0, 1], dtype=uint8), array([56333, 9203]))
(array([0, 1], dtype=uint8), array([60345, 5191]))
(array([0, 1], dtype=uint8), array([47844, 17692]))
(array([0, 1], dtype=uint8), array([52458, 13078]))
(array([0, 1], dtype=uint8), array([60042, 5494]))
(array([0, 1], dtype=uint8), array([46726, 18810]))
(array([0, 1], dtype=uint8), array([49593, 15943]))
(array([0, 1], dtype=uint8), array([59848, 5688]))
(array([0, 1], dtype=uint8), array([53051, 12485]))
(array([0, 1], dtype=uint8), array([52838, 12698]))
(array([0, 1], dtype=uint8), array([51920, 13616]))
(array([0, 1], dtype=uint8), array([60386, 5150]))
(array([0, 1], dtype=uint8), array([58968, 6568]))
(array([0, 1], dtype=uint8), array([59745, 5791]))
(array([0, 1], dtype=uint8), array([62821, 2715]))
(array([0, 1], dtype=uint8), array([60143, 5393]))
(array([0, 1], dtype=uint8), array([60006, 5530]))
(array([0, 1], dtype=uint8), array([61338, 4198]))
(array([0, 1], dtype=uint8), array([59115, 6421]))
(array([0, 1], dtype=uint8), array([59939, 5597]))
(array([0, 1], dtype=uint8), array([58708, 6828]))
(array([0, 1], dtype=uint8), array([58884, 6652]))
(array([0, 1], dtype=uint8), array([59892, 5644]))
(array([0, 1], dtype=uint8), array([58935, 6601]))
(array([0, 1], dtype=uint8), array([43870, 21666]))
(array([0, 1], dtype=uint8), array([47543, 17993]))
###Markdown
Augmentation tests
###Code
# images
images = [path for path in os.listdir("./leftImg8bit/delamination") if path.endswith(".png")]
path = images[50]
img = cv2.imread("./leftImg8bit/delamination/" + path)
dst = cv2.fastNlMeansDenoising(img,None,35,25,9)
plt.subplot(121),plt.imshow(img)
plt.subplot(122),plt.imshow(dst)
plt.show()
###Output
_____no_output_____
###Markdown
image testing for pixels
###Code
# image = cv2.imread("./gtFine/GAN_crack/16_226.png")
# image = cv2.imread("./gtFine/GAN_crack/16_227.png")
import matplotlib.image as mpimg
image = np.array(cv2.imread("./gtFine/GAN_crack/16_227.png", 0))
# cv2.imwrite("out.png", image)
image.shape
image[image == 2] = 255
image[image<=0]=0
image[image>0] =255
plt.imshow(image)
np.unique(image)
image[image==255] =255
###Output
_____no_output_____ |
object_detection_for_image_tagging/life_stages/archive/insect_lifestages_yolov3.ipynb | ###Markdown
Using YOLO v3 pre-trained on Google Open Images to detect insect life stages (juvenile, adult) from EOL images---*Last Updated 22 February 2021* Using a YOLOv3 model pre-trained on Google Open Images as a method to do customized, large-scale image processing. Insect images will be tagged using the location and dimensions of the detected life stages to improve search features of EOL. Installs---
###Code
# Mount google drive to import/export files
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
# clone darknet repo
%cd /content/drive/My Drive/train/darknet2
#!git clone https://github.com/AlexeyAB/darknet
# change makefile to have GPU and OPENCV enabled
%cd darknet
!sed -i 's/OPENCV=0/OPENCV=1/' Makefile
!sed -i 's/GPU=0/GPU=1/' Makefile
!sed -i 's/CUDNN=0/CUDNN=1/' Makefile
!sed -i 's/CUDNN_HALF=0/CUDNN_HALF=1/' Makefile
# verify CUDA
!/usr/local/cuda/bin/nvcc --version
# make darknet (builds darknet so that you can then use the darknet executable file to run or train object detectors)
!make
# download pre-trained weights (only run once)
#!wget https://pjreddie.com/media/files/yolov3-openimages.weights
# For importing/exporting files, working with arrays, etc
import os
import pathlib
import six.moves.urllib as urllib
import sys
import tarfile
import zipfile
import numpy as np
import csv
import matplotlib.pyplot as plt
import time
import pandas as pd
# For downloading the images
!apt-get install aria2
# For drawing onto and plotting the images
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageColor
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageOps
import cv2
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
###Output
_____no_output_____
###Markdown
Classify images--- Temporarily download images from EOL bundle to Google Drive (YOLO cannot directly parse URL images)
###Code
# Download images
bundle = "https://editors.eol.org/other_files/bundle_images/files/images_for_Lepidoptera_20K_breakdown_download_000001.txt" #@param {type:"string"}
df = pd.read_csv(bundle)
# Take subset of bundle
# TO DO: Change file name for each bundle/run abcd if doing 4 batches using dropdown form to right
ss = "life_stage_tags_c" #@param ["life_stage_tags_a", "life_stage_tags_b", "life_stage_tags_c", "life_stage_tags_d"] {allow-input: true}
ss = ss + ".txt"
# Run in 4 batches of 5k images each (batch a is from 0-5000, b from 5000 to 10000, etc)
if "a" in ss:
a=0
b=5000
elif "b" in ss:
a=5000
b=10000
elif "c" in ss:
a=10000
b=15000
elif "d" in ss:
a=15000
b=20000
# Save subset to text file for image download
df = df.iloc[a:b]
outpath = "/content/drive/My Drive/train/darknet/data/imgs/" + ss
df.to_csv(outpath, sep='\n', index=False, header=False)
# Download images (takes 7-10 min per 5k imgs, aria2 downloads 16imgs at a time)
%cd /content/drive/My Drive/train/darknet/data/imgs
!aria2c -x 16 -s 1 -i $ss
# Check how many images downloaded
print("Number of images downloaded to Google Drive: ")
!ls . | wc -l
# Move text file to image_data/bundles
%cd ../
!mv imgs/*.txt img_info/
# Make imgs.txt file to run images through YOLO for inference in batches
%cd /content/drive/My Drive/train/darknet/data/
import glob
import os
path = "/content/drive/My Drive/train/darknet/data/imgs"
inf_ss = path+'/'+ss
with open(inf_ss, 'w', encoding='utf-8') as f:
for dir, dirs, files in os.walk(path):
files = [fn for fn in files]
for fn in files:
if 'txt' not in fn:
out = "data/imgs/" + fn
f.writelines(out + '\n')
# Inspect imgs.txt file to confirm length and content
df = pd.read_csv(inf_ss, header=None)
print(df.head())
print(len(df))
###Output
_____no_output_____
###Markdown
Run images through trained model
###Code
# this creates a symbolic link so that now the path /content/gdrive/My\ Drive/ is equal to /mydrive
!ln -s /content/gdrive/My\ Drive/ /mydrive
!ls /mydrive
# TO DO: In next bloc, change inference image file list name at end of line after "<" to match inf_ss defined above
# ex: data/imgs/plant_poll_coocc_tags_a.txt
print("filename to copy-paste into code block below:", os.path.basename(inf_ss))
# TO DO: Change inference image file list name at end of line after "<" to match inf_ss defined above
%cd /content/drive/My Drive/train/darknet
# darknet run with external output flag to print bounding box coordinates
!./darknet detector test cfg/openimages.data cfg/yolov3-openimages.cfg yolov3-openimages.weights -dont_show -save_labels < data/imgs/life_stage_tags_c.txt
###Output
_____no_output_____
###Markdown
Post-process model predictions---
###Code
# Combine individual prediction files for each image to all_predictions.txt
# Delete image file list for inference
path = "/content/drive/My Drive/train/darknet/data/imgs"
inf_ss = path+'/'+ss
inf_ss = "data/imgs/"+ss
!rm $inf_ss
# Combine individual text files and image filenames into all_predictions.txt
fns = os.listdir('data/imgs')
with open('data/results/all_predictions.txt', 'w') as outfile:
header = "class_id x y w h img_id"
outfile.write(header + "\n")
for fn in fns:
if 'txt' in fn:
with open('data/imgs/'+fn) as infile:
lines = infile.readlines()
newlines = [''.join([x.strip(), ' ' + os.path.splitext(fn)[0] + '\n']) for x in lines]
outfile.writelines(newlines)
# Inspect saved predictions
df = pd.read_csv('data/results/all_predictions.txt')
print(df.head())
# Delete all individual prediction files
!rm -r data/imgs/*.txt
# Delete all image files now that they have been used for inference
!rm -r data/imgs/*
# Create final predictions dataframe with class names (instead of numbers) and image urls
# EOL image url bundle
df = pd.read_csv(bundle)
df.columns = ['url']
print(df)
# Model predictions with number-coded classes
predict = pd.read_csv('data/results/all_predictions.txt', header=0, sep=" ")
predict.class_id = predict.class_id - 1 #class_id counts started from 1 instead of 0 from YOLO
print(predict)
# Add class names to model predictions
classnames = pd.read_table('data/openimages.names')
classnames.columns = ['classname']
#print(classnames)
tag_df = predict.copy()
di = pd.Series(classnames.classname.values,index=classnames.index).to_dict()
tag_df.replace({"class_id":di}, inplace=True)
tag_df['class_id'] = tag_df['class_id'].astype(str)
print(tag_df)
# Add urls to model predictions
map_urls = df.copy()
img_ids = map_urls['url'].apply(lambda x: os.path.splitext((os.path.basename(x)))[0])
map_urls['img_id'] = img_ids
#print(map_urls)
tag_df.set_index('img_id', inplace=True, drop=True)
map_urls.set_index('img_id', inplace=True, drop=True)
mapped_tagdf = tag_df.merge(map_urls, left_index=True, right_index=True)
mapped_tagdf.reset_index(drop=False, inplace=True)
mapped_tagdf.drop_duplicates(inplace=True, ignore_index=True)
print(mapped_tagdf.head())
# Save final tags to file
fn = os.path.splitext(os.path.basename(inf_ss))[0]
outpath = 'data/results/' + fn + '.tsv'
mapped_tagdf.to_csv(outpath, sep="\t", index=False)
###Output
_____no_output_____
###Markdown
Combine tag files A-D---
###Code
# Write header row of output tagging file
# TO DO: Change file name for each bundle/run abcd if doing 4 batches using dropdown form to right
tags_file = "life_stage_tags_a" #@param {type:"string"}
tags_fpath = "/content/drive/My Drive/train/darknet2/darknet/data/results/" + tags_file + ".tsv"
# Combine exported model predictions and confidence values from above to one dataframe
fpath = os.path.splitext(tags_fpath)[0]
base = fpath.rsplit('_',1)[0] + '_'
exts = ['a.tsv', 'b.tsv', 'c.tsv', 'd.tsv']
all_filenames = [base + e for e in exts]
df1 = pd.concat([pd.read_csv(f, sep='\t', header=0, na_filter = False) for f in all_filenames], ignore_index=True)
# Filter for desired classes
filter1 = ['Ant', 'Bee', 'Beetle', 'Butterfly', 'Dragonfly', 'Insect', \
'Invertebrate', 'Moths and butterflies']
pattern = '|'.join(filter1)
df = df1.copy()
print(df.class_id)
print(df.class_id[df.class_id.str.contains(pattern)])
df.loc[df['class_id'].str.contains(pattern), 'class_id'] = 'Adult'
print(df.class_id[df.class_id.str.contains(pattern)])
filter2 = ['Caterpillar', 'Centipede', 'Worm']
pattern = '|'.join(filter2)
df.loc[df['class_id'].str.contains(pattern), 'class_id'] = 'Juvenile'
patterns = '|'.join(filter1+filter2+['Adult','Juvenile'])
df.loc[~df['class_id'].str.contains(patterns), 'class_id'] = 'None'
print(df.class_id)
print(len(df.class_id[df.class_id != 'None']))
# Write results to tsv
print(df.head())
outfpath = base + 'finaltags.tsv'
print(outfpath)
df.to_csv(outfpath, sep='\t', index=False)
###Output
_____no_output_____
###Markdown
Display predictions on images---Inspect detection results and verify that they are as expected
###Code
# TO DO: Do you want to use the tagging file exported above?
use_outfpath = "yes" #@param ["yes", "no"]
# If no, choose other path to use
otherpath = "\u003Cpath to other tag file> " #@param {type:"string"}
if use_outpath == "yes":
outfpath = outfpath
else:
outfpath = otherpath
df = pd.read_csv(outfpath, sep="\t", header=0)
print(df.head())
# For uploading an image from url
# Modified from https://www.pyimagesearch.com/2015/03/02/convert-url-to-image-with-python-and-opencv/
def url_to_image(url):
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image
# Display crop dimensions on images
# Adjust line below to see up to 50 images displayed at a time
a = 0 #@param {type:"slider", min:0, max:5000, step:50}
b = a+50
for i, row in df.iloc[a:b].iterrows():
# Read in image
url = df['url'][i]
img = url_to_image(url)
h,w = img.shape[:2]
# Define variables needed to draw bounding box on image
xmin = round((df['x'][i] - (df['w'][i]/2))*w)
if (xmin < 0): xmin = 0
ymin = round((df['y'][i] - (df['h'][i]/2))*h)
if (ymin < 0): ymin = 0
xmax = round(xmin + (df['w'][i]) * w)
if (xmax > w-1): xmax = w-1
ymax = round(ymin + (df['h'][i].astype(int)) * h)
if (ymax > 0): ymax = h-1
# Set box/font color and size
maxdim = max(df['w'][i],df['h'][i])
fontScale = 1
box_col = (255, 0, 157)
# Draw tag label on image
tag = df['class_id'][i]
image_wbox = cv2.putText(img, tag, (xmin+7, ymax-12), cv2.FONT_HERSHEY_SIMPLEX, fontScale, box_col, 2, cv2.LINE_AA)
# Draw tag box on image
image_wbox = cv2.rectangle(img, (xmin, ymax), (xmax, ymin), box_col, 5)
# Plot and show cropping boxes on images
_, ax = plt.subplots(figsize=(10, 10))
ax.imshow(image_wbox)
# Display image URL above image to facilitate troubleshooting/fine-tuning of data reformatting and tidying steps in convert_bboxdims.py or preprocessing.ipynb
plt.title('{}'.format(url, xmin, ymin, xmax, ymax))
###Output
_____no_output_____ |
7_Image_Classification_with_CNNs_fashion_mnist_data_set.ipynb | ###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###Output
_____no_output_____
###Markdown
Image Classification with Convolutional Neural Networks Run in Google Colab View source on GitHub In this tutorial, we'll build and train a neural network to classify images of clothing, like sneakers and shirts.It's okay if you don't understand everything. This is a fast-paced overview of a complete TensorFlow program, with explanations along the way. The goal is to get the general sense of a TensorFlow project, not to catch every detail.This guide uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow. Install and import dependenciesWe'll need [TensorFlow Datasets](https://www.tensorflow.org/datasets/), an API that simplifies downloading and accessing datasets, and provides several sample datasets to work with. We're also using a few helper libraries.
###Code
!pip install -U tensorflow_datasets
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow==2.0.0-alpha0
# Import TensorFlow and TensorFlow Datasets
import tensorflow as tf
import tensorflow_datasets as tfds
# let tensorflow only log errors
#tf.logging.set_verbosity(tf.logging.ERROR)
# Helper libraries
import math
import numpy as np
import matplotlib.pyplot as plt
# Improve progress bar display
import tqdm
import tqdm.auto
tqdm.tqdm = tqdm.auto.tqdm
print(tf.__version__)
# This will go away in the future.
# If this gives an error, you might be running TensorFlow 2 or above
# If so, the just comment out this line and run this cell again
#tf.enable_eager_execution()
###Output
_____no_output_____
###Markdown
Import the Fashion MNIST dataset This guide uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset, which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 $\times$ 28 pixels), as seen here: <img src="https://tensorflow.org/images/fashion-mnist-sprite.png" alt="Fashion MNIST sprite" width="600"> Figure 1. Fashion-MNIST samples (by Zalando, MIT License). Fashion MNIST is intended as a drop-in replacement for the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset—often used as the "Hello, World" of machine learning programs for computer vision. The MNIST dataset contains images of handwritten digits (0, 1, 2, etc) in an identical format to the articles of clothing we'll use here.This guide uses Fashion MNIST for variety, and because it's a slightly more challenging problem than regular MNIST. Both datasets are relatively small and are used to verify that an algorithm works as expected. They're good starting points to test and debug code. We will use 60,000 images to train the network and 10,000 images to evaluate how accurately the network learned to classify images. You can access the Fashion MNIST directly from TensorFlow, using the [Datasets](https://www.tensorflow.org/datasets) API:
###Code
dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True)
train_dataset, test_dataset = dataset['train'], dataset['test']
###Output
_____no_output_____
###Markdown
Loading the dataset returns metadata as well as a *training dataset* and *test dataset*.* The model is trained using `train_dataset`.* The model is tested against `test_dataset`.The images are 28 $\times$ 28 arrays, with pixel values in the range `[0, 255]`. The *labels* are an array of integers, in the range `[0, 9]`. These correspond to the *class* of clothing the image represents: Label Class 0 T-shirt/top 1 Trouser 2 Pullover 3 Dress 4 Coat 5 Sandal 6 Shirt 7 Sneaker 8 Bag 9 Ankle boot Each image is mapped to a single label. Since the *class names* are not included with the dataset, store them here to use later when plotting the images:
###Code
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
###Output
_____no_output_____
###Markdown
Explore the data> Indented blockLet's explore the format of the dataset before training the model. The following shows there are 60,000 images in the training set, and 10000 images in the test set:
###Code
num_train_examples = metadata.splits['train'].num_examples
num_test_examples = metadata.splits['test'].num_examples
print("Number of training examples: {}".format(num_train_examples))
print("Number of test examples: {}".format(num_test_examples))
###Output
_____no_output_____
###Markdown
Preprocess the dataThe value of each pixel in the image data is an integer in the range `[0,255]`. For the model to work properly, these values need to be normalized to the range `[0,1]`. So here we create a normalization function, and then apply it to each image in the test and train datasets.
###Code
def normalize(images, labels):
images = tf.cast(images, tf.float32)
images /= 255
return images, labels
# The map function applies the normalize function to each element in the train
# and test datasets
train_dataset = train_dataset.map(normalize)
test_dataset = test_dataset.map(normalize)
test_dataset
train_dataset
###Output
_____no_output_____
###Markdown
Explore the processed dataLet's plot an image to see what it looks like.
###Code
# Take a single image, and remove the color dimension by reshaping
for image, label in test_dataset.take(1):
break
image = image.numpy().reshape((28,28))
# Plot the image - voila a piece of fashion clothing
plt.figure()
plt.imshow(image, cmap=plt.cm.binary)
plt.colorbar()
plt.grid(False)
plt.show()
###Output
_____no_output_____
###Markdown
Display the first 25 images from the *training set* and display the class name below each image. Verify that the data is in the correct format and we're ready to build and train the network.
###Code
plt.figure(figsize=(10,10))
i = 0
for (image, label) in test_dataset.take(25):
image = image.numpy().reshape((28,28))
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(image, cmap=plt.cm.binary)
plt.xlabel(class_names[label], color='white')
i += 1
plt.show()
###Output
_____no_output_____
###Markdown
Build the modelBuilding the neural network requires configuring the layers of the model, then compiling the model. Setup the layersThe basic building block of a neural network is the *layer*. A layer extracts a representation from the data fed into it. Hopefully, a series of connected layers results in a representation that is meaningful for the problem at hand.Much of deep learning consists of chaining together simple layers. Most layers, like `tf.keras.layers.Dense`, have internal parameters which are adjusted ("learned") during training.
###Code
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3,3), padding='same', activation=tf.nn.relu,
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D((2, 2), strides=2),
tf.keras.layers.Conv2D(64, (3,3), padding='same', activation=tf.nn.relu),
tf.keras.layers.MaxPooling2D((2, 2), strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.summary()
###Output
_____no_output_____
###Markdown
This network layers are:* **"convolutions"** `tf.keras.layers.Conv2D and MaxPooling2D`— Network start with two pairs of Conv/MaxPool. The first layer is a Conv2D filters (3,3) being applied to the input image, retaining the original image size by using padding, and creating 32 output (convoluted) images (so this layer creates 32 convoluted images of the same size as input). After that, the 32 outputs are reduced in size using a MaxPooling2D (2,2) with a stride of 2. The next Conv2D also has a (3,3) kernel, takes the 32 images as input and creates 64 outputs which are again reduced in size by a MaxPooling2D layer. * **output** `tf.keras.layers.Dense` — A 128-neuron, followed by 10-node *softmax* layer. Each node represents a class of clothing. As in the previous layer, the final layer takes input from the 128 nodes in the layer before it, and outputs a value in the range `[0, 1]`, representing the probability that the image belongs to that class. The sum of all 10 node values is 1. Compile the modelBefore the model is ready for training, it needs a few more settings. These are added during the model's *compile* step:* *Loss function* — An algorithm for measuring how far the model's outputs are from the desired output. The goal of training is this measures loss.* *Optimizer* —An algorithm for adjusting the inner parameters of the model in order to minimize loss.* *Metrics* —Used to monitor the training and testing steps. The following example uses *accuracy*, the fraction of the images that are correctly classified.
###Code
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
###Output
_____no_output_____
###Markdown
Train the modelFirst, we define the iteration behavior for the train dataset:1. Repeat forever by specifying `dataset.repeat()` (the `epochs` parameter described below limits how long we perform training).2. The `dataset.shuffle(60000)` randomizes the order so our model cannot learn anything from the order of the examples.3. And `dataset.batch(32)` tells `model.fit` to use batches of 32 images and labels when updating the model variables.Training is performed by calling the `model.fit` method:1. Feed the training data to the model using `train_dataset`.2. The model learns to associate images and labels.3. The `epochs=5` parameter limits training to 5 full iterations of the training dataset, so a total of 5 * 60000 = 300000 examples.(Don't worry about `steps_per_epoch`, the requirement to have this flag will soon be removed.)
###Code
BATCH_SIZE = 32
train_dataset = train_dataset.repeat().shuffle(num_train_examples).batch(BATCH_SIZE)
test_dataset = test_dataset.batch(BATCH_SIZE)
model.fit(train_dataset, epochs=10, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE))
###Output
_____no_output_____
###Markdown
As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.97 (or 97%) on the training data. Evaluate accuracyNext, compare how the model performs on the test dataset. Use all examples we have in the test dataset to assess accuracy.
###Code
test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32))
print('Accuracy on test dataset:', test_accuracy)
###Output
_____no_output_____
###Markdown
As it turns out, the accuracy on the test dataset is smaller than the accuracy on the training dataset. This is completely normal, since the model was trained on the `train_dataset`. When the model sees images it has never seen during training, (that is, from the `test_dataset`), we can expect performance to go down. Make predictions and exploreWith the model trained, we can use it to make predictions about some images.
###Code
for test_images, test_labels in test_dataset.take(1):
test_images = test_images.numpy()
test_labels = test_labels.numpy()
predictions = model.predict(test_images)
predictions.shape
###Output
_____no_output_____
###Markdown
Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction:
###Code
predictions[0]
###Output
_____no_output_____
###Markdown
A prediction is an array of 10 numbers. These describe the "confidence" of the model that the image corresponds to each of the 10 different articles of clothing. We can see which label has the highest confidence value:
###Code
np.argmax(predictions[0])
###Output
_____no_output_____
###Markdown
So the model is most confident that this image is a shirt, or `class_names[6]`. And we can check the test label to see this is correct:
###Code
test_labels[0]
###Output
_____no_output_____
###Markdown
We can graph this to look at the full set of 10 channels
###Code
def plot_image(i, predictions_array, true_labels, images):
predictions_array, true_label, img = predictions_array[i], true_labels[i], images[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img[...,0], cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
###Output
_____no_output_____
###Markdown
Let's look at the 0th image, predictions, and prediction array.
###Code
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
###Output
_____no_output_____
###Markdown
Let's plot several images with their predictions. Correct prediction labels are blue and incorrect prediction labels are red. The number gives the percent (out of 100) for the predicted label. Note that it can be wrong even when very confident.
###Code
# Plot the first X test images, their predicted label, and the true label
# Color correct predictions in blue, incorrect predictions in red
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
###Output
_____no_output_____
###Markdown
Finally, use the trained model to make a prediction about a single image.
###Code
# Grab an image from the test dataset
img = test_images[0]
print(img.shape)
###Output
_____no_output_____
###Markdown
`tf.keras` models are optimized to make predictions on a *batch*, or collection, of examples at once. So even though we're using a single image, we need to add it to a list:
###Code
# Add the image to a batch where it's the only member.
img = np.array([img])
print(img.shape)
###Output
_____no_output_____
###Markdown
Now predict the image:
###Code
predictions_single = model.predict(img)
print(predictions_single)
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
###Output
_____no_output_____
###Markdown
`model.predict` returns a list of lists, one for each image in the batch of data. Grab the predictions for our (only) image in the batch:
###Code
np.argmax(predictions_single[0])
###Output
_____no_output_____
###Markdown
And, as before, the model predicts a label of 6 (shirt). ExercisesExperiment with different models and see how the accuracy results differ. In particular change the following parameters:* Set training epochs set to 1* Number of neurons in the Dense layer following the Flatten one. For example, go really low (e.g. 10) in ranges up to 512 and see how accuracy changes* Add additional Dense layers between the Flatten and the final Dense(10, activation=tf.nn.softmax), experiment with different units in these layers* Don't normalize the pixel values, and see the effect that hasRemember to enable GPU to make everything run faster (Runtime -> Change runtime type -> Hardware accelerator -> GPU).Also, if you run into trouble, simply reset the entire environment and start from the beginning:* Edit -> Clear all outputs* Runtime -> Reset all runtimes
###Code
import os, signal
os.kill(os.getpid(), signal.SIGKILL)
###Output
_____no_output_____ |
ipython notebooks/intro_to_neural_nets.ipynb | ###Markdown
Copyright 2017 Google LLC.
###Code
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Intro to Neural Networks **Learning Objectives:** * Define a neural network (NN) and its hidden layers using the TensorFlow `DNNRegressor` class * Train a neural network to learn nonlinearities in a dataset and achieve better performance than a linear regression model In the previous exercises, we used synthetic features to help our model incorporate nonlinearities.One important set of nonlinearities was around latitude and longitude, but there may be others.We'll also switch back, for now, to a standard regression task, rather than the logistic regression task from the previous exercise. That is, we'll be predicting `median_house_value` directly. SetupFirst, let's load and prepare the data.
###Code
from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
california_housing_dataframe = california_housing_dataframe.reindex(
np.random.permutation(california_housing_dataframe.index))
def preprocess_features(california_housing_dataframe):
"""Prepares input features from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the features to be used for the model, including
synthetic features.
"""
selected_features = california_housing_dataframe[
["latitude",
"longitude",
"housing_median_age",
"total_rooms",
"total_bedrooms",
"population",
"households",
"median_income"]]
processed_features = selected_features.copy()
# Create a synthetic feature.
processed_features["rooms_per_person"] = (
california_housing_dataframe["total_rooms"] /
california_housing_dataframe["population"])
return processed_features
def preprocess_targets(california_housing_dataframe):
"""Prepares target features (i.e., labels) from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the target feature.
"""
output_targets = pd.DataFrame()
# Scale the target to be in units of thousands of dollars.
output_targets["median_house_value"] = (
california_housing_dataframe["median_house_value"] / 1000.0)
return output_targets
# Choose the first 12000 (out of 17000) examples for training.
training_examples = preprocess_features(california_housing_dataframe.head(12000))
training_targets = preprocess_targets(california_housing_dataframe.head(12000))
# Choose the last 5000 (out of 17000) examples for validation.
validation_examples = preprocess_features(california_housing_dataframe.tail(5000))
validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))
# Double-check that we've done the right thing.
print("Training examples summary:")
display.display(training_examples.describe())
print("Validation examples summary:")
display.display(validation_examples.describe())
print("Training targets summary:")
display.display(training_targets.describe())
print("Validation targets summary:")
display.display(validation_targets.describe())
###Output
Training examples summary:
###Markdown
Building a Neural NetworkThe NN is defined by the [DNNRegressor](https://www.tensorflow.org/api_docs/python/tf/estimator/DNNRegressor) class.Use **`hidden_units`** to define the structure of the NN. The `hidden_units` argument provides a list of ints, where each int corresponds to a hidden layer and indicates the number of nodes in it. For example, consider the following assignment:`hidden_units=[3,10]`The preceding assignment specifies a neural net with two hidden layers:* The first hidden layer contains 3 nodes.* The second hidden layer contains 10 nodes.If we wanted to add more layers, we'd add more ints to the list. For example, `hidden_units=[10,20,30,40]` would create four layers with ten, twenty, thirty, and forty units, respectively.By default, all hidden layers will use ReLu activation and will be fully connected.
###Code
def construct_feature_columns(input_features):
"""Construct the TensorFlow Feature Columns.
Args:
input_features: The names of the numerical input features to use.
Returns:
A set of feature columns
"""
return set([tf.feature_column.numeric_column(my_feature)
for my_feature in input_features])
def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
"""Trains a neural net regression model.
Args:
features: pandas DataFrame of features
targets: pandas DataFrame of targets
batch_size: Size of batches to be passed to the model
shuffle: True or False. Whether to shuffle the data.
num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely
Returns:
Tuple of (features, labels) for next data batch
"""
# Convert pandas data into a dict of np arrays.
features = {key:np.array(value) for key,value in dict(features).items()}
# Construct a dataset, and configure batching/repeating.
ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit
ds = ds.batch(batch_size).repeat(num_epochs)
# Shuffle the data, if specified.
if shuffle:
ds = ds.shuffle(10000)
# Return the next batch of data.
features, labels = ds.make_one_shot_iterator().get_next()
return features, labels
def train_nn_regression_model(
learning_rate,
steps,
batch_size,
hidden_units,
training_examples,
training_targets,
validation_examples,
validation_targets):
"""Trains a neural network regression model.
In addition to training, this function also prints training progress information,
as well as a plot of the training and validation loss over time.
Args:
learning_rate: A `float`, the learning rate.
steps: A non-zero `int`, the total number of training steps. A training step
consists of a forward and backward pass using a single batch.
batch_size: A non-zero `int`, the batch size.
hidden_units: A `list` of int values, specifying the number of neurons in each layer.
training_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for training.
training_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for training.
validation_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for validation.
validation_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for validation.
Returns:
A `DNNRegressor` object trained on the training data.
"""
periods = 10
steps_per_period = steps / periods
# Create a DNNRegressor object.
my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
dnn_regressor = tf.estimator.DNNRegressor(
feature_columns=construct_feature_columns(training_examples),
hidden_units=hidden_units,
optimizer=my_optimizer,
)
# Create input functions.
training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value"],
batch_size=batch_size)
predict_training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value"],
num_epochs=1,
shuffle=False)
predict_validation_input_fn = lambda: my_input_fn(validation_examples,
validation_targets["median_house_value"],
num_epochs=1,
shuffle=False)
# Train the model, but do so inside a loop so that we can periodically assess
# loss metrics.
print("Training model...")
print("RMSE (on training data):")
training_rmse = []
validation_rmse = []
for period in range (0, periods):
# Train the model, starting from the prior state.
dnn_regressor.train(
input_fn=training_input_fn,
steps=steps_per_period
)
# Take a break and compute predictions.
training_predictions = dnn_regressor.predict(input_fn=predict_training_input_fn)
training_predictions = np.array([item['predictions'][0] for item in training_predictions])
validation_predictions = dnn_regressor.predict(input_fn=predict_validation_input_fn)
validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])
# Compute training and validation loss.
training_root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(training_predictions, training_targets))
validation_root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(validation_predictions, validation_targets))
# Occasionally print the current loss.
print(" period %02d : %0.2f" % (period, training_root_mean_squared_error))
# Add the loss metrics from this period to our list.
training_rmse.append(training_root_mean_squared_error)
validation_rmse.append(validation_root_mean_squared_error)
print("Model training finished.")
# Output a graph of loss metrics over periods.
plt.ylabel("RMSE")
plt.xlabel("Periods")
plt.title("Root Mean Squared Error vs. Periods")
plt.tight_layout()
plt.plot(training_rmse, label="training")
plt.plot(validation_rmse, label="validation")
plt.legend()
print("Final RMSE (on training data): %0.2f" % training_root_mean_squared_error)
print("Final RMSE (on validation data): %0.2f" % validation_root_mean_squared_error)
return dnn_regressor
###Output
_____no_output_____
###Markdown
Task 1: Train a NN Model**Adjust hyperparameters, aiming to drop RMSE below 110.**Run the following block to train a NN model. Recall that in the linear regression exercise with many features, an RMSE of 110 or so was pretty good. We'll aim to beat that.Your task here is to modify various learning settings to improve accuracy on validation data.Overfitting is a real potential hazard for NNs. You can look at the gap between loss on training data and loss on validation data to help judge if your model is starting to overfit. If the gap starts to grow, that is usually a sure sign of overfitting.Because of the number of different possible settings, it's strongly recommended that you take notes on each trial to help guide your development process.Also, when you get a good setting, try running it multiple times and see how repeatable your result is. NN weights are typically initialized to small random values, so you should see differences from run to run.
###Code
dnn_regressor = train_nn_regression_model(
learning_rate=0.003,
steps=1000,
batch_size=20,
hidden_units=[10, 4],
training_examples=training_examples,
training_targets=training_targets,
validation_examples=validation_examples,
validation_targets=validation_targets)
###Output
Training model...
RMSE (on training data):
period 00 : 171.80
period 01 : 173.01
period 02 : 178.83
period 03 : 171.75
###Markdown
SolutionClick below to see a possible solution **NOTE:** This selection of parameters is somewhat arbitrary. Here we've tried combinations that are increasingly complex, combined with training for longer, until the error falls below our objective. This may not be the best combination; others may attain an even lower RMSE. If your aim is to find the model that can attain the best error, then you'll want to use a more rigorous process, like a parameter search.
###Code
dnn_regressor = train_nn_regression_model(
learning_rate=0.001,
steps=2000,
batch_size=100,
hidden_units=[10, 10],
training_examples=training_examples,
training_targets=training_targets,
validation_examples=validation_examples,
validation_targets=validation_targets)
###Output
Training model...
RMSE (on training data):
period 00 : 159.98
period 01 : 151.18
period 02 : 142.43
period 03 : 133.82
period 04 : 127.15
period 05 : 122.52
period 06 : 114.59
period 07 : 114.61
period 08 : 109.14
period 09 : 108.00
Model training finished.
Final RMSE (on training data): 108.00
Final RMSE (on validation data): 107.19
###Markdown
Task 2: Evaluate on Test Data**Confirm that your validation performance results hold up on test data.**Once you have a model you're happy with, evaluate it on test data to compare that to validation performance.Reminder, the test data set is located [here](https://storage.googleapis.com/mledu-datasets/california_housing_test.csv).
###Code
california_housing_test_data = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_test.csv", sep=",")
# YOUR CODE HERE
test_examples = preprocess_features(california_housing_test_data)
test_targets = preprocess_targets(california_housing_test_data)
predict_testing_input_fn = lambda: my_input_fn(test_examples, test_targets["median_house_value"], num_epochs=1, shuffle=False)
test_predictions = dnn_regressor.predict(input_fn=predict_testing_input_fn)
test_predictions = np.array([item['predictions'][0] for item in test_predictions])
rmse = math.sqrt(metrics.mean_squared_error(test_predictions, test_targets))
print("Final RMSE on test data is %.2f" % rmse)
###Output
Final RMSE on test data is 107.43
###Markdown
SolutionClick below to see a possible solution. Similar to what the code at the top does, we just need to load the appropriate data file, preprocess it and call predict and mean_squared_error.Note that we don't have to randomize the test data, since we will use all records.
###Code
california_housing_test_data = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_test.csv", sep=",")
test_examples = preprocess_features(california_housing_test_data)
test_targets = preprocess_targets(california_housing_test_data)
predict_testing_input_fn = lambda: my_input_fn(test_examples,
test_targets["median_house_value"],
num_epochs=1,
shuffle=False)
test_predictions = dnn_regressor.predict(input_fn=predict_testing_input_fn)
test_predictions = np.array([item['predictions'][0] for item in test_predictions])
root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(test_predictions, test_targets))
print("Final RMSE (on test data): %0.2f" % root_mean_squared_error)
###Output
Final RMSE (on test data): 107.43
|
gan/lipton_female_to_male_repeat.ipynb | ###Markdown
Kolmogorov–Smirnov test
###Code
from scipy.stats import ks_2samp as ks
warnings.simplefilter('ignore', UserWarning)
lambda_l1 = 1e-4
ks_work_exp = []
ks_hair_len = []
fakes = []
for i in range(10):
print('GAN #{}'.format(i+1))
D, G, combined = create_gan_small(data_dim, trans_loss_func=squared_l1_loss, trans_loss_wt=lambda_l1)
train(D, G, combined, X1, X2, name1, name2, plot_progress=False)
X_fake2 = G.predict(X1)
fakes.append(X_fake2)
ks_work_exp.append(ks(X2[:,0], X_fake2[:,0]).statistic)
ks_hair_len.append(ks(X2[:,1], X_fake2[:,1]).statistic)
ks_work_exp = np.array(ks_work_exp)
ks_hair_len = np.array(ks_hair_len)
print(ks_work_exp, ks_work_exp.mean(), ks_work_exp.std())
print(ks_hair_len, ks_hair_len.mean(), ks_hair_len.std())
###Output
GAN #1
GAN #2
GAN #3
GAN #4
GAN #5
GAN #6
GAN #7
GAN #8
GAN #9
GAN #10
[0.0515 0.0461 0.0679 0.0521 0.055 0.0378 0.0492 0.0629 0.0375 0.0641] 0.052410000000000026 0.00990024747165444
[0.0238 0.0092 0.0247 0.0183 0.0366 0.0838 0.045 0.0674 0.0493 0.0729] 0.04310000000000001 0.02386340294258137
###Markdown
Mean Squared Error
###Code
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error as mse
X2_train, X2_test = train_test_split(X2, train_size=0.5, test_size=0.5)
lr_work_exp = LinearRegression().fit(X2_train[:,1:2], X2_train[:,0]) #predict work_exp from hair_len
lr_hair_len = LinearRegression().fit(X2_train[:,0:1], X2_train[:,1]) #predict hair_len from work_exp
print('work_exp MSE on real: {}'.format(mse(X2_test[:,0], lr_hair_len.predict(X2_test[:,1:2]))))
print('hair_len MSE on real: {}'.format(mse(X2_test[:,1], lr_hair_len.predict(X2_test[:,0:1]))))
mse_work_exp = []
mse_hair_len = []
for X_fake2 in fakes:
mse_work_exp.append(mse(X_fake2[:,0], lr_hair_len.predict(X_fake2[:,1:2])))
mse_hair_len.append(mse(X_fake2[:,1], lr_hair_len.predict(X_fake2[:,0:1])))
mse_work_exp = np.array(mse_work_exp)
mse_hair_len = np.array(mse_hair_len)
print(mse_work_exp, mse_work_exp.mean(), mse_work_exp.std())
print(mse_hair_len, mse_hair_len.mean(), mse_hair_len.std())
###Output
work_exp MSE on real: 2.010543298177521
hair_len MSE on real: 0.3305221132230612
[1.86572853 1.8547777 1.8785402 1.80400211 1.69368272 1.85677528
1.90254464 1.8043894 1.90357428 1.88197615] 1.8445991016343313 0.06010308303578143
[0.34198437 0.33678067 0.34249321 0.34243129 0.36220409 0.31056555
0.37430472 0.30450019 0.32173123 0.33662457] 0.3373619886445253 0.02024459886773657
|
python/Fig6-RingStability.ipynb | ###Markdown
Computing the ring stability of truncated contagion maps in dependence of the (a) threshold and (b) number of contagion steps
###Code
%load_ext autoreload
%autoreload 2
import cmap as conmap
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns;
sns.set_theme()
import pandas as pd
# For pretty colourmaps
import palettable
from matplotlib.colors import ListedColormap
sns.set_style("white")
from sklearn.decomposition import PCA
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
###Output
_____no_output_____
###Markdown
We construct a noisy ring lattice network.
###Code
noisyRL = conmap.constructNoisyRingLattice(numberNodes=400,geometricDegree=6,nongeometricDegree=2)
###Output
_____no_output_____
###Markdown
a) Ring stability in dependence of the thresholdWe run the truncated contagion maps.
###Code
%%time
tVec = np.arange(0,0.625,0.025)
nStepVec = [10,20,np.Inf]
correlationOut = []
ringStabilityOut = []
thresholdOut=[]
nStepOut=[]
for t in tVec:
print(t)
for nStep in nStepVec:
contagionMap = conmap.runTruncatedContagionMap(noisyRL,threshold=t,numberSteps=nStep,symmetric=True)
# compute correlation
correlation = conmap.computeCorrelationDistances(noisyRL,contagionMap,type='Spearman')
# compute Ring stability
ringStability = conmap.callRipser(contagionMap)
# save
thresholdOut.append(t)
nStepOut.append(nStep)
correlationOut.append(correlation)
ringStabilityOut.append(ringStability)
# save output DF
contagionMapPerformace = pd.DataFrame()
contagionMapPerformace['threshold'] = thresholdOut
contagionMapPerformace['number steps'] = nStepOut
contagionMapPerformace['spearman correlation'] = correlationOut
contagionMapPerformace['ring stability'] = ringStabilityOut
# We select the data we want to plot for each line
data_s10 = contagionMapPerformace[contagionMapPerformace['number steps'] == 10]
data_s20 = contagionMapPerformace[contagionMapPerformace['number steps'] == 20]
data_full = contagionMapPerformace[contagionMapPerformace['number steps'] == np.inf]
# We plot it
plt.plot(data_s10['threshold'],data_s10['ring stability'],color='#d64161',linewidth=2.0,label='$s=10$')
plt.plot(data_s20['threshold'],data_s20['ring stability'],color='#4161d6',linewidth=2.0,label='$s=20$')
plt.plot(data_full['threshold'],data_full['ring stability'],color='k',linewidth=2.0,label='$s=\infty$', linestyle='--')
plt.xlim([0,0.6])
plt.ylim([0,0.5])
# labels for data line
plt.text(0.22,0.40,s='$s=10$',color='#d64161',ha='right')
plt.text(0.22,0.45,s='$s=20$',color='#4161d6',ha='right')
plt.text(0.22,0.32,s='full contagion map',color='k',ha='right')
# vertical lines
plt.vlines(0.3/(1+0.3),ymin=0,ymax=0.5,color='#282828', linestyle=':')
plt.vlines(1/(2+2*0.3),ymin=0,ymax=0.5,color='#282828', linestyle=':')
plt.xlabel('threshold, $T$')
plt.ylabel('ring stability, $\Delta$')
plt.tight_layout()
plt.savefig('./figures/Fig6a-ringStabilityVsTreshold.pdf')
###Output
_____no_output_____
###Markdown
b) Ring stability in dependece of the number of steps.We run the truncated contagion maps.
###Code
%%time
tVec = [0.3]
nStepVec = [i for i in range(1,120,1)]
nStepVec.append(np.Inf)
correlationOut = []
ringStabilityOut = []
thresholdOut=[]
nStepOut=[]
for t in tVec:
for nStep in nStepVec:
print(nStep)
contagionMap = conmap.runTruncatedContagionMap(noisyRL,threshold=t,numberSteps=nStep,symmetric=True)
# compute correlation
correlation = conmap.computeCorrelationDistances(noisyRL,contagionMap,type='Spearman')
# compute Ring stability
ringStability = conmap.callRipser(contagionMap)
# save
thresholdOut.append(t)
nStepOut.append(nStep)
correlationOut.append(correlation)
ringStabilityOut.append(ringStability)
# save output DF
contagionMapPerformace_s = pd.DataFrame()
contagionMapPerformace_s['threshold'] = thresholdOut
contagionMapPerformace_s['number steps'] = nStepOut
contagionMapPerformace_s['spearman correlation'] = correlationOut
contagionMapPerformace_s['ring stability'] = ringStabilityOut
###Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
inf
CPU times: user 9min 15s, sys: 27 s, total: 9min 42s
Wall time: 18min 51s
###Markdown
Plotting
###Code
data_t03 = contagionMapPerformace_s[contagionMapPerformace_s['threshold'] == 0.3]
plt.plot(data_t03['number steps'],data_t03['ring stability'],color='#d64161',linewidth=2.0,label='truncated contagion map')
plt.axhline(y=data_t03[data_t03['number steps'] == np.inf]['ring stability'].values[0], color='k', linestyle='--',label=' ')
plt.text(42,0.50,s='truncated contagion map',color='#d64161')
plt.text(59,0.36,s='full contagion map',color='k')
plt.xlim([0,120])
plt.xlabel('number of steps, $s$')
plt.ylabel('ring stability, $\Delta$')
plt.tight_layout()
plt.savefig('./figures/Fig6b-ringStabilityVsSteps.pdf')
###Output
_____no_output_____
###Markdown
c) Number of steps $s$ for optimal ring stability in dependence of the network size
###Code
%%time
# networkSizeVec = np.ceil(10**np.arange(2,4,0.5))
# networkSizeVec = networkSizeVec.astype(int)
networkSizeVec = np.arange(50,525,25)
tVec = [0.3]
nStepVec = [i for i in range(1,120,5)]
nStepVec.append(np.Inf)
ringStabilityOut = []
thresholdOut=[]
nStepOut=[]
networkSizeOut=[]
for networkSize in networkSizeVec:
print(networkSize)
noisyRL = conmap.constructNoisyRingLattice(numberNodes=networkSize,geometricDegree=6,nongeometricDegree=2)
for t in tVec:
for nStep in nStepVec:
contagionMap = conmap.runTruncatedContagionMap(noisyRL,threshold=t,numberSteps=nStep,symmetric=True)
# compute Ring stability
ringStability = conmap.callRipser(contagionMap)
# save
thresholdOut.append(t)
nStepOut.append(nStep)
networkSizeOut.append(networkSize)
ringStabilityOut.append(ringStability)
# save output DF
contagionMapPerformace_s = pd.DataFrame()
contagionMapPerformace_s['threshold'] = thresholdOut
contagionMapPerformace_s['number steps'] = nStepOut
contagionMapPerformace_s['network size'] = networkSizeOut
contagionMapPerformace_s['ring stability'] = ringStabilityOut
# find the optimal number of steps for each of the sizes
optimalStepSize_Out=[]
for networkSize in networkSizeVec:
#
dataThisNetworkSize = contagionMapPerformace_s[contagionMapPerformace_s['network size'] == networkSize]
# find it
bestStepSize = dataThisNetworkSize['number steps'][dataThisNetworkSize['ring stability'].idxmax()]
# save it
optimalStepSize_Out.append(bestStepSize)
# should we find /pm 10% of the optimal ring stability?
plt.plot(networkSizeVec,0.1*networkSizeVec,color='k',linewidth=2.0,label='truncated contagion map',linestyle='--')
plt.scatter(networkSizeVec,optimalStepSize_Out,color='#d64161',linewidth=2.0,label='heuristic',marker='x')
plt.text(450,50,s='heuristic choice $N/10$',color='k',ha='right')
plt.ylabel('optimal number of steps, $s$')
plt.xlabel('network size, $N$')
plt.tight_layout()
plt.savefig('./figures/Fig6c-optimalNumberSteps.pdf')
np.mean(optimalStepSize_Out/networkSizeVec)
optimalStepSize_Out
networkSizeVec
###Output
_____no_output_____ |
run_eqtransformer_aktest.ipynb | ###Markdown
Environment and Repository Set-up
###Code
# Import modules
import numpy as np
import pandas as pd
import shutil
import os
from zipfile import ZipFile
import glob
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
!pip install obspy
# Install and set-up EQTransformer following installation via git
# NOTE: if using Google CoLab, make sure the runtime includes GPU before starting
!pip install git+https://github.com/smousavi05/EQTransformer
# This method of setup does not require the curation of the local environment, which is why it is useful when using a platform such as Google CoLab.
# If using Google CoLab, restart the runtime after this install.
# The platform will not recognize your new setup if it is not restarted and will throw errors.
# Clone in the repository setup- this is what contains the pre-trained model, so this is necessary
!git clone https://github.com/UW-ESS-DS/krauss-repo
# Mount Google Drive if retrieving data or saving data to the cloud
# WARNING: this will connect to all Shared Drives in your name. Proceed with caution.
from google.colab import drive
drive.mount('/content/gdrive/')
###Output
[2022-03-25 16:20:05,800] - obspy.clients.fdsn.mass_downloader - INFO: Total acquired or preexisting stations: 0
[2022-03-25 16:20:05,800] - obspy.clients.fdsn.mass_downloader - INFO: Total acquired or preexisting stations: 0
[2022-03-25 16:20:05,803] - obspy.clients.fdsn.mass_downloader - INFO: Client 'IRIS' - Requesting reliable availability.
[2022-03-25 16:20:05,803] - obspy.clients.fdsn.mass_downloader - INFO: Client 'IRIS' - Requesting reliable availability.
###Markdown
Download Data
###Code
# Make list of stations to query
from EQTransformer.utils.downloader import makeStationList
# For all stations:
makeStationList('/content/stationlist.json',client_list=["IRIS"],min_lat =47.5 , max_lat = 48.5,min_lon=-129.4,max_lon=-128.8,start_time='2018-08-03T00:00:00',end_time='2018-08-05T00:00:00',channel_list=['HH[ZNE]','EH[ZNE]', 'HH[Z21]','EH[Z21]', 'CH[ZNE]'],filter_network=['SY'])
# For just ENWF, filter the other station names:
# makeStationList('/content/stationlist_ENWF.json',client_list=["IRIS"],min_lat =47.5 , max_lat = 48.5,min_lon=-129.4,max_lon=-128.8,start_time='2018-08-03T00:00:00',end_time='2018-08-05T00:00:00',channel_list=['HH[ZNE]','EH[ZNE]', 'HH[Z21]','EH[Z21]', 'CH[ZNE]'],filter_network=['SY'],filter_station=['ENEF','ENHR','KEMF','KEMO','NCHR'])
def station_list(dfS,t1,t2,elevation=False,network=False):
"""
Function to make a station sublist from the master station list based on several choices
INPUTS:
dfS - pandas dataframe of station information for the entire AACSE catalog
t1,t2 - datetime objects; only return stations operating between these two timestamps
elevation - float; only return stations below this maximum elevation
network - string; only return stations within this network
OUTPUTS:
dfS = subset of the original pandas station dataframe that meets specifications
"""
if isinstance(dfS.iloc[0]['start_date'],str):
dfS['start_date'] = pd.to_datetime(dfS['start_date'],infer_datetime_format=True,errors='coerce')
dfS['end_date'] = pd.to_datetime(dfS['end_date'],infer_datetime_format=True,errors='coerce')
dfS = dfS[(dfS['start_date'] < t1) & (dfS['end_date'] > t2)]
if elevation:
dfS = dfS[dfS['elevation(m)']<elevation]
if network:
dfS = dfS[dfS['network']==network]
return dfS
# Make Alaska station list, which EQT requires as json
import json
import datetime
import pandas as pd
dfS = pd.read_parquet("https://github.com/zoekrauss/alaska_catalog/raw/main/data_acquisition/alaska_stations.parquet")
starttime = datetime.datetime(2019, 5, 27)
endtime = datetime.datetime(2019, 5, 28)
dfS = station_list(dfS,starttime,endtime,elevation=False,network=False)
dfS.drop_duplicates(subset=['station'],inplace=True)
dfS.set_index('station',inplace=True)
dfS['coords'] = [[dfS.iloc[i].latitude,dfS.iloc[i].longitude,dfS.iloc[i]['elevation(m)']] for i in range(len(dfS))]
dfS['channels'] = [[dfS.iloc[i]['id'][-2:]+dfS.iloc[i]['component'][0],dfS.iloc[i]['id'][-2:]+dfS.iloc[i]['component'][2],dfS.iloc[i]['id'][-2:]+dfS.iloc[i]['component'][4]] for i in range(len(dfS))]
# Grab only a subset of stations, if desired:
sub_list = ['EP15','KD01','KD02','LA21','WD53','WD55']
dfS_sub = dfS.filter(items=sub_list,axis=0)
# Convert to dictionary
stations = dfS_sub[['network','channels','coords']].to_dict(orient='index')
# Save to json
with open("stationlist.json", "w") as outfile:
json.dump(stations, outfile)
# Download the mseeds, which is the actual seismic time series data, for desired time period
from EQTransformer.utils.downloader import downloadMseeds
stime = "2019-05-27"
ftime = "2019-05-28"
downloadMseeds(client_list=["IRIS"], stations_json='stationlist.json', output_dir="sample_data/downloads_mseeds",min_lat =52, max_lat = 59,min_lon=-162,max_lon=-149,start_time=stime,end_time=ftime, chunk_size=1, n_processor=1)
# Save miniseeds to Google Drive, if desired
# Zip and save mseed folders:
!zip -r /content/gdrive/MyDrive/Colab_Notebooks/downloads_mseeds_august1_5.zip /content/downloads_mseeds_august3_2018
# Save xml:
# !mv "/content/downloads_mseeds_july2018xml" "/content/gdrive/MyDrive/Colab_Notebooks/downloads_mseeds_july2018xml"
###Output
_____no_output_____
###Markdown
Perform detections
###Code
from EQTransformer.core.mseed_predictor import mseed_predictor
mseed_predictor(input_dir='/content/sample_data/downloads_mseeds',
input_model='/content/krauss-repo/eq_project/eqtransformer_local/ModelsAndSampleData/EqT_model.h5',
stations_json='stationlist.json',
output_dir='aacse_detection',
detection_threshold=0.2,
P_threshold=0.3,
S_threshold=0.3,
number_of_plots=10,
plot_mode='time_frequency',
batch_size=20,
overlap=0.3)
# Save to google drive, if desired
# Zip and save detection folder:
!zip -r /content/gdrive/MyDrive/Colab_Notebooks/detection_results_august1-5_2018.zip /content/detection_results_august1-5_2018
# Save time tracks:
#!mv "/content/time_tracks.pkl" "/content/gdrive/MyDrive/Colab_Notebooks/time_tracks.pkl"
###Output
_____no_output_____
###Markdown
Analyze Results
###Code
# If unzipping files from the Drive
zipfilename = '/content/gdrive/MyDrive/Colab_Notebooks/detection_results_august1-5_2018.zip'
# opening the zip file in READ mode
with ZipFile(zipfilename, 'r') as zip:
# printing all the contents of the zip file
zip.printdir()
# extracting all the files
print('Extracting all the files now...')
zip.extractall()
print('Done!')
# Make a pandas dataframe of the output detections
# Concat list of all csv files
bigdir = "/content/detection_results_august1-5_2018"
bigdir = '/content/content/detection_results_august1-5_2018'
folder_list = glob.glob(bigdir + "/*") # Include slash or it will search in the wrong directory!!
file_list = []
for folder in folder_list:
file_list.append(glob.glob(folder+"/*.csv"))
# Read data into pandas dataframe
data = pd.concat([pd.read_csv(f[0]) for f in file_list])
# Change time columns to datetime format
startdate = pd.to_datetime(data['event_start_time'], format='%Y-%m-%d %H:%M:%S');
enddate = pd.to_datetime(data['event_end_time'], format='%Y-%m-%d %H:%M:%S');
p_time = pd.to_datetime(data['p_arrival_time'], format='%Y-%m-%d %H:%M:%S');
s_time = pd.to_datetime(data['s_arrival_time'], format='%Y-%m-%d %H:%M:%S');
data['start_time'] = startdate;data['end_time'] = enddate
data['ptime'] = p_time
data['stime'] = s_time
# Split into station subsets
new_kemf = data.loc[(data.station=='KEMF')].copy()
new_enwf = data.loc[(data.station=='ENWF')].copy()
new_enhr = data.loc[(data.station=='ENHR')].copy()
new_kemo = data.loc[(data.station=='KEMO')].copy()
# Read in MATLAB detections
startdate = datetime(2018,8,1)
enddate = datetime(2018,8,6)
#og_eqs = pd.read_csv('/content/gdrive/Shareddrives/ESS490_Spring2021/August2018_EndEarthquakes.csv')
og_eqs = pd.read_csv('/content/August2018_EarthquakeData.csv')
# Filter it down to just the dates you want to compare
origintime = pd.to_datetime(og_eqs['originTime']);
og_eqs['originTime'] = origintime
og_eqs = og_eqs.loc[(og_eqs.originTime>startdate) & (og_eqs.originTime<enddate)]
print(og_eqs)
# Turn time columns into datetime format
og_eqs['KEMF_P_time'] = pd.to_datetime(og_eqs['KEMF_P_time'])
og_eqs['KEMF_S_time'] = pd.to_datetime(og_eqs['KEMF_S_time'])
og_eqs['KEMO_P_time'] = pd.to_datetime(og_eqs['KEMO_P_time'])
og_eqs['KEMO_S_time'] = pd.to_datetime(og_eqs['KEMO_S_time'])
og_eqs['ENWF_P_time'] = pd.to_datetime(og_eqs['ENWF_P_time'])
og_eqs['ENWF_S_time'] = pd.to_datetime(og_eqs['ENWF_S_time'])
og_eqs['ENHR_P_time'] = pd.to_datetime(og_eqs['ENHR_P_time'])
og_eqs['ENHR_S_time'] = pd.to_datetime(og_eqs['ENHR_S_time'])
# Split into station subsets
org_kemf = og_eqs[['originTime','KEMF_P_time','KEMF_S_time','magnitude','nwp','nws']].copy()
org_enwf = og_eqs[['originTime','ENWF_P_time','ENWF_S_time','magnitude','nwp','nws']].copy()
org_enhr = og_eqs[['originTime','ENHR_P_time','ENHR_S_time','magnitude','nwp','nws']].copy()
org_kemo = og_eqs[['originTime','KEMO_P_time','KEMO_S_time','magnitude','nwp','nws']].copy()
# Rename columns to match the other dataframe
org_kemf.rename(columns={'KEMF_P_time':'ptime','KEMF_S_time':'stime'},inplace=True)
org_kemo.rename(columns={'KEMO_P_time':'ptime','KEMO_S_time':'stime'},inplace=True)
org_enwf.rename(columns={'ENWF_P_time':'ptime','ENWF_S_time':'stime'},inplace=True)
org_enhr.rename(columns={'ENHR_P_time':'ptime','ENHR_S_time':'stime'},inplace=True)
org_kemf.head()
# A way to visualize which and how many detections are lining up in time:
# Scatter plot the true time arrivals, and overlay the EQTransformer detections
# Filter to desired time band
new_enwf = new_enwf.loc[(new_enwf.ptime>startdate) & (new_enwf.ptime<enddate)]
fig,ax = plt.subplots()
ax.scatter(org_enwf['ENWF_S_time'],np.zeros(len(org_enwf)))
# Define successful EQTransformer detections as those that occur within 2 seconds of true detections
success = []
for i in org_enwf['ENWF_P_time']:
differ = new_enwf['ptime'] - i
if any(abs(differ)<timedelta(seconds=2)):
success.append(min(abs(differ)))
S_success = []
for i in org_enwf['ENWF_S_time']:
differ = new_enwf['stime'] - i
if any(abs(differ)<timedelta(seconds=2)):
S_success.append(min(abs(differ)))
for i in new_enwf['ptime'].dropna():
ax.axvline(i)
print(len(success))
def calc_performance(true_data,new_data):
'''
Reads in two vectors/pandas columns in datetime format
Inputs:
true_data = vector containing the datetimes of a phase arrival (either P or S) as detected by traditional methods
new_data = vector containing the datetimes of a phase arrival (either P or S) as detected by EQTransformer
NOTE: true_data must be longer than new_data in the way the code is written.
Matches occur when the timing of one arrival is within 2 seconds of another
Returns:
tp = number of true positives (number of matches)
fn = number of false negatives (number of traditional method detections that did not have an EQTransformer match)
fp = number of false positivies (number of EQTransformer detections that did not have a traditional detection match)
'''
success = []
for i in true_data:
differ = new_data - i
if any(abs(differ)<timedelta(seconds=2)):
success.append(min(abs(differ)))
# True positive
tp = len(success)
# False negative
fn = len(true_data) - len(success)
# False positive
fp = len(new_data) - len(success)
# Precision
prec = tp/(fp+tp)
# Recall
rec = tp / (tp + fn)
# F1 score
f1 = tp / (tp + (fn+fp)/2)
return(tp,fn,fp)
# Read in finished runs
test_folder = '/content/gdrive/Shareddrives/ESS490_Spring2021/True False Parameter Results/Success_Results'
test = pd.read_csv(test_folder+'/default_results')
test.columns
test.drop(columns='Unnamed: 0',inplace=True)
print('Default results:')
print(test)
test2 = pd.read_csv(test_folder+'/dt_03_results')
test2.columns
test2.drop(columns='Unnamed: 0',inplace=True)
print('Detection threshold 0.3:')
print(test2)
test3 = pd.read_csv(test_folder+'/bs_50_results')
test3.columns
test3.drop(columns='Unnamed: 0',inplace=True)
print('Detection threshold 0.3:')
print(test3)
success = pd.DataFrame(columns=['Station-Phase Pair','True Positives','False Negatives','False Positives'])
# enwf_p_tp,enwf_p_fn = calc_fscore(org_enwf['ENWF_P_time'],new_enwf['ptime'])
success['Station-Phase Pair'] = ['ENWF_P','ENWF_S','KEMF_P','KEMF_S','KEMO_P','KEMO_S','ENHR_P','ENHR_S']
success['True Positives'].iloc[0],success['False Negatives'].iloc[0],success['False Positives'].iloc[0] = calc_performance(org_enwf['ptime'],new_enwf['ptime'])
success['True Positives'].iloc[1],success['False Negatives'].iloc[1],success['False Positives'].iloc[1] = calc_performance(org_enwf['stime'],new_enwf['stime'])
success['True Positives'].iloc[2],success['False Negatives'].iloc[2],success['False Positives'].iloc[2] = calc_performance(org_kemf['ptime'],new_kemf['ptime'])
success['True Positives'].iloc[3],success['False Negatives'].iloc[3],success['False Positives'].iloc[3] = calc_performance(org_kemf['stime'],new_kemf['stime'])
success['True Positives'].iloc[4],success['False Negatives'].iloc[4],success['False Positives'].iloc[4] = calc_performance(org_kemo['ptime'],new_kemo['ptime'])
success['True Positives'].iloc[5],success['False Negatives'].iloc[5],success['False Positives'].iloc[5] = calc_performance(org_kemo['stime'],new_kemo['stime'])
success['True Positives'].iloc[6],success['False Negatives'].iloc[6],success['False Positives'].iloc[6] = calc_performance(org_enhr['ptime'],new_enhr['ptime'])
success['True Positives'].iloc[7],success['False Negatives'].iloc[7],success['False Positives'].iloc[7] = calc_performance(org_enhr['stime'],new_enhr['stime'])
print(success)
# Earthquake characteristic analysis
def get_indices(true_data,new_data):
success=[]
counter = 0
# Save indices of successful matches
for i in true_data['ptime']:
counter += 1
differ = new_data['ptime'] - i
if any(abs(differ)<timedelta(seconds=2)):
# success.append(np.amin(abs(differ)))
success.append(counter)
counter = 0
for i in true_data['stime']:
counter += 1
differ = new_data['stime'] - i
if any(abs(differ)<timedelta(seconds=2)):
# success.append(np.amin(abs(differ)))
success.append(counter)
return(success)
success1 = get_indices(org_enhr,new_enhr)
success2 = get_indices(org_enwf,new_enwf)
success3 = get_indices(org_kemf,new_kemf)
success4 = get_indices(org_kemo,new_kemo)
all=success1+success2+success3+success4
eq_stats = pd.DataFrame(columns=['Magnitude','nwp','nws'])
eq_stats['Magnitude'] = org_kemf['magnitude'].iloc[np.unique(all)]
eq_stats['nwp'] = org_kemf['nwp'].iloc[np.unique(all)]
eq_stats['nws'] = org_kemf['nws'].iloc[np.unique(all)]
print(eq_stats)
###Output
Magnitude nwp nws
149 1.632591 2 4
150 0.338127 4 4
156 0.739630 3 4
157 -0.114712 3 4
161 0.967936 3 4
165 NaN 1 4
172 0.389003 4 4
173 0.248404 3 4
181 0.259680 3 4
189 0.036561 2 4
203 -0.310464 2 3
221 -0.068506 3 4
225 NaN 0 5
226 0.096432 1 4
|
2_toy_models.ipynb | ###Markdown
Copyright 2019 Qiyang Hu
###Code
#@title Licensed under MIT License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://huqy.github.io/idre_learning_machine_learning/LICENSE.md
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
warnings.filterwarnings('ignore')
warnings.filterwarnings('ignore', category=DeprecationWarning)
import numpy as np;
import pandas as pd;
import seaborn as sns; sns.set(color_codes=True)
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_squared_error
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.tree import export_graphviz
from graphviz import Source
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV
from sklearn import ensemble, tree, svm, naive_bayes, neighbors, linear_model, gaussian_process, neural_network
from sklearn.metrics import accuracy_score, f1_score, auc, roc_curve, roc_auc_score, make_scorer
from sklearn.model_selection import cross_val_score
np.random.seed(0)
%matplotlib inline
def compute_score(clf, X, y, scoring='accuracy'):
xval = cross_val_score(clf, X, y, cv = 5, scoring=scoring)
return np.mean(xval)
###Output
_____no_output_____
###Markdown
Regression: Linear and Polynomial
###Code
mean, cov = [5, 5], [(0.4, 0.5), (0.5, 1)]
x, y = np.random.multivariate_normal(mean, cov, 20).T
x, y = pd.Series(x, name="x_var"), pd.Series(y, name="y_var")
ax = sns.regplot(x=x, y=y, ci=None, line_kws={'color':'c'})
ax = sns.regplot(x=x, y=y, ci=None, order=11, line_kws={'color':'c'})
x = x.values.reshape(-1,1)
y = y.values.reshape(-1,1)
clf = LinearRegression()
clf.fit(x,y)
pred = clf.predict(x)
score = clf.score(y, pred)
print("Coefficient of determination R^2 of the prediction:", score)
print("Coefficients for the linear regression problem:", clf.coef_[0])
print("Bias term for the linear regression problem:", clf.intercept_)
###Output
Coefficient of determination R^2 of the prediction: -0.046539229482777555
Coefficients for the linear regression problem: [1.31676205]
Bias term for the linear regression problem: [-1.66085188]
###Markdown
Generating Data Points
###Code
def f(x):
""" function to approximate by linear and polynomial interpolation"""
return 0.05*x*x + 0.9 * x +1
# generate points used to plot
x_plot = np.linspace(5, 95, 1000)
n_train = 20
n_test = 10
err_range = 100
np.random.seed(0)
x_whole = np.linspace(5, 95, 1000)
rng = np.random.RandomState(0)
rng.shuffle(x_whole)
# generate training points
x_train = np.sort(x_whole[:n_train])
delta = np.random.uniform(-err_range, err_range, n_train)
y_train = f(x_train) + delta
# generate testing points
x_test = np.sort(x_whole[n_train:n_train+n_test])
delta = np.random.uniform(-err_range, err_range, n_test)
y_test = f(x_test) + delta
# create matrix versions of these arrays
X_train = x_train[:, np.newaxis]
X_test = x_test[:, np.newaxis]
X_plot = x_plot[:, np.newaxis]
###Output
_____no_output_____
###Markdown
Regression fit
###Code
colors = ['red', 'yellowgreen', 'm']
lw = 2
plt.plot(x_plot, f(x_plot), color='cornflowerblue', linewidth=lw, label="ground truth")
plt.scatter(x_train, y_train, color='navy', s=30, marker='o', label="training points")
plt.scatter(x_test, y_test, color='orange', s=30, marker='X', label="testing points")
model = LinearRegression().fit(X_train,y_train)
y_plot = model.predict(X_plot)
plt.plot(x_plot, y_plot, color='cyan', linewidth=lw, label="Linear Regression")
for count, degree in enumerate([2, 3, 10]):
model = make_pipeline(PolynomialFeatures(degree), Ridge(alpha=0))
model.fit(X_train, y_train)
y_plot = model.predict(X_plot)
#if degree != 2: break
plt.plot(x_plot, y_plot, color=colors[count], linewidth=lw, label="Polynomial degree %d" % degree)
plt.legend(loc='upper left')
plt.axis([0, 100, np.min(y_train)-50, np.max(y_train)+100])
plt.show()
###Output
_____no_output_____
###Markdown
Check the loss function
###Code
col = []
loss = pd.DataFrame(columns = col)
idx = 0
withreg = False
for degree in np.arange(10):
loss.loc[idx, 'degree'] = degree
for a in np.arange( 2 if withreg else 1 ) :
model = make_pipeline(PolynomialFeatures(degree), Ridge(alpha=a))
model.fit(X_train, y_train)
y_pred = model.predict(X_train)
mse_train = mean_squared_error(y_train, y_pred)
y_pred = model.predict(X_test)
mse_test = mean_squared_error(y_test, y_pred)
loss.loc[idx, "mse train %d" % a] = mse_train
loss.loc[idx, "mse test %d" % a] = mse_test
idx+=1
plt.plot(loss['degree'], loss['mse train 0']/1000, color='cyan', linewidth=lw, label="From Training Data w/o regularization")
plt.plot(loss['degree'], loss['mse test 0']/1000, color='red', linewidth=lw, label="From Testing Data w/o regularization")
if withreg:
plt.plot(loss['degree'], loss['mse train 1']/1000, color='m', linestyle='--', linewidth=lw, label="From Training Data w regularization")
plt.plot(loss['degree'], loss['mse test 1']/1000, color='green', linestyle='--', linewidth=lw, label="From Testing Data w regularization")
plt.scatter(2, np.min(loss['mse test 0'])/1000, s=100, facecolors='none', edgecolors='blue')
plt.legend(loc='upper right')
plt.xlabel('Polynomial Regression Degree')
plt.ylabel('Mean Squred Error x1000')
plt.show()
###Output
_____no_output_____
###Markdown
Bias and Variance
###Code
def f(x):
""" function to approximate by linear and polynomial interpolation"""
return 0.05*x*x + 0.9 * x +1
np.random.seed(0)
n_grid = 8000
lw = 2
x_whole = np.linspace(5, 95, n_grid)
# generate points used to plot
x_plot = np.linspace(5, 95, n_grid)
col = []
loss = pd.DataFrame(columns = col)
idx = 0
for n in np.arange(10, 4000, 100):
n_train = n
n_test = n
err_range = 100
# generate training points
rng = np.random.RandomState(0)
rng.shuffle(x_whole)
x_train = np.sort(x_whole[:n_train])
delta = np.random.uniform(-err_range, err_range, n_train)
y_train = f(x_train) + delta
# generate testing points
x_test = np.sort(x_whole[n_train:n_train+n_test])
delta = np.random.uniform(-err_range, err_range, n_test)
y_test = f(x_test) + delta
# create matrix versions of these arrays
X_train = x_train[:, np.newaxis]
X_test = x_test[:, np.newaxis]
X_plot = x_plot[:, np.newaxis]
# change the degree to have different complexity of the model
degree = 4
loss.loc[idx, 'problem size'] = n
model = make_pipeline(PolynomialFeatures(degree), Ridge())
model.fit(X_train, y_train)
y_pred = model.predict(X_train)
mse_train = mean_squared_error(y_train, y_pred)
y_pred = model.predict(X_test)
mse_test = mean_squared_error(y_test, y_pred)
loss.loc[idx, "mse train"] = mse_train
loss.loc[idx, "mse test"] = mse_test
loss.loc[idx, "variance"] = abs(mse_train-mse_test)
loss.loc[idx, "desired perf"] = 3.3
idx+=1
plt.plot(loss['problem size'], loss['mse train']/1000, color='cyan', linewidth=lw, label="From Training Data")
plt.plot(loss['problem size'], loss['mse test']/1000, color='red', linewidth=lw, label="From Testing Data")
plt.plot(loss['problem size'], loss['desired perf'], color='m', linewidth=lw, linestyle='--', label="Desired performance")
plt.legend(loc='upper right')
plt.xlabel('Data size')
plt.ylabel('Mean Squred Error x1000')
plt.show()
###Output
_____no_output_____
###Markdown
Regularization
###Code
col = []
loss = pd.DataFrame(columns = col)
idx = 0
withreg = False
degree = 8
for a in np.power(10, range(14)) / 100000:
loss.loc[idx, 'a'] = a
model = make_pipeline(PolynomialFeatures(degree), Ridge(alpha=a))
model.fit(X_train, y_train)
y_pred = model.predict(X_train)
mse_train = mean_squared_error(y_train, y_pred)
y_pred = model.predict(X_test)
mse_test = mean_squared_error(y_test, y_pred)
loss.loc[idx, "mse train"] = mse_train
loss.loc[idx, "mse test"] = mse_test
idx+=1
plt.plot(loss['a'], loss['mse train']/1000, color='cyan', linewidth=lw, label="From Training Data")
plt.plot(loss['a'], loss['mse test']/1000, color='red', linewidth=lw, label="From Testing Data")
#plt.scatter(2, np.min(loss['mse test 0'])/1000, s=100, facecolors='none', edgecolors='blue')
plt.legend(loc='center left')
plt.xlabel(r'Regularization Penality $\theta$')
plt.ylabel('Mean Squred Error x1000')
plt.xscale('log')
plt.show()
###Output
_____no_output_____
###Markdown
Classification: Logistic Regression, Naive Bayes, Decision Tree, ...
###Code
n = 40
mean, cov = [4, 6], [(0.4, 0.5), (0.5, 1)]
np.random.seed(0)
x1, x2 = np.random.multivariate_normal(mean, cov, n).T
y1 = np.zeros(n)
y2 = np.ones(n)
x = np.concatenate((x1, x2), axis=None)
y = np.concatenate((np.zeros(n), np.ones(n)), axis=None)
x, y = pd.Series(x, name="x_var"), pd.Series(y, name="Probability")
ax = sns.regplot(x=x, y=y, ci=None, logistic=True, line_kws={'color':'c'})
g = sns.JointGrid(x=x, y=y)
g = g.plot_joint(sns.regplot, ci=None, logistic=True, line_kws={'color':'c'})
g.ax_marg_x.hist(x2, color="r", alpha=.6, bins=np.arange(2, 8, 0.2))
g.ax_marg_x.hist(x1, color="b", alpha=.6, bins=np.arange(2, 8, 0.2))
g.ax_marg_y.set_axis_off()
x = x.values.reshape(-1,1)
clf = LogisticRegression()
clf = naive_bayes.GaussianNB()
clf.fit(x,y)
pred = clf.predict(x)
acc = accuracy_score(y, pred)
f1 = f1_score(y, pred)
cv = cross_val_score(clf, x, y).mean()
print("Accuracy Score:", acc)
print("F1 score or balanced F-score:", f1)
print("Cross Validation Score:", cv)
x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
xx = np.linspace(x_min, x_max, 10000)
yy = clf.predict(xx.reshape(-1,1))
plt.scatter(x, y, color='navy', s=30, marker='o', label="training points")
#plt.scatter(xx, yy, color='red', s=30, marker='o', label="training points")
plt.plot(xx, yy, color='cyan', label="predicting mesh points")
plt.legend(loc='center right')
plt.xlabel('x_var')
plt.ylabel('y_var')
plt.show()
clf = DecisionTreeClassifier(max_depth=1)
clf.fit(x,y)
pred = clf.predict(x)
acc = accuracy_score(y, pred)
f1 = f1_score(y, pred)
cv = cross_val_score(clf, x, y).mean()
print("Accuracy Score:", acc)
print("F1 score or balanced F-score:", f1)
print("Cross Validation Score:", cv)
Source( tree.export_graphviz(clf, out_file=None, rounded=True, filled=True) )
clf = RandomForestClassifier(max_depth=1)
clf.fit(x,y)
pred = clf.predict(x)
acc = accuracy_score(y, pred)
f1 = f1_score(y, pred)
cv = cross_val_score(clf, x, y).mean()
print("Accuracy Score:", acc)
print("F1 score or balanced F-score:", f1)
print("Cross Validation Score:", cv)
# default 10 estimators in RandomForestClassifier
estimator = clf.estimators_[2]
Source( tree.export_graphviz(estimator, out_file=None, rounded=True, filled=True) )
###Output
_____no_output_____ |
project-4_breast-cancer-recognition/NN_proj4.ipynb | ###Markdown
Data WranglingHere we seperate the data out into 100 training cases, equal parts malaginint and benign, and 469 remaining evalulation cases.
###Code
data = load_breast_cancer()
data_m = []
data_b = []
for input, output in zip(data["data"],data['target']):
if output == 0:
data_m.append((input,output))
else:
data_b.append((input,output))
#variable to store number of values to train off of, selected at a 50/50 mix
num_train = 100
train_x = []
train_y = []
eval_x = []
eval_y = []
#populate the training data
for i in range(0,num_train//2):
train_x.append(data_m[i][0])
train_x.append(data_b[i][0])
train_y.append(data_m[i][1])
train_y.append(data_b[i][1])
for item in data_m[num_train//2:]:
eval_x.append(item[0])
eval_y.append(item[1])
for item in data_b[num_train//2:]:
eval_x.append(item[0])
eval_y.append(item[1])
###Output
_____no_output_____
###Markdown
Neural NetworkHere we initialize our neural network, with 30 inputs, 2 hidden layers, with 15 and 2 nodes respectivly, and 1 output.
###Code
net = buildNetwork(30,15,2,1)
LEN_PARAM = len(net.params)
###Output
_____no_output_____
###Markdown
Setup DeapHere we initialize the properties for an individual and the fitness function. Eeach individual is set to be a random float from -1 to 1
###Code
def random_0to1():
return random.uniform(-1, 1)
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)
toolbox = base.Toolbox()
toolbox.register("attr_float", random_0to1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=LEN_PARAM)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
###Output
_____no_output_____
###Markdown
Fitness FunctionHere we activate the network with the weights given by the genes for every test case in eval X and if the result is >= 0, we have a result of 1, if < 0 we have a 0
###Code
def evalNN(individual):
net._setParameters(individual)
fitness = 0
for result, actual in zip(map(net.activate,train_x),train_y):
if result >= 0 and actual == 0:
fitness += 1
elif result < 0 and actual == 1:
fitness += 1
return fitness,
toolbox.register("evaluate", evalNN)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0.0, sigma=0.2, indpb=0.2)
toolbox.register("select", tools.selTournament, tournsize=5)
###Output
_____no_output_____
###Markdown
Evaluation on all:This function is used to test an individual against the the datapoints not used to train the network. It returns the number it got wrong.
###Code
def evalNNall(individual):
net._setParameters(individual)
fitness = 0
for result, actual in zip(map(net.activate,eval_x),eval_y):
if result >= 0 and actual == 0:
fitness += 1
elif result < 0 and actual == 1:
fitness += 1
return fitness
###Output
_____no_output_____
###Markdown
Evolutionary Algorithm We run a ea(explained below) on a 1000 individuals for 20 generations. The selection method is tournament size of 5. Each gene is mutated with values from a gaussian distribution, with an independent probability of 0.2. The hall of fame stores the fittest individual, across all generations (not just the last) The documantation for easimple can be found at https://deap.readthedocs.io/en/master/api/algo.html under easimple. The algorithm is effectively a heavily modified steady state model. I didn't reproduce the the description of the algorithm fully here, since the description there is more helpful, and since DEAP uses specfic functions that I could not explain better then the documantation.
###Code
def run_ea():
pop = toolbox.population(n=1000)
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", numpy.mean)
stats.register("min", numpy.min)
stats.register("max", numpy.max)
pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=20, stats=stats, halloffame=hof, verbose=True)
return pop, logbook, hof
pop, log, hof = run_ea()
print("Best individual is: %s\nwith fitness: %s" % (hof[0], hof[0].fitness))
gen, avg, min_, max_ = log.select("gen", "avg", "min", "max")
plt.plot(gen, avg, label="average")
plt.plot(gen, min_, label="minimum")
plt.plot(gen, max_, label="maximum")
plt.xlabel("Generation")
plt.ylabel("Fitness")
plt.legend(loc="lower right")
plt.show()
#number of incorrect results on the values not used in training
print(evalNNall(hof[0]))
###Output
40
|
notebooks/Compress the String!.ipynb | ###Markdown
You are given a string,"S" . Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character '(X,c)' with in the string.
###Code
s = '1222311'
from itertools import groupby
print(*[(len(list(c)), int(k)) for k, c in groupby(s)])
for c, items in groupby(s):
print(tuple([len(list(items)),int(c)]), end=' ')
for i, n in groupby(s):
a = list(n)
print(a)
#print("(", len(a), ", ", a[0], ")", end = " ", sep = "")
for k, g in groupby(s):
print("({}, {})".format(len(list(g)), k), end=" ")
###Output
(1, 1) (3, 2) (1, 3) (2, 1) |
Lessons/0 - Think Python Recap - Summary of Chapter 1-6.ipynb | ###Markdown
Recap of previous topicsWe already know "everything" there is to know to create anything that can be done with a computer. We only need to aquire the knowledge to put the pieces together and reduce the complexity.Code examples taken from https://greenteapress.com/wp/think-python-2e/ The first program
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
*** Arithmetic operators
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Values and types
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Formal and natural languagesNatural languages are the languages people speak, such as English, Spanish, and French.They were not designed by people (although people try to impose some order on them);they evolved naturally. Formal languages are languages that are designed by people for specific applications. Forexample, the notation that mathematicians use is a formal language that is particularlygood at denoting relationships among numbers and symbols. Chemists use a formal languageto represent the chemical structure of molecules. And most importantly: Programming languages are formal languages that have been designed toexpress computations. *** DebuggingProgrammers make mistakes. For whimsical reasons, programming errors are called bugsand the process of tracking them down is called debugging.Programming, and especially debugging, sometimes brings out strong emotions. If youare struggling with a difficult bug, you might feel angry, despondent, or embarrassed.Your job is to be a good manager: find ways to take advantage of the strengths and mitigatethe weaknesses. And find ways to use your emotions to engage with the problem, withoutletting your reactions interfere with your ability to work effectively.Learning to debug can be frustrating, but it is a valuable skill that is useful for many activitiesbeyond programming. *** Exercises - Chapter 1 Exercise 1.1It is a good idea to read this book in front of a computer so you can try out theexamples as you go.Whenever you are experimenting with a new feature, you should try to make mistakes. For example,in the "Hello, world!" program, what happens if you leave out one of the quotation marks? What ifyou leave out both? What if you spell print wrong?This kind of experiment helps you remember what you read; it also helps when you are programming,because you get to know what the error messages mean. It is better to make mistakes now and onpurpose than later and accidentally.
###Code
# Time to experiment, write some code, try to raise errors and understand what the system is telling you
###Output
_____no_output_____
###Markdown
Exercise 1.2Start the Python interpreter and use it as a calculator.1. How many seconds are there in 42 minutes 42 seconds?2. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.3. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour?
###Code
# Start calculating here
###Output
_____no_output_____
###Markdown
*** Assignment statements
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Order of operationsWhen an expression contains more than one operator, the order of evaluation dependson the order of operations. For mathematical operators, Python follows mathematicalconvention. The acronym PEMDAS is a useful way to remember the rules: Parentheseshave the highest precedence and can be used to force an expression toevaluate in the order you want. Since expressions in parentheses are evaluated first `2 * (3-1)` is $4$ and `(1+1) ** (5-2)` is $8$.You can also use parentheses to make an expression easier to read, as in `(minute * 100)}{60}` even if it does not change the result. Exponentiationhas the next highest precedence, so `1 + 2**3` is $9$, not $27$, and `2 * 3**2` is $18$, not $36$. Multiplication and Divisionhave higher precedence than Addition and Subtraction.So `2 * 3 - 1` is $5$, not $4$, and `6 + 4 / 2` is $8$, not $5$. Operators with the same precedence are evaluated from left to right (except exponentiation).So in the expression `degrees / 2 * pi`, the division happens first and theresult is multiplied by `pi`. To divide by $2\pi$, you can use parentheses or write `degrees / 2 / pi`. *** CommentsAs programs get bigger and more complicated, they get more difficult to read. Formallanguages are dense, and it is often difficult to look at a piece of code and figure out whatit is doing, or why.For this reason, it is a good idea to add notes to your programs to explain in natural languagewhat the program is doing. These notes are called comments, and they start withthe `` symbol:` compute the percentage of the hour that has elapsedpercentage = (minute * 100) / 60`In this case, the comment appears on a line by itself. You can also put comments at the endof a line:`percentage = (minute * 100) / 60 percentage of an hour`Everything from the `` to the end of the line is ignored—it has no effect on the execution ofthe program. Comments are most useful when they document non-obvious features of the codeIt is reasonable to assume that the reader can figure out what the code does; it is more useful toexplain why.This comment is redundant with the code and useless:`v = 5 assign 5 to v`This comment contains useful information that is not in the code:`v = 5 velocity in meters/second.` Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff. *** FunctionsA function is a block of organized, reusable code that is used to perform a single, related action. Uncle Bob's Rules for Functions:- The first rule of functions is that they should be small.- The second rule of functions is that they should be smaller than that (up to ~20 lines of code)- FUNCTIONS SHOULD DO ONE THING (Single-responsibility principle) Function calls
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
Math functions
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** CompositionSo far, we have looked at the elements of a program—variables, expressions, andstatements — in isolation, without talking about how to combine them.One of the most useful features of programming languages is their ability to take smallbuilding blocks and compose them. For example, the argument of a function can be anykind of expression, including arithmetic operators:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
And even function calls:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
Almost anywhere you can put a value, you can put an arbitrary expression, with one exception:the left side of an assignment statement has to be a variable name. Any otherexpression on the left side is a syntax error (we will see exceptions to this rule later).
###Code
hours = 5# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Adding new functionsSo far, we have only been using the functions that come with Python, but it is also possibleto add new functions. A function definition specifies the name of a new function and thesequence of statements that run when the function is called.
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
The first line of the function definition is called the header; the rest is called the body. Theheader has to end with a colon and the body has to be indented. By convention, indentationis always four spaces. The body can contain any number of statements.
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
Definition for a function that takes an argument:
###Code
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Fruitful functions and void functionsSome of the functions we have used, such as the math functions, return results; for lack ofa better name, I call them fruitful functions. Other functions, like `repeat_lyrics`, performan action but don’t return a value. They are called void functions.Void functions might display something on the screen or have some other effect, but theydo not have a return value. If you assign the result to a variable, you get a special valuecalled `None`.
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Interface designThe interface of a function is a summary of how it is used: what are the parameters? Whatdoes the function do? And what is the return value? An interface is "clean" if it allows thecaller to do what they want without dealing with unnecessary details. Repetition Instead of doing this
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
Use a `for` loop
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
*** Encapsulation Instead of reapting lines:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
Declare a function:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
This is known as the DRY-Principle (Don't repeat yourself) *** Generalization Instead of restricting yourself with fixed parameters
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
Try to find a generic solution
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
*** RefactoringThe process of rearranging a program to improve interfaces and facilitate code re-use—iscalled refactoring.Boy-Scout-Rule"Always leave the code you are editing a little bit cleaner than you found it" - Robert C. MartinFurther information on Refactoring:https://blog.jetbrains.com/idea/2011/09/refactoring-in-intellij-idea-live-by-robert-c-martin-uncle-bob/ *** docstringA docstring is a string at the beginning of a function that explains the interface ("doc" isshort for "documentation"). Here is an example:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
Note: You can use the Hotkey combination `Shift + Tab` to view the docstring of imported methods directly in Jupyter
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
*** Boolean expressionsA boolean expression is an expression that is either true or false.
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
The `==` operator is one of the relational operators; the others are:
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
Logical operatorsThere are three logical operators: `and`, `or`, and `not`. Example 1
###Code
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Example 2
###Code
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Example 3
###Code
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Conditional execution
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Alternative execution
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
*** Chained conditionals
###Code
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Return values
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
Incremental development Create a function that can calculate the distance between two points, as in: $$d = \sqrt{\left(x_2 - x_1\right)^2 + \left(y_2 - y_1\right)^2}$$
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Refactoring - Revisited
###Code
# Space for writing
# Space for writing
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
*** Composition - RevisistedAs an example, we will write a function that takes two points, the center of the circle and a point on theperimeter, and computes the area of the circle.Assume that the center point is stored in the variables `xc` and `yc`, and the perimeter point isin `xp` and `yp`. The first step is to find the radius of the circle, which is the distance betweenthe two points. We just wrote a function, `distance`, that does that:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
The next step is to find the area of a circle with that radius; we also wrote this before:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
Encapsulating these steps in a function, we get:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
The temporary variables `radius` and `result` are useful for development and debugging,but once the program is working, we can make it more concise by composing the functioncalls:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
*** Boolean functionsFunctions can return booleans, which is often convenient for hiding complicated tests insidefunctions. For example:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
Note: We should avoid using more than 1 return in a function, as this increases complexity and is error-prone. We are doing it here for educational reasons. A more concise version of this function is provided below. It is recommend to write boolean functions in this other way. It is common to give boolean functions names that sound like yes/no questions;`is_divisible` returns either `True` or `False` to indicate whether `x` is divisible by `y`.
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____
###Markdown
The result of the `==` operator is a boolean, so we can write the function more concisely byreturning it directly:
###Code
# Space for writing
###Output
_____no_output_____
###Markdown
*** Well done - You now know everything! *** We have only covered a small subset of Python, but you might be interested to know thatthis subset is a complete programming language, which means that anything that can becomputed can be expressed in this language. Any program ever written could be rewrittenusing only the language features you have learned so far (actually, you would need a fewcommands to control devices like the mouse, disks, etc., but that is all). Proving that claim is a nontrivial exercise first accomplished by Alan Turing, one of thefirst computer scientists (some would argue that he was a mathematician, but a lot of earlycomputer scientists started as mathematicians). Accordingly, it is known as the TuringThesis. *** Recursion It is legal for one function to call another; it is also legal for a function to call itself. It maynot be obvious why that is a good thing, but it turns out to be one of the most magicalthings a program can do.
###Code
# Space for writing
# Space for writing
###Output
_____no_output_____ |
Code and Data Availability - 22 Nov 2021.ipynb | ###Markdown
Code Availability
###Code
print(df['Code availability statement (Yes/No)'].value_counts())
## No - 275
## Yes - 205
## Code availability irrespective of type of code
print(df['Code availability (Yes/No (reason))'].value_counts())
## Yes - 222
## No - 258
## Analytical Code availability out of 480
print(df['Analytical code availability (Yes/No)'].value_counts())
## Yes - 43
## No - 437
labels = 'Code available', 'Code unavailable'
sizes = [43, 437]
explode = (0.05, 0)
colors = ['gold', 'tomato']
textprops = {"fontsize":14}
# Plot
#plt.rcParams['font.size']=14
fig1, ax1 = plt.subplots(figsize = (5,5))
#plt.title("Code availability", fontsize=14)
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.2f%%', colors=colors, startangle=360, textprops = textprops)
ax1.axis('equal')
sns.despine()
plt.savefig(r'C:\Users\dhrit\code1.jpg', bbox_inches='tight', dpi=600)
plt.show()
print(df['What kind of code do they share?'].value_counts())
print(df['Where do they share code (supplementary/ GitHub/ other)'].value_counts())
## Analytical Code
print(df['If analytical code availability = yes, where do they share code (supplementary/ GitHub/ other)'].value_counts())
fig3, ax = plt.subplots(edgecolor ='none', figsize=(6,4))
#colors= ['lightsalmon', 'lightgreen', 'lightblue', 'yellow', 'pink']
colors=["gold"]
textprops = {"fontsize":14}
#codeavailability = ['GitHub', 'Supplementary Section', 'Supplementary and GitHub', 'Zenodo', 'WebPage']
#Supp&GitHub + GitHub = 1 + 33 = 34
codeavailability = ['GitHub', 'WebPage', 'Supplementary\n Materials', 'Zenodo']
count = [34,2,2,5]
Percentage = [79.06, 11.62, 4.65,4.65]
ax.barh(codeavailability, Percentage, color=colors)
#ax.axis("off")
##to get horizontal barplot with percentage
for p in ax.patches:
width = p.get_width() # get bar length
ax.text(width + 1, # set the text at 1 unit right of the bar
p.get_y() + p.get_height() / 2, # get Y coordinate + X coordinate / 2
'{:1.1f}'.format(width)+'%', # set variable to display, 2 decimals
ha = 'left', # horizontal alignment
va = 'center', fontsize=13) # vertical alignment
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.xlabel("Percentage", fontsize=14)
plt.ylabel("Code repository", fontsize=14)
sns.despine()
plt.savefig(r'C:\Users\dhrit\code1.jpg', bbox_inches='tight', dpi=600)
plt.show()
###Output
_____no_output_____
###Markdown
Number of citations and code availability
###Code
#x=df['Number of citations']
#x.dropna()
df['Number of citations'] = df['Number of citations'].apply(lambda x:0 if type(x)!=int else x)
available = df.loc[df["Analytical code availability (Yes/No)"]=="Yes","Number of citations"]
#no =(df.loc[df["Code availability (Yes/No)"]=="No","Number of citations"]).dropna()
no =df.loc[df["Analytical code availability (Yes/No)"]=="No","Number of citations"]
mwu_results = stats.mannwhitneyu(available, no, alternative="greater")
mwu2_results = stats.mannwhitneyu(available, no, alternative="less")
mwu3_results = stats.mannwhitneyu(available, no, alternative="two-sided")
print(mwu_results)
print(mwu2_results)
print(mwu3_results)
df['Number of citations'] = df['Number of citations'].apply(lambda x:0 if type(x)!=int else x)
set([i for i in no.values if type(i)==str])
plt.figure(figsize=(5,5))
sns.set_style('white')
sns.set_context('talk')
sns.stripplot(data=df, x="Analytical code availability (Yes/No)", y="Number of citations",
order=["Yes", "No"])
sns.barplot(x="Analytical code availability (Yes/No)", y="Number of citations", data=df,
estimator=np.mean, capsize=.2, facecolor="white", edgecolor="black",
order=["Yes", "No"])
plt.xlabel("Code Availability", fontsize=14)
plt.yscale('log')
plt.ylim(ymax=1400)
plt.ylabel("Number of Citations", fontsize=14)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
#pvalue = mpatches.Patch(color ="white", label='p=0.08')
#plt.legend(handles=[pvalue], fontsize=12)
#x=df['Number of citations']
#x.dropna()
df['Number of citations'] = df['Number of citations'].apply(lambda x:0 if type(x)!=int else x)
available = df.loc[df["Data availability (yes/no)"]=="yes","Number of citations"]
#no =(df.loc[df["Code availability (Yes/No)"]=="No","Number of citations"]).dropna()
no =df.loc[df["Data availability (yes/no)"]=="no","Number of citations"]
mwu_results = stats.mannwhitneyu(available, no, alternative="greater")
mwu2_results = stats.mannwhitneyu(available, no, alternative="less")
mwu3_results = stats.mannwhitneyu(available, no, alternative="two-sided")
print(mwu_results)
print(mwu2_results)
print(mwu3_results)
plt.figure(figsize=(5,5))
sns.set_style('white')
sns.set_context('talk')
sns.stripplot(data=df, x="Data availability (yes/no)", y="Number of citations",
order=["yes", "no"])
sns.barplot(x="Data availability (yes/no)", y="Number of citations", data=df,
estimator=np.mean, capsize=.2, facecolor="white", edgecolor="black",
order=["yes", "no"])
plt.xlabel("Data Availability", fontsize=14)
plt.yscale('log')
plt.ylim(ymax=1300)
plt.ylabel("Number of Citations", fontsize=14)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
#pvalue = mpatches.Patch(color ="white", label='p=0.08')
#plt.legend(handles=[pvalue], fontsize=12)
## Data availability trend
data = {'Year':['2016', '2017', '2018', '2019', '2020', '2021'],
'PercentageIncrease':[6.71, 16.41, 23.88, 26.11, 30.97, 36.19]}
df4 = pd.DataFrame(data, columns=['Year','PercentageIncrease'])
print(df4)
fig, ax= plt.subplots(figsize = (7,5))
#colors = ['#009FFA']
colors=['cornflowerblue']
sns.set_style('white')
sns.set_context('talk')
overall = sns.barplot(data = df4, x = 'Year', y = 'PercentageIncrease', ci=None, palette=colors)
total = 100
for i in ax.patches:
# get_x pulls left or right; get_height pushes up or down
ax.text(i.get_x()+0.25, i.get_height()+.6, \
str(round((i.get_height()/total)*100, 1))+'%', fontsize=13,
color='black')
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.xlabel("")
plt.ylabel("Percentage of papers sharing data", fontsize=14)
#plt.title("Code availability across 2016-2020", fontsize=14)
#plt.tight_layout()
sns.despine()
#plt.savefig(r'C:\Users\dhrit\code3.jpg', bbox_inches='tight', dpi=600)
plt.show()
## Code availability trend
data = {'Year':['2016', '2017', '2018', '2019', '2020', '2021'],
'PercentageIncrease':[0.83, 2.08, 3.12, 3.54, 5.41, 8.95]}
df4 = pd.DataFrame(data, columns=['Year','PercentageIncrease'])
print(df4)
fig, ax= plt.subplots(figsize = (7,5))
#colors = ['#009FFA']
colors=['gold']
sns.set_style('white')
sns.set_context('talk')
overall = sns.barplot(data = df4, x = 'Year', y = 'PercentageIncrease', ci=None, palette=colors)
total = 100
for i in ax.patches:
# get_x pulls left or right; get_height pushes up or down
ax.text(i.get_x()+0.25, i.get_height()+.6, \
str(round((i.get_height()/total)*100, 1))+'%', fontsize=13,
color='black')
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.xlabel("")
plt.ylabel("Percentage of papers sharing code", fontsize=14)
#plt.title("Code availability across 2016-2020", fontsize=14)
#plt.tight_layout()
sns.despine()
#plt.savefig(r'C:\Users\dhrit\code3.jpg', bbox_inches='tight', dpi=600)
plt.show()
###Output
Year PercentageIncrease
0 2016 0.83
1 2017 2.08
2 2018 3.12
3 2019 3.54
4 2020 5.41
5 2021 8.95
###Markdown
Journal policies and code and data availability
###Code
data2 = {'Journal':['Bioinformatics', 'BMC_Bioinformatics', 'Genome_Biol','Genome_Med','Nat_Biotechnol', 'Nat_Genet',
'Nat_Methods','Nucleic_Acids_Res'],
'Total':[60,60,60,60,60,60,60,60],
'Share Code':[7, 1, 5, 4, 5, 7 ,13, 1],
'Share Data':[3,2,17,12,17,18,15,13]}
df5 = pd.DataFrame(data2, columns=['Journal','Total', 'Share Code', 'Share Data'])
print(df5)
data9 = {'Journal':['Journal 1', 'Journal 2', 'Journal 3', 'Journal 4', 'Journal 5', 'Journal 6',
'Journal 7', 'Journal 8'],
'Journal Name': ['Bioinformatics', 'BMC_Bioinformatics', 'Genome_Biol', 'Genome_Med',
'Nat_Biotechnol', 'Nat_Genet', 'Nat_Methods','Nucleic_Acids_Res'],
'Total':[60,60,60,60,60,60,60,60],
'Share Code':[7, 1, 5, 4, 5, 7 ,13, 1],
'Share Data':[3,2,17,12,17,18,15,13],
'Code Sharing Policy':['Mandatory', 'Encouraged', 'Mandatory', 'Encouraged', 'Mandatory','Mandatory','Mandatory','Encouraged'],
'Data Sharing Policy':['Mandatory', 'Encouraged', 'Mandatory', 'Encouraged', 'Mandatory','Mandatory','Mandatory','Mandatory'],
'Code Sharing Percentage': [11.66, 1.66,8.33,6.66,8.33,11.66,21.66,1.66],
'Data Sharing Percentage': [5,3.33,28.33,20,28.33,30,25,21.66]}
df9 = pd.DataFrame(data9, columns=['Journal','Journal Name','Total', 'Share Code', 'Share Data',
'Code Sharing Policy', 'Data Sharing Policy', 'Code Sharing Percentage', 'Data Sharing Percentage'])
df9
fig, ax= plt.subplots(figsize = (7,5))
#darkcyan=Mandatory
#paleturquoise=Encouraged
colors = ['darkcyan', 'paleturquoise', 'darkcyan','paleturquoise','darkcyan', 'darkcyan','darkcyan','darkcyan']
sns.set_style('white')
sns.set_context('talk')
overall = sns.barplot(data = df9, x = 'Data Sharing Percentage', y = 'Journal', ci=None, palette=colors)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.ylabel('')
plt.xlabel('Percentage',fontsize=14)
##to get horizontal barplot with percentage
for p in ax.patches:
width = p.get_width() # get bar length
ax.text(width + 1, # set the text at 1 unit right of the bar
p.get_y() + p.get_height() / 2, # get Y coordinate + X coordinate / 2
'{:1.1f}'.format(width)+'%', # set variable to display, 2 decimals
ha = 'left', # horizontal alignment
va = 'center', fontsize=13) # vertical alignment
Encouraged = mpatches.Patch(color='paleturquoise', label='Encouraged')
Mandatory= mpatches.Patch(color='darkcyan', label='Mandatory')
plt.legend(handles=[Encouraged,Mandatory], fontsize=12)
plt.title('Data sharing policies', fontsize=14)
sns.despine()
fig, ax= plt.subplots(figsize = (7,5))
#darkcyan=Mandatory
#c=Encouraged
#paleturquoise=No Policy
colors = ['darkcyan', 'paleturquoise', 'darkcyan','paleturquoise','darkcyan', 'darkcyan','darkcyan','paleturquoise']
sns.set_style('white')
sns.set_context('talk')
overall = sns.barplot(data = df9, x = 'Code Sharing Percentage', y = 'Journal', ci=None, palette=colors)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.ylabel('')
plt.xlabel('Percentage',fontsize=14)
##to get horizontal barplot with percentage
for p in ax.patches:
width = p.get_width() # get bar length
ax.text(width + 1, # set the text at 1 unit right of the bar
p.get_y() + p.get_height() / 2, # get Y coordinate + X coordinate / 2
'{:1.1f}'.format(width)+'%', # set variable to display, 2 decimals
ha = 'left', # horizontal alignment
va = 'center', fontsize=13) # vertical alignment
Encouraged = mpatches.Patch(color='paleturquoise', label='Encouraged')
Mandatory= mpatches.Patch(color='darkcyan', label='Mandatory')
plt.legend(handles=[Encouraged,Mandatory], fontsize=12)
plt.title('Code sharing policies', fontsize=14)
sns.despine()
###Output
_____no_output_____
###Markdown
Code and data availability statements Data and statement available - 88 (88/268*100 = 32.83%);Statement available no data- 81 (81/268*100 = 30.22%);No statement no data - 90 (90/268*100 = 33.58%);No statement but data avail- 9 (3.35%); Code and statement available - 35 (35/480*100 = 7.29%);Statement available no code - 170 (170/480*100 = 35.41%);No statement no code - 267 (55.62%);No statement but code avail - 8 (1.66%);
###Code
print(df['Data availability statement (yes/no)'].value_counts())
print(df['Code availability statement (Yes/No)'].value_counts())
## Statement vs sharing
data = {'Availability':['Data Availability Statement', 'Data Availability'],
'Percentage':[63.05, 36.2]}
df4 = pd.DataFrame(data, columns=['Availability','Percentage'])
print(df4)
fig, ax= plt.subplots(figsize = (4,2))
#cornflowerblue - data
#gold - code
colors = ['cornflowerblue', 'cornflowerblue']
sns.set_style('white')
sns.set_context('talk')
overall = sns.barplot(data = df4, x = 'Percentage', y = 'Availability', ci=None, palette=colors)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.ylabel('')
plt.xlabel('Percentage',fontsize=14)
##to get horizontal barplot with percentage
for p in ax.patches:
width = p.get_width() # get bar length
ax.text(width + 1, # set the text at 1 unit right of the bar
p.get_y() + p.get_height() / 2, # get Y coordinate + X coordinate / 2
'{:1.1f}'.format(width)+'%', # set variable to display, 2 decimals
ha = 'left', # horizontal alignment
va = 'center', fontsize=14) # vertical alignment
sns.despine()
## Statement vs sharing
data = {'Availability':['Code Availability Statement', 'Code Availability'],
'Percentage':[42.7, 9.0]}
df4 = pd.DataFrame(data, columns=['Availability','Percentage'])
print(df4)
fig, ax= plt.subplots(figsize = (4,2))
#cornflowerblue - data
#gold - code
colors = ['gold', 'gold']
sns.set_style('white')
sns.set_context('talk')
overall = sns.barplot(data = df4, x = 'Percentage', y = 'Availability', ci=None, palette=colors)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.ylabel('')
plt.xlabel('Percentage',fontsize=14)
plt.xlim(xmax=60)
##to get horizontal barplot with percentage
for p in ax.patches:
width = p.get_width() # get bar length
ax.text(width + 1, # set the text at 1 unit right of the bar
p.get_y() + p.get_height() / 2, # get Y coordinate + X coordinate / 2
'{:1.1f}'.format(width)+'%', # set variable to display, 2 decimals
ha = 'left', # horizontal alignment
va = 'center', fontsize=14) # vertical alignment
sns.despine()
###Output
Availability Percentage
0 Code Availability Statement 42.7
1 Code Availability 9.0
|
curve_fitting_Bradford_assay_values.ipynb | ###Markdown
This notebook uses curve_fit and initial estimated values to calculate the Y0, plateau and rate constant values to find a model to explain data generated from a protein standard curve using the Bradford assay. Using SciPy's curve_fit makes GraphPad plotting unnecessary.
###Code
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
from scipy import stats
###Output
_____no_output_____
###Markdown
Import raw data:
###Code
xdata = [2000, 1500, 1000, 750, 500, 250, 125, 25]
ydata = [0.99815, 0.8708,0.73975,0.6597,0.4659,0.25495,0.15,0.0292]
#ydata = [1.07685, 0.9741, 0.8432, 0.74875, 0.4937, 0.2928, 0.1696, 0.02865]
###Output
_____no_output_____
###Markdown
The initial guesses are important. Without them, curve_fit can't coalesce around explanatory values. I wonder how to generate values without human input. Y0 can be zero. The plateau could be Max + a few units. K, the rate, is difficult to estimate. When too high, incomputable values are generated (0's). Initial guesses could be more accurate by taking into account constraints e.g. p != Y0 and k !=0.
###Code
# an array for initial guesses
# g = [y0, P, k]
# when k < 0.002 then no errors
# when k > 0.002 then log(0) = errors
g = [0, 1.176, 0.001]
def eqn(y, y0, P, k):
'=(LN(($D$76-$D$75)/($D$76-G76))+0)/$D$77'
return (np.log((P-y0)/(P-y)))/k
conc_pred = np.empty(len(ydata))
for i in range(len(ydata)):
conc_pred[i]=eqn(ydata[i], g[0], g[1], g[2])
plt.plot(xdata, ydata, 'bo', label='data')
plt.plot(conc_pred, ydata, 'r.', label='predicted')
from sklearn.metrics import r2_score
print ("R2 =", r2_score(conc_pred, xdata))
###Output
R2 = 0.986118497937112
###Markdown
When predicted line (red) is below observed (blue) line, then no error in curve_fit. When above observed line, then errors about "...invalid value encountered in log." i.d. log(0).
###Code
c,cov = curve_fit(eqn, ydata, xdata, g)
c
conc = np.empty(len(ydata))
for i in range(len(ydata)):
conc[i]=eqn(ydata[i], c[0], c[1], c[2])
plt.plot(xdata, ydata, 'bo', label='data')
plt.plot(conc, ydata, 'r.', label='predicted')
plt.xlabel('conc (mg/ml)')
plt.ylabel('abs')
plt.legend()
r_squared = r2_score(conc, xdata)
plt.text(1500, 0.5, r_squared) #'R-squared = %' % r_squared)
# calculate unknowns
unk_data = [0.84985,0.8079,0.5547,0.1273]
# make new array as long as unknowns
unk_calcs = np.empty(len(unk_data))
for each in range(len(unk_data)):
#print (type(each))
unk_calcs[each] =eqn(unk_data[each], c[0], c[1], c[2])
for value in unk_calcs:
print (value.round(2))
###Output
1331.31
1199.33
642.42
100.46
|
tests/tf/nearest_neighbor.ipynb | ###Markdown
Nearest Neighbor ExampleA nearest neighbor learning algorithm example using TensorFlow library.This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)- Author: Aymeric Damien- Project: https://github.com/aymericdamien/TensorFlow-Examples/
###Code
import numpy as np
import tensorflow as tf
# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# In this example, we limit mnist data
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing
# tf Graph Input
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder("float", [784])
# Nearest Neighbor calculation using L1 Distance
# Calculate L1 Distance
distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)
accuracy = 0.
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
# Start training
with tf.Session() as sess:
sess.run(init)
# loop over test data
for i in range(len(Xte)):
# Get nearest neighbor
nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
# Get nearest neighbor class label and compare it to its true label
print ("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
"True Class:", np.argmax(Yte[i]))
# Calculate accuracy
if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
accuracy += 1./len(Xte)
print ("Done!")
print ("Accuracy:", accuracy)
test complete; Gopal
###Output
_____no_output_____ |
_notebooks/Kerry_Matrix_2.0.ipynb | ###Markdown
KERRY MATRIX- author: Richard Castro - toc: true - badges: true- comments: true- categories: [Matrix]- image: images/kerry.png
###Code
#collapse
#IMPORTING LIBRARIES AND DATA FILES
import pandas as pd
mat=pd.read_csv('../us_m.csv')
kerry=pd.read_csv('../kerry.csv')
rt = pd.read_csv('https://d14wlfuexuxgcm.cloudfront.net/covid/rt.csv')
da = pd.read_csv('https://covidtracking.com/api/v1/states/daily.csv')
#collapse
#FORMATING DATA FROM LAST WEEKS MATRIX TO MOVE WEEKLY DATA OVER
mat.columns = map(str.lower, mat.columns)
col=['state','social index current','rt current','test increase current','tpr current',
'weekly deaths current','total deaths current','total tests current']
newCol=mat[col]
newerCol=newCol.rename(columns={'social index current':'social index past' ,'rt current':'rt past' ,'test increase current':'test increase past',
'tpr current':'tpr past', 'weekly deaths current':'weekly deaths past', 'total deaths current':'total deaths past',
'total tests current':'total tests past'})
kerry.columns=map(str.lower, kerry.columns)
#collapse
#CLEANING THE RTLIVE DATA
today='2020-08-03'
rtCleaned = rt[rt['date']==today]
rtColumns = ['date', 'region', 'mean']
rtCleaned = rtCleaned[rtColumns]
rtCleaned = rtCleaned.rename(columns = {'region':'state'})
rtCleaned = rtCleaned.sort_values('state', ascending=True)
#collapse
#CLEANING THE DAILY COVID DATA
dateRange='20200803'
dailyColumns = ['date', 'state', 'death', 'positiveIncrease', 'totalTestResultsIncrease', 'deathIncrease']
dailyData = da[dailyColumns]
dailyData = dailyData.sort_values('state', ascending=True)
dailyCleaned = dailyData[dailyData['date'].astype(str)==dateRange]
#collapse
#MERGING THE DATASETS TOGETHER
mergef=pd.merge(kerry, rtCleaned, on='state')
merget=pd.merge(mergef, dailyCleaned, on='state')
merger=pd.merge(merget, newerCol, on='state')
#SHOW THE LOCATIONS FOR CLIENT
kerry
#SHOW CLIP OF THE RT DATA
rtCleaned.head(3)
#SHOW CLIP OF THE DAILY DATA
dailyCleaned.head(3)
#SHOW CLIP OF THE PAST DATA
newerCol.head(3)
#SHOW THE MERGED DATA
merger
###Output
_____no_output_____ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.