markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Filter for results that we want We want to remove words that aren't associated with a type (null WordType)
wordlist_filtered = wordlist[wordlist["WordType"].notnull()]
build_wordlist.ipynb
sdaros/placeword
unlicense
We want to remove words that contain non word characters (whitespace, hypens, etc.)
# we choose [a-z] here and not [A-Za-z] because we do _not_ # want to match words starting with uppercase characters. # ^to matches verbs in the infinitive from `dictcc` word_chars = r'^[a-z]+$|^to\s' is_word_chars = wordlist_filtered["Word"].str.contains(word_chars, na=False) wordlist_filtered = wordlist_filtered[is_w...
build_wordlist.ipynb
sdaros/placeword
unlicense
We want results that are less than 'x' letters long (x+3 for verbs since they are in their infinitive form in the dictcc wordlist)
lt_x_letters = (wordlist_filtered["Word"].str.len() < 9) |\ ((wordlist_filtered["Word"].str.contains('^to\s\w+\s')) &\ (wordlist_filtered["Word"].str.len() < 11)\ ) wordlist_filtered = wordlist_filtered[lt_x_letters] wordlist_filtered.describe()
build_wordlist.ipynb
sdaros/placeword
unlicense
We want to remove all duplicates
wordlist_filtered = wordlist_filtered.drop_duplicates("Word") wordlist_filtered.describe() wordlist_filtered["WordType"].value_counts()
build_wordlist.ipynb
sdaros/placeword
unlicense
Load our wordlists into nltk
# The TaggedCorpusReader likes to use the forward slash character '/' # as seperator between the word and part-of-speech tag (WordType). wordlist_filtered.to_csv("dictcc_moby.csv",index=False,sep="/",header=None) from nltk.corpus import TaggedCorpusReader from nltk.tokenize import WhitespaceTokenizer nltk_wordlist = T...
build_wordlist.ipynb
sdaros/placeword
unlicense
NLTK Use NLTK to help us merge our wordlists
# Our custom wordlist import nltk custom_cfd = nltk.ConditionalFreqDist((tag, word) for (word, tag) in nltk_wordlist.tagged_words() if len(word) < 9 and word.isalpha) # Brown Corpus import nltk brown_cfd = nltk.ConditionalFreqDist((tag, word) for (word, tag) in nltk.corpus.brown.tagged_words() if word.isalpha() and le...
build_wordlist.ipynb
sdaros/placeword
unlicense
Make Some Placewords Magic Happen
def populate_degrees(nouns): degrees = {} nouns_copy = nouns.copy() for latitude in range(60): for longtitude in range(190): degrees[(latitude,longtitude)] = nouns_copy.pop() return degrees def populate_minutes(verbs): minutes = {} verbs_copy = verbs.copy() for latitude ...
build_wordlist.ipynb
sdaros/placeword
unlicense
Below we will examine the different aspects/objects that define a plot in Plotly. These are: Data Layout Figure We will first follow with a few examples to showcase Plotly.
py.offline.iplot({ "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])], "layout": Layout(title="hello world") }) # do a table df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") table = ff.create_table(df) py.offline.iplot(table, filename='jupyter/table1')
Python/Plotly/PlotlyTutorial.ipynb
jaabberwocky/jaabberwocky.github.io
mit
Under every graph is a JSON object, which is a dictionary like data structure. Simply changing values of some keywords and we get different plots.
# follows trace - data - layout - figure semantic trace1 = Scatter( x = [1,2,3], y = [4,5,6], marker = {'color':'red', 'symbol':104, 'size':"10"}, mode = "markers+lines", text = ['one','two','three'], name = '1st Trace' ) data = Data([trace1]) layout = Layout( title="First Plot", xaxi...
Python/Plotly/PlotlyTutorial.ipynb
jaabberwocky/jaabberwocky.github.io
mit
Data We see that data is actually a list object in Python. Data will actually contain all the traces that you wish to plot. Now the question may be, what is a trace? A trace is just the name we give a collection of data and the specifications of which we want that data plotted. Notice that a trace will also be an objec...
# generate data x = np.linspace(0,np.pi*8,100) y = np.sin(x) z = np.cos(x) layout = Layout( title="My First Plotly Graph", xaxis = dict( title="x"), yaxis = dict(title="sin(x)") ) trace1 = Scatter( x = x, y = y, mode = "lines", marker = dict( size=8, color="navy" ...
Python/Plotly/PlotlyTutorial.ipynb
jaabberwocky/jaabberwocky.github.io
mit
Layout The Layout object will define the look of the plot, and plot features which are unrelated to the data. So we will be able to change things like the title, axis titles, spacing, font and even draw shapes on top of your plot!
layout
Python/Plotly/PlotlyTutorial.ipynb
jaabberwocky/jaabberwocky.github.io
mit
Annotations We added a plot title as well as titles for all the axes. For fun we could add some text annotation as well in order to indicate the maximum point that's been plotted on the current plotting surface.
# highest point layout.update(dict( annotations=[Annotation( text="Highest Point", x=3, y=6)] ) ) py.offline.iplot(Figure(data=data, layout=layout), filename='pyguide_4') #lowest point layout.update(dict( annotations = [Annotation( text = "lowest point", x=1, y=4)])) py.offl...
Python/Plotly/PlotlyTutorial.ipynb
jaabberwocky/jaabberwocky.github.io
mit
Shapes Let's add a rectangular block to highlight the section where trace 1 is above trace2.
layout.update(dict( annotations=[Annotation( text="Highest Point", x=3, y=6)], shapes = [ # 1st highlight during Feb 4 - Feb 6 { 'type': 'rect', # x-reference is assigned to the x-values 'xref': 'x', # y-reference is assig...
Python/Plotly/PlotlyTutorial.ipynb
jaabberwocky/jaabberwocky.github.io
mit
Load some data
from datasets import get_pbc d = get_pbc(prints=True, norm_in=True, norm_out=False) durcol = d.columns[0] eventcol = d.columns[1] if np.any(d[durcol] < 0): raise ValueError("Negative times encountered") # Sort the data before training - handled by ensemble #d.sort(d.columns[0], inplace=True) # Example: d.iloc[...
AnnGroups.ipynb
spacecowboy/article-annriskgroups-source
gpl-3.0
Create an ANN model With all correct parameters, ensemble settings and such.
import ann from classensemble import ClassEnsemble mingroup = int(0.25 * d.shape[0]) def get_net(func=ann.geneticnetwork.FITNESS_SURV_KAPLAN_MIN): hidden_count = 10 outcount = 2 l = (d.shape[1] - 2) + hidden_count + outcount + 1 net = ann.geneticnetwork((d.shape[1] - 2), hidden_count, outcount) n...
AnnGroups.ipynb
spacecowboy/article-annriskgroups-source
gpl-3.0
Train the ANNs And print groupings on training data.
e.fit(d, durcol, eventcol) # grouplabels = e.predict_classes grouplabels, mems = e.label_data(d) for l, m in mems.items(): print("Group", l, "has", len(m), "members")
AnnGroups.ipynb
spacecowboy/article-annriskgroups-source
gpl-3.0
Plot grouping
from lifelines.plotting import add_at_risk_counts from lifelines.estimation import KaplanMeierFitter from lifelines.estimation import median_survival_times plt.figure() fitters = [] for g in ['high', 'mid', 'low']: kmf = KaplanMeierFitter() fitters.append(kmf) members = grouplabels == g kmf.f...
AnnGroups.ipynb
spacecowboy/article-annriskgroups-source
gpl-3.0
Load data Here we consider lin2 data for gor01 on the first recording day (6-7-2006), since this session had the most units (91) of all the gor01 sessions, and lin2 has position data, whereas lin1 only has partial position data.
datadirs = ['/home/etienne/Dropbox/neoReader/Data', 'C:/etienne/Dropbox/neoReader/Data', '/Users/etienne/Dropbox/neoReader/Data'] fileroot = next( (dir for dir in datadirs if os.path.isdir(dir)), None) animal = 'gor01'; month,day = (6,7); session = '16-40-19' # 91 units spikes = load_data(fil...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Find most appropriate number of states using cross validation Here we split the data into training, validation, and test sets. We monitor the average log probability per sequence (normalized by length) for each of these sets, and we use the validation set to choose the number of model states $m$. Note to self: I shoul...
## bin ALL spikes ds = 0.125 # bin spikes into 125 ms bins (theta-cycle inspired) binned_spikes_all = klab.bin_spikes(spikes.data, ds=ds, fs=spikes.samprate, verbose=True) ## identify boundaries for running (active) epochs and then bin those observations into separate sequences: runbdries = klab.get_boundaries_from_bi...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Remarks: We see that the training error is decreasing (equivalently, the training log probability is increasing) over the entire range of states considered. Indeed, we have computed this for a much larger number of states, and the training error keeps on decreasing, whereas both the validation and test errors reach a p...
from placefieldviz import hmmplacefieldposviz num_states = 35 ds = 0.0625 # bin spikes into 62.5 ms bins (theta-cycle inspired) vth = 8 # units/sec velocity threshold for place fields #state_pos, peakorder = hmmplacefieldposviz(num_states=num_states, ds=ds, posdf=posdf, spikes=spikes, speed=speed, vth=vth) fig, axes...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Remarks: As can be expected, with low velocity thresholds, we see an overrepresentation of the reward locations, and only a relatively small number of states that are dedicated to encoding the position along the track. Recall that the track was shortened halfway through the recording session. Here, the reward location...
from placefieldviz import hmmplacefieldposviz num_states = 35 ds = 0.0625 # bin spikes into 62.5 ms bins (theta-cycle inspired) vth = 8 # units/sec velocity threshold for place fields #state_pos, peakorder = hmmplacefieldposviz(num_states=num_states, ds=ds, posdf=posdf, spikes=spikes, speed=speed, vth=vth) fig, axes...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Remarks: First, we see that independent of the number of states, the model captures the place field like nature of the underlying states very well. Furthermore, the bifurcation of some states to represent both the first and second halves of the experiment becomes clear with as few as 15 states, but interestingly this b...
from placefieldviz import hmmplacefieldposviz num_states = 35 ds = 0.0625 # bin spikes into 62.5 ms bins (theta-cycle inspired) vth = 8 # units/sec velocity threshold for place fields #state_pos, peakorder = hmmplacefieldposviz(num_states=num_states, ds=ds, posdf=posdf, spikes=spikes, speed=speed, vth=vth) fig, axes...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Remarks: We notice that we clearly see the bimodal place fields when the timescales are sufficiently small, with a particularly clear example at 62.5 ms, for example. Larger timescales tend to focus on the longer track piece, with a single trajectory being skewed away towards the shorter track piece. Next we consider t...
from placefieldviz import hmmplacefieldposviz num_states = 35 ds = 0.0625 # bin spikes into 62.5 ms bins (theta-cycle inspired) vth = 8 # units/sec velocity threshold for place fields #state_pos, peakorder = hmmplacefieldposviz(num_states=num_states, ds=ds, posdf=posdf, spikes=spikes, speed=speed, vth=vth) fig, axes...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Remarks: Again, we see that with larger timescales, the spatial resolution becomes more coarse, because we don't have that sufficiently many observations, and the modes of the place fields tend to lie close to those associated wit the longer track. Splitting the experimment in half Just as a confirmation of what we've ...
from placefieldviz import hmmplacefieldposviz num_states = 25 ds = 0.0625 # bin spikes into 62.5 ms bins (theta-cycle inspired) vth = 8 # units/sec velocity threshold for place fields state_pos_b, peakorder_b, stateorder_b = hmmplacefieldposviz(num_states=num_states, ds=ds, posdf=posdf, spikes=spikes, speed=speed, vt...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Remarks: We clearly see the bimodal place fields when we use all of the data, and we see the unimodal place fields emerge as we focus on either the first, or the second half of the experiment. Notice that the reward locations are more concentrated, but that the velocity (with fixed state progression) is roughly constan...
from placefieldviz import hmmplacefieldposviz num_states = 45 ds = 0.0625 # bin spikes into 62.5 ms bins (theta-cycle inspired) vth = 8 # units/sec velocity threshold for place fields state_pos_b, peakorder_b, stateorder_b = hmmplacefieldposviz(num_states=num_states, ds=ds, posdf=posdf, spikes=spikes, speed=speed, vt...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
then we stat to see the emergence of the S-shaped place field progressions again, indicating that the reward locations are overexpressed by several different states. This observation is even more pronounced if we increase the number of states further:
from placefieldviz import hmmplacefieldposviz num_states = 100 ds = 0.0625 # bin spikes into 62.5 ms bins (theta-cycle inspired) vth = 8 # units/sec velocity threshold for place fields state_pos_b, peakorder_b, stateorder_b = hmmplacefieldposviz(num_states=num_states, ds=ds, posdf=posdf, spikes=spikes, speed=speed, v...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
With enough expressiveness in the number of states, we see the S-shaped curve reappear, which suggests an overexpression of the reward locations, which is consistent with what we see with place cells in animals.
import matplotlib.patches as patches fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(17, 3)) ax1.matshow(state_pos_b[stateorder_b,:], interpolation='none', cmap='OrRd') ax1.set_ylabel('state') ax1.set_xticklabels([]) ax1.set_yticklabels([]) ax1.set_title('learned place fields BOTH; RUN > ' + str(vth) + '; m = ' + ...
ModelSelection.ipynb
kemerelab/NeuroHMM
mit
Dataset We will use the Wisconsin breast cancer dataset for the following questions
import pandas as pd wdbc_source = 'https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data' #wdbc_source = '../datasets/wdbc/wdbc.data' df = pd.read_csv(wdbc_source, header=None) from sklearn.preprocessing import LabelEncoder X = df.loc[:, 2:].values y = df.loc[:, 1].values le = L...
5 Training and Ensemble.ipynb
irsisyphus/machine-learning
apache-2.0
K-fold validation (20 points) Someone wrote the code below to conduct cross validation. Do you see anything wrong with it? And if so, correct the code and provide an explanation.
import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline if Version(sklearn_version) < '0.18': from sklearn.cross_validation import StratifiedKFold else: from sklearn.model_selecti...
5 Training and Ensemble.ipynb
irsisyphus/machine-learning
apache-2.0
Answer Problems with the original code: Use partial fit for all folds, which results in dependent training and thus cumulative learning.<br> Due to problem 1, we the CV accuracy is incorrect, and not able to show score for every epoch. <br> There are two major changes: We create a list of Perceptrons, each correspon...
from sklearn.metrics import roc_curve, precision_recall_curve, auc from scipy import interp from sklearn.linear_model import LogisticRegression pipe_lr = Pipeline([('scl', StandardScaler()), ('pca', PCA(n_components=2)), ('clf', LogisticRegression(penalty='l2', ...
5 Training and Ensemble.ipynb
irsisyphus/machine-learning
apache-2.0
Explanation Definition REC(recall) = TPR(true positive rate) = $\frac{TP}{TP+FN}$<br> PRE(precision) = $\frac{TP}{TP+FP}$<br> FPR(false positive rate) = $\frac{FP}{FP+TN}$<br> TP: Actual Class $A$, test result $A$<br> FP: Actual Class $B$, test result $A$<br> TN: Actual Class $B$, test result $B$<br> FN: Actual Class $...
from scipy.misc import comb import math import numpy as np def ensemble_error(num_classifier, base_error): k_start = math.ceil(num_classifier/2) probs = [comb(num_classifier, k)*(base_error**k)*((1-base_error)**(num_classifier-k)) for k in range(k_start, num_classifier+1)] return sum(probs) import matplot...
5 Training and Ensemble.ipynb
irsisyphus/machine-learning
apache-2.0
Number of classifiers (40 points) The function plot_base_error() above plots the ensemble error as a function of the base error given a fixed number of classifiers. Write another function to plot ensembe error versus different number of classifiers with a given base error. Does the ensemble error always go down with mo...
def plot_num_classifier(ensemble_error_func, max_num_classifier, base_error): num_classifiers = range(1, max_num_classifier+1) ensemble_errors = [ensemble_error_func(num_classifier = num_classifier, base_error=base_error) for num_classifier in num_classifiers] plt.plot(num_classifiers, ensemble_errors, ...
5 Training and Ensemble.ipynb
irsisyphus/machine-learning
apache-2.0
Explanation Observations: The ensemble error DOES NOT ALWAYS go down with more classifiers.<br> Overall, the ensemble error declines as the number of classifiers increases. However, when the number of calssifiers $N = 2k$, the error is much higher than $N = 2k-1$ and $2k+1$. Reason: This is because when a draw comes, i...
def better_ensemble_error(num_classifier, base_error): k_start = math.ceil(num_classifier/2) probs = [comb(num_classifier, k)*(base_error**k)*((1-base_error)**(num_classifier-k)) for k in range(k_start, num_classifier+1)] if num_classifier % 2 == 0: probs.append(-0.5*comb(num_classifier, k_start)*(b...
5 Training and Ensemble.ipynb
irsisyphus/machine-learning
apache-2.0
The frame represented by video 98, frame 1 is shown here: Feature selection for training the model The objective of feature selection when training a model is to choose the most relevant variables while keeping the model as simple as possible, thus reducing training time. We can use the raw features already provided ...
asl.df['grnd-ry'] = asl.df['right-y'] - asl.df['nose-y'] asl.df.head() # the new feature 'grnd-ry' is now in the frames dictionary
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Try it!
from asl_utils import test_features_tryit # TODO add df columns for 'grnd-rx', 'grnd-ly', 'grnd-lx' representing differences between hand and nose locations asl.df['grnd-rx'] = asl.df['right-x'] - asl.df['nose-x'] asl.df['grnd-ly'] = asl.df['left-y'] - asl.df['nose-y'] asl.df['grnd-lx'] = asl.df['left-x'] - asl.df['nos...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Build the training set Now that we have a feature list defined, we can pass that list to the build_training method to collect the features for all the words in the training set. Each word in the training set has multiple examples from various videos. Below we can see the unique words that have been loaded into the tr...
training = asl.build_training(features_ground) print("Training words: {}".format(training.words))
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
The training data in training is an object of class WordsData defined in the asl_data module. in addition to the words list, data can be accessed with the get_all_sequences, get_all_Xlengths, get_word_sequences, and get_word_Xlengths methods. We need the get_word_Xlengths method to train multiple sequences with the hm...
training.get_word_Xlengths('CHOCOLATE')
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
More feature sets So far we have a simple feature set that is enough to get started modeling. However, we might get better results if we manipulate the raw values a bit more, so we will go ahead and set up some other options now for experimentation later. For example, we could normalize each speaker's range of motion...
df_means = asl.df.groupby('speaker').mean() df_means
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
To select a mean that matches by speaker, use the pandas map method:
asl.df['left-x-mean']= asl.df['speaker'].map(df_means['left-x']) asl.df.head()
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Try it!
from asl_utils import test_std_tryit # TODO Create a dataframe named `df_std` with standard deviations grouped by speaker df_std = asl.df.groupby('speaker').std() # test the code test_std_tryit(df_std)
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
<a id='part1_submission'></a> Features Implementation Submission Implement four feature sets and answer the question that follows. - normalized Cartesian coordinates - use mean and standard deviation statistics and the standard score equation to account for speakers with different heights and arm length polar coo...
# TODO add features for normalized by speaker values of left, right, x, y # Name these 'norm-rx', 'norm-ry', 'norm-lx', and 'norm-ly' # using Z-score scaling (X-Xmean)/Xstd columns = ['right-x','right-y','left-x','left-y'] features_norm = ['norm-rx','norm-ry', 'norm-lx','norm-ly'] for i,f in enumerate(features_norm): ...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Question 1: What custom features did you choose for the features_custom set and why? Answer 1: The custom features choosen is the addition of normalized polar coordinates with the delta values. Polar coordinates are used to make the nose the origin of the frame and all the frame points orbit around it. Normalization ...
import unittest # import numpy as np class TestFeatures(unittest.TestCase): def test_features_ground(self): sample = (asl.df.ix[98, 1][features_ground]).tolist() self.assertEqual(sample, [9, 113, -12, 119]) def test_features_norm(self): sample = (asl.df.ix[98, 1][features_norm]).tolis...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
<a id='part2_tutorial'></a> PART 2: Model Selection Model Selection Tutorial The objective of Model Selection is to tune the number of states for each word HMM prior to testing on unseen data. In this section you will explore three methods: - Log likelihood using cross-validation folds (CV) - Bayesian Information Cri...
import warnings from hmmlearn.hmm import GaussianHMM def train_a_word(word, num_hidden_states, features): warnings.filterwarnings("ignore", category=DeprecationWarning) training = asl.build_training(features) X, lengths = training.get_word_Xlengths(word) model = GaussianHMM(n_components=num_hidd...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
The HMM model has been trained and information can be pulled from the model, including means and variances for each feature and hidden state. The log likelihood for any individual sample or group of samples can also be calculated with the score method.
def show_model_stats(word, model): print("Number of states trained in model for {} is {}".format(word, model.n_components)) variance=np.array([np.diag(model.covars_[i]) for i in range(model.n_components)]) for i in range(model.n_components): # for each hidden state print("hidden state #{}"....
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Try it! Experiment by changing the feature set, word, and/or num_hidden_states values in the next cell to see changes in values.
my_testword = 'CHOCOLATE' model, logL = train_a_word(my_testword, 3, features_ground) # Experiment here with different parameters show_model_stats(my_testword, model) print("logL = {}".format(logL))
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Visualize the hidden states We can plot the means and variances for each state and feature. Try varying the number of states trained for the HMM model and examine the variances. Are there some models that are "better" than others? How can you tell? We would like to hear what you think in the classroom online.
%matplotlib inline import math from matplotlib import (cm, pyplot as plt, mlab) def visualize(word, model): """ visualize the input model for a particular word """ variance=np.array([np.diag(model.covars_[i]) for i in range(model.n_components)]) figures = [] for parm_idx in range(len(model.means_[0]))...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
ModelSelector class Review the ModelSelector class from the codebase found in the my_model_selectors.py module. It is designed to be a strategy pattern for choosing different model selectors. For the project submission in this section, subclass SelectorModel to implement the following model selectors. In other words...
from my_model_selectors import SelectorConstant training = asl.build_training(features_ground) # Experiment here with different feature sets defined in part 1 word = 'VEGETABLE' # Experiment here with different words model = SelectorConstant(training.get_all_sequences(), training.get_all_Xlengths(), word, n_constant=...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Cross-validation folds If we simply score the model with the Log Likelihood calculated from the feature sequences it has been trained on, we should expect that more complex models will have higher likelihoods. However, that doesn't tell us which would have a better likelihood score on unseen data. The model will likel...
from sklearn.model_selection import KFold training = asl.build_training(features_ground) # Experiment here with different feature sets word = 'VEGETABLE' # Experiment here with different words word_sequences = training.get_word_sequences(word) split_method = KFold() for cv_train_idx, cv_test_idx in split_method.split(...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Tip: In order to run hmmlearn training using the X,lengths tuples on the new folds, subsets must be combined based on the indices given for the folds. A helper utility has been provided in the asl_utils module named combine_sequences for this purpose. Scoring models with other criterion Scoring model topologies with B...
words_to_train = ['FISH', 'BOOK', 'VEGETABLE', 'FUTURE', 'JOHN'] import timeit # TODO: Implement SelectorCV in my_model_selector.py from my_model_selectors import SelectorCV training = asl.build_training(features_ground) # Experiment here with different feature sets defined in part 1 sequences = training.get_all_seq...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Question 2: Compare and contrast the possible advantages and disadvantages of the various model selectors implemented. Answer 2: SelectorBIC (lowest Baysian Information Criterion(BIC) score) Advantage : It penalizes the complexity of the model where complexity refers to the number of parameters in the model. Disadvan...
from asl_test_model_selectors import TestSelectors suite = unittest.TestLoader().loadTestsFromModule(TestSelectors()) unittest.TextTestRunner().run(suite)
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
<a id='part3_tutorial'></a> PART 3: Recognizer The objective of this section is to "put it all together". Using the four feature sets created and the three model selectors, you will experiment with the models and present your results. Instead of training only five specific words as in the previous section, train the ...
# autoreload for automatically reloading changes made in my_model_selectors and my_recognizer %load_ext autoreload %autoreload 2 from my_model_selectors import SelectorConstant def train_all_words(features, model_selector): training = asl.build_training(features) # Experiment here with different feature sets def...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Load the test set The build_test method in ASLdb is similar to the build_training method already presented, but there are a few differences: - the object is type SinglesData - the internal dictionary keys are the index of the test word rather than the word itself - the getter methods are get_all_sequences, get_all_Xle...
test_set = asl.build_test(features_ground) print("Number of test set items: {}".format(test_set.num_items)) print("Number of test set sentences: {}".format(len(test_set.sentences_index)))
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
<a id='part3_submission'></a> Recognizer Implementation Submission For the final project submission, students must implement a recognizer following guidance in the my_recognizer.py module. Experiment with the four feature sets and the three model selection methods (that's 12 possible combinations). You can add and rem...
# TODO implement the recognize method in my_recognizer from my_recognizer import recognize from asl_utils import show_errors # TODO Choose a feature set and model selector features = custom_features # change as needed model_selector = SelectorCV # change as needed # TODO Recognize the test set and display the result ...
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Question 3: Summarize the error results from three combinations of features and model selectors. What was the "best" combination and why? What additional information might we use to improve our WER? For more insight on improving WER, take a look at the introduction to Part 4. Answer 3: Using the custom_features, bu...
from asl_test_recognizer import TestRecognize suite = unittest.TestLoader().loadTestsFromModule(TestRecognize()) unittest.TextTestRunner().run(suite)
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
<a id='part4_info'></a> PART 4: (OPTIONAL) Improve the WER with Language Models We've squeezed just about as much as we can out of the model and still only get about 50% of the words right! Surely we can do better than that. Probability to the rescue again in the form of statistical language models (SLM). The basic ...
# create a DataFrame of log likelihoods for the test word items df_probs = pd.DataFrame(data=probabilities) df_probs.head()
Udacity-Artificial-Intelligence-Nanodegree/Project-4/asl_recognizer.ipynb
joelowj/Udacity-Projects
apache-2.0
Structures like these are encoded in "PDB" files How can we parse a complicted file like this one?
import pandas as pd pd.read_table("data/1stn.pdb")
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
We can do better by manually parsing the file. Our test file Predict what this will print
f = open("test-file.txt") print(f.readlines()) f.close()
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Predict what this will print
f = open("test-file.txt") for line in f.readlines(): print(line) f.close()
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Predict what this will print
f = open("test-file.txt") for line in f.readlines(): print(line,end="") f.close()
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Basic file reading operations: Open a file for reading: f = open(SOME_FILE_NAME) Read lines of file sequentially: f.readlines() Read one line from the file: f.readline() Read the whole file into a string: f.read() Close the file: f.close() Now what do we do with each line? Predict what the following program will do
f = open("test-file.txt") for line in f.readlines(): print(line.split()) f.close()
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Predict what the following program will do
f = open("test-file.txt") for line in f.readlines(): print(line.split("1")) f.close()
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Splitting strings SOME_STRING.split(CHAR_TO_SPLIT_ON) allows you to split strings into a list. If CHAR_TO_SPLIT_ON is not defined, it will split on all whitespace (" ","\t","\n","\r") "\t" is TAB, "\n" is NEWLINE, "\r" is CARRIAGE_RETURN. Predict what the following will do
f = open("test-file.txt") lines = f.readlines() f.close() line_of_interest = lines[-1] value = line_of_interest.split()[0] print(value)
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Predict what will happen:
print(value*5)
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
value is a string of "1.5". You can't do math on it yet. The solution is to cast it into a float
value_as_float = float(value) print(value_as_float*5)
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Cast calls: float, int, str, list, tuple
list("1.5")
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Write a program that grabs the "1" from the first line in the file and multiplies it by 75.
f = open("test-file.txt") lines = f.readlines() f.close() value = lines[0].split(" ")[1] value_as_int = int(value) print(value_as_int*75)
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
What about writing to files? Basic file writing operations: Open a file for writing: f = open(SOME_FILE_NAME,'w') will wipe out file immediately! Open a file to append: f = open(SOME_FILE_NAME,'a') Write a string to a file: f.write(SOME_STRING) Write a list of strings: f.writelines([STRING1,STRING2,...]) Close the fil...
def file_printer(file_name): f = open(file_name) for line in f.readlines(): print(line,end="") f.close()
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Predict what this code will do
a_list = ["a","b","c"] f = open("another-file.txt","w") for a in a_list: f.write(a) f.close() file_printer("another-file.txt")
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Predict what this code will do
a_list = ["a","b","c"] f = open("another-file.txt","w") for a in a_list: f.write(a) f.write("\n") f.close() file_printer("another-file.txt")
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Predict what this code will do
a_list = ["a","b","ccat"] f = open("another-file.txt","w") for a in a_list: f.write("A test {{}} {}\n".format(a)) f.close() file_printer("another-file.txt")
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
format lets you make pretty strings
print("The value is: {:}".format(10.35151)) print("The value is: {:.2f}".format(10.35151)) print("The value is: {:20.2f}".format(10.35151)) print("The value is: {:}".format(10)) print("The value is: {:20d}".format(10))
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
String formatting Pretty decimal printing: "{:LENGITH_OF_STRING.NUM_DECIMALSf}".format(FLOAT) Pretty integer printing: "{:LENGTH_OF_STRINGd}".format(INT) Pretty string printing: "{:LENGTH_OF_STRINGs}".format(STRING) Create a loop that prints 0 to 9 to a file. Each number should be on its own line, written to 3 deci...
f = open("junk","w") for i in range(10): f.write("{:.3f}\n".format(i)) f.close() file_printer("junk")
chapters/03_dealing-with-files/00_interacting-with-files_key.ipynb
harmsm/pythonic-science
unlicense
Create an array of 10 zeros
np.zeros(10)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Create an array of 10 ones
np.ones(10)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Create an array of 10 fives
np.ones(10) * 5
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Create an array of the integers from 10 to 50
np.arange(10,51)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Create an array of all the even integers from 10 to 50
np.arange(10,51,2)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Create a 3x3 matrix with values ranging from 0 to 8
np.arange(9).reshape(3,3)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Create a 3x3 identity matrix
np.eye(3)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Use NumPy to generate a random number between 0 and 1
np.random.rand(1)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution
np.random.randn(25)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Numpy Indexing and Selection Now you will be given a few matrices, and be asked to replicate the resulting matrix outputs:
mat = np.arange(1,26).reshape(5,5) mat # WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW # BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T # BE ABLE TO SEE THE OUTPUT ANY MORE mat[2:,1:] # WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW # BE CAREFUL NOT TO RUN THE CELL BELOW, OTHE...
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Now do the following Get the sum of all the values in mat
mat.sum()
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Get the standard deviation of the values in mat
mat.std()
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
Get the sum of all the columns in mat
mat.sum(axis=0)
Python-for-Data-Analysis/NumPy/Numpy Exercise - Solutions.ipynb
iannesbitt/ml_bootcamp
mit
TensorBoard Scalars: Logging training metrics in Keras <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/tensorboard/scalars_and_keras"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="...
# Load the TensorBoard notebook extension. %load_ext tensorboard from datetime import datetime from packaging import version import tensorflow as tf from tensorflow import keras import numpy as np print("TensorFlow version: ", tf.__version__) assert version.parse(tf.__version__).release[0] >= 2, \ "This noteboo...
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
Set up data for a simple regression You're now going to use Keras to calculate a regression, i.e., find the best line of fit for a paired data set. (While using neural networks and gradient descent is overkill for this kind of problem, it does make for a very easy to understand example.) You're going to use TensorBoard...
data_size = 1000 # 80% of the data is for training. train_pct = 0.8 train_size = int(data_size * train_pct) # Create some input data between -1 and 1 and randomize it. x = np.linspace(-1, 1, data_size) np.random.shuffle(x) # Generate the output data. # y = 0.5x + 2 + noise y = 0.5 * x + 2 + np.random.normal(0, 0.05,...
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
Training the model and logging loss You're now ready to define, train and evaluate your model. To log the loss scalar as you train, you'll do the following: Create the Keras TensorBoard callback Specify a log directory Pass the TensorBoard callback to Keras' Model.fit(). TensorBoard reads log data from the log direc...
logdir = "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir) model = keras.models.Sequential([ keras.layers.Dense(16, input_dim=1), keras.layers.Dense(1), ]) model.compile( loss='mse', # keras.losses.mean_squared_error optimizer...
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
Examining loss using TensorBoard Now, start TensorBoard, specifying the root log directory you used above. Wait a few seconds for TensorBoard's UI to spin up.
%tensorboard --logdir logs/scalars
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
<!-- <img class="tfo-display-only-on-site" src="https://github.com/tensorflow/tensorboard/blob/master/docs/images/scalars_loss.png?raw=1"/> --> You may see TensorBoard display the message "No dashboards are active for the current data set". That's because initial logging data hasn't been saved yet. As training progres...
print(model.predict([60, 25, 2])) # True values to compare predictions against: # [[32.0] # [14.5] # [ 3.0]]
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
Not bad! Logging custom scalars What if you want to log custom values, such as a dynamic learning rate? To do that, you need to use the TensorFlow Summary API. Retrain the regression model and log a custom learning rate. Here's how: Create a file writer, using tf.summary.create_file_writer(). Define a custom learning ...
logdir = "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S") file_writer = tf.summary.create_file_writer(logdir + "/metrics") file_writer.set_as_default() def lr_schedule(epoch): """ Returns a custom learning rate that decreases as epochs progress. """ learning_rate = 0.2 if epoch > 10: learning_r...
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
Let's look at TensorBoard again.
%tensorboard --logdir logs/scalars
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
<!-- <img class="tfo-display-only-on-site" src="https://github.com/tensorflow/tensorboard/blob/master/docs/images/scalars_custom_lr.png?raw=1"/> --> Using the "Runs" selector on the left, notice that you have a &lt;timestamp&gt;/metrics run. Selecting this run displays a "learning rate" graph that allows you to verify...
print(model.predict([60, 25, 2])) # True values to compare predictions against: # [[32.0] # [14.5] # [ 3.0]]
site/en-snapshot/tensorboard/scalars_and_keras.ipynb
tensorflow/docs-l10n
apache-2.0
Perplexity on Each Dataset
%matplotlib inline from IPython.display import HTML, display def display_table(data): display(HTML( u'<table><tr>{}</tr></table>'.format( u'</tr><tr>'.join( u'<td>{}</td>'.format('</td><td>'.join(unicode(_) for _ in row)) for row in data) ) )) def bar_chart(data...
model_comparisons/noingX_bow_compared.ipynb
kingb12/languagemodelRNN
mit
Loss vs. Epoch
%matplotlib inline plt.figure(figsize=(10, 8)) for rname, l in logs: for k in l.keys(): plt.plot(l[k][0], l[k][1], label=str(k) + ' ' + rname + ' (train)') plt.plot(l[k][0], l[k][2], label=str(k) + ' ' + rname + ' (valid)') plt.title('Loss v. Epoch') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend...
model_comparisons/noingX_bow_compared.ipynb
kingb12/languagemodelRNN
mit
Perplexity vs. Epoch
%matplotlib inline plt.figure(figsize=(10, 8)) for rname, l in logs: for k in l.keys(): plt.plot(l[k][0], l[k][3], label=str(k) + ' ' + rname + ' (train)') plt.plot(l[k][0], l[k][4], label=str(k) + ' ' + rname + ' (valid)') plt.title('Perplexity v. Epoch') plt.xlabel('Epoch') plt.ylabel('Perplexity'...
model_comparisons/noingX_bow_compared.ipynb
kingb12/languagemodelRNN
mit
Generations
def print_sample(sample, best_bleu=None): enc_input = ' '.join([w for w in sample['encoder_input'].split(' ') if w != '<pad>']) gold = ' '.join([w for w in sample['gold'].split(' ') if w != '<mask>']) print('Input: '+ enc_input + '\n') print('Gend: ' + sample['generated'] + '\n') print('True: ' + go...
model_comparisons/noingX_bow_compared.ipynb
kingb12/languagemodelRNN
mit
BLEU Analysis
def print_bleu(blue_structs): data= [['<b>Model</b>', '<b>Overall Score</b>','<b>1-gram Score</b>','<b>2-gram Score</b>','<b>3-gram Score</b>','<b>4-gram Score</b>']] for rname, blue_struct in blue_structs: data.append([rname, blue_struct['score'], blue_struct['components']['1'], blue_struct['components...
model_comparisons/noingX_bow_compared.ipynb
kingb12/languagemodelRNN
mit
N-pairs BLEU Analysis This analysis randomly samples 1000 pairs of generations/ground truths and treats them as translations, giving their BLEU score. We can expect very low scores in the ground truth and high scores can expose hyper-common generations
# Training Set BLEU n-pairs Scores print_bleu([(rname, report['n_pairs_bleu_train']) for (rname, report) in reports]) # Validation Set n-pairs BLEU Scores print_bleu([(rname, report['n_pairs_bleu_valid']) for (rname, report) in reports]) # Test Set n-pairs BLEU Scores print_bleu([(rname, report['n_pairs_bleu_test']) ...
model_comparisons/noingX_bow_compared.ipynb
kingb12/languagemodelRNN
mit
Alignment Analysis This analysis computs the average Smith-Waterman alignment score for generations, with the same intuition as N-pairs BLEU, in that we expect low scores in the ground truth and hyper-common generations to raise the scores
def print_align(reports): data= [['<b>Model</b>', '<b>Average (Train) Generated Score</b>','<b>Average (Valid) Generated Score</b>','<b>Average (Test) Generated Score</b>','<b>Average (All) Generated Score</b>', '<b>Average (Gold) Score</b>']] for rname, report in reports: data.append([rname, report['av...
model_comparisons/noingX_bow_compared.ipynb
kingb12/languagemodelRNN
mit