markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Fit information equilibrium parameters
Here we take the information equilibrium model with A = nominal GDP, B = labor employed (PAYEMS), and p = CPI (all items). First we solve for the IT index and show the model. Note: this is a simple model with limited accuracy. | result = IEtools.fitGeneralInfoEq(gdp['data'],lab['data'], guess=[1.0,0.0])
print(result)
print('IT index = ',np.round(result.x[0],decimals=2))
time=gdp['interp'].x
pl.plot(time,np.exp(result.x[0]*np.log(lab['interp'](time))+result.x[1]),label='model')
pl.plot(time,gdp['interp'](time),label='data')
pl.yscale('log')
pl.ylabel(gdp['name']+' [G$]')
pl.legend()
pl.show() | IEtools Demo.ipynb | infotranecon/IEtools | mit |
And we can show the relationship between the growth rates (i.e. compute the inflation rate equal to the growth rate of the CPI) | time=gdp['data'][:,0]
der1=gdp['growth'](time)-lab['growth'](time)
der2=cpi['growth'](time)
pl.plot(time,der1,label='model')
pl.plot(time,der2,label='data')
pl.legend()
pl.show() | IEtools Demo.ipynb | infotranecon/IEtools | mit |
Additionally, rearranging the terms and looking at the growth rate, we can show a form of Okun's law. Since g_p = g_a - g_b, we can say g_b = g_a - g_p. The right hand side of the last equation when A is nominal GDP and p is the CPI is the CPI-deflated real GDP growth. Okun's law is an inverse relationship between the change in unemployment and RGDP growth, but in our case we will look at the direct relationship of RGDP growth and change in employment (PAYEMS). | time=gdp['data'][:,0]
der1=gdp['growth'](time)-cpi['growth'](time)
der2=lab['growth'](time)
pl.plot(time,der1,label='model')
pl.plot(time,der2,label='data')
pl.legend()
pl.show() | IEtools Demo.ipynb | infotranecon/IEtools | mit |
IO: Reading and preprocess the data
We can define a function which will read the data and process them. | def read_spectra(path_csv):
"""Read and parse data in pandas DataFrames.
Parameters
----------
path_csv : str
Path to the CSV file to read.
Returns
-------
s : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all Raman spectra.
c : pandas Series, shape (n_spectra,)
Series containing the concentration of the molecule.
m : pandas Series, shape (n_spectra,)
Series containing the type of chemotherapeutic agent.
"""
s = pandas.read_csv(path_csv)
c = s['concentration']
m = s['molecule']
s = s['spectra']
x = []
for spec in s:
x.append(numpy.fromstring(spec[1:-1], sep=','))
s = pandas.DataFrame(x)
return s, c, m
# read the frequency and get a pandas serie
f = pandas.read_csv('data/freq.csv')['freqs']
# read all data for training
filenames = ['data/spectra_{}.csv'.format(i)
for i in range(4)]
stot = []
c = []
m = []
for filename in filenames:
s_tmp, c_tmp, m_tmp = read_spectra(filename)
stot.append(s_tmp)
c.append(c_tmp)
m.append(m_tmp)
stot = pandas.concat(stot)
c = pandas.concat(c)
m = pandas.concat(m) | Day_2_Software_engineering_best_practices/solutions/02_docstring.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Plot helper functions
We can create two functions: (i) to plot all spectra and (ii) plot the mean spectra with the std intervals.
We will make a "private" function which will be used by both plot types. | def _apply_axis_layout(ax, title):
"""Apply despine style and add labels to axis."""
ax.set_xlabel('Frequency')
ax.set_ylabel('Concentration')
ax.set_title(title)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.spines['left'].set_position(('outward', 10))
ax.spines['bottom'].set_position(('outward', 10))
def plot_spectra(f, s, title):
"""Plot a bunch of Raman spectra.
Parameters
----------
f : pandas Series, shape (n_freq_points,)
Frequencies for which the Raman spectra were acquired.
s : pandas DataFrame, shape (n_spectra, n_freq_points)
DataFrame containing all Raman spectra.
title : str
Title added to the plot.
Returns
-------
None
"""
fig, ax = pyplot.subplots()
ax.plot(f, s.T)
_apply_axis_layout(ax, title)
def plot_spectra_by_type(f, s, classes, title):
"""Plot mean spectrum with its variance for a given class.
Parameters
----------
f : pandas Series, shape (n_freq_points,)
Frequencies for which the Raman spectra were acquired.
s : pandas DataFrame, shape (n_spectra, n_freq_points)
DataFrame containing all Raman spectra.
classes : array-like, shape (n_classes,)
Array contining the different spectra class which will be plotted.
title : str
Title added to the plot.
Returns
-------
None
"""
fig, ax = pyplot.subplots()
for c_type in numpy.unique(classes):
i = numpy.nonzero(classes == c_type)[0]
ax.plot(f, numpy.mean(s.iloc[i], axis=0), label=c_type)
ax.fill_between(f, numpy.mean(s.iloc[i], axis=0) + numpy.std(s.iloc[i], axis=0), numpy.mean(s.iloc[i], axis=0) - numpy.std(s.iloc[i], axis=0), alpha=0.2)
_apply_axis_layout(ax, title)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plot_spectra(f, stot, 'All training spectra')
plot_spectra_by_type(f, stot, m, 'Mean spectra in function of the molecules')
plot_spectra_by_type(f, stot, c, 'Mean spectra in function of the concentrations') | Day_2_Software_engineering_best_practices/solutions/02_docstring.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Reusability for new data: | s4, c4, m4 = read_spectra('data/spectra_4.csv')
plot_spectra(f, stot, 'All training spectra')
plot_spectra_by_type(f, s4, m4, 'Mean spectra in function of the molecules')
plot_spectra_by_type(f, s4, c4, 'Mean spectra in function of the concentrations') | Day_2_Software_engineering_best_practices/solutions/02_docstring.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Training and testing a machine learning model for classification | def plot_cm(cm, classes, title):
"""Plot a confusion matrix.
Parameters
----------
cm : ndarray, shape (n_classes, n_classes)
Confusion matrix.
classes : array-like, shape (n_classes,)
Array contining the different spectra classes used in the
classification problem.
title : str
Title added to the plot.
Returns
-------
None
"""
import itertools
fig, ax = pyplot.subplots()
pyplot.imshow(cm, interpolation='nearest', cmap='bwr')
pyplot.title(title)
pyplot.colorbar()
tick_marks = numpy.arange(len(numpy.unique(classes)))
pyplot.xticks(tick_marks, numpy.unique(classes), rotation=45)
pyplot.yticks(tick_marks, numpy.unique(classes))
fmt = 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
pyplot.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
pyplot.tight_layout()
pyplot.ylabel('True label')
pyplot.xlabel('Predicted label')
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.metrics import confusion_matrix
for clf in [RandomForestClassifier(random_state=0),
LinearSVC(random_state=0)]:
p = make_pipeline(StandardScaler(), PCA(n_components=100, random_state=0), clf)
p.fit(stot, m)
pred = p.predict(s4)
plot_cm(confusion_matrix(m4, pred), p.classes_, 'Confusion matrix using {}'.format(clf.__class__.__name__))
print('Accuracy score: {0:.2f}'.format(p.score(s4, m4))) | Day_2_Software_engineering_best_practices/solutions/02_docstring.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Training and testing a machine learning model for regression | def plot_regression(y_true, y_pred, title):
"""Plot actual vs. predicted scatter plot.
Parameters
----------
y_true : array-like, shape (n_samples,)
Ground truth (correct) target values.
y_pred : array-like, shape (n_samples,)
Estimated targets as returned by a regressor.
title : str
Title added to the plot.
Returns
-------
None
"""
from sklearn.metrics import r2_score, median_absolute_error
fig, ax = pyplot.subplots()
ax.scatter(y_true, y_pred)
ax.plot([0, 25000], [0, 25000], '--k')
ax.set_ylabel('Target predicted')
ax.set_xlabel('True Target')
ax.set_title(title)
ax.text(1000, 20000, r'$R^2$=%.2f, MAE=%.2f' % (
r2_score(y_true, y_pred), median_absolute_error(y_true, y_pred)))
ax.set_xlim([0, 25000])
ax.set_ylim([0, 25000])
from sklearn.decomposition import PCA
from sklearn.linear_model import RidgeCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import make_pipeline
for reg in [RidgeCV(), RandomForestRegressor(random_state=0)]:
p = make_pipeline(PCA(n_components=100), reg)
p.fit(stot, c)
pred = p.predict(s4)
plot_regression(c4, pred, 'Regression using {}'.format(reg.__class__.__name__))
def fit_params(data):
"""Compute statistics for robustly scale data.
Compute the median and the variance, i.e. the difference
between the 75th and 25th percentiles.
These statistics are used later to scale data.
Parameters
----------
data : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all Raman spectra.
Returns
-------
median : ndarray, shape (n_freq_point,)
Median for each wavelength.
variance : ndarray, shape (n_freq_point,)
Variance (difference between the 75th and 25th
percentiles) for each wavelength.
"""
median = numpy.median(data, axis=0)
p_25 = numpy.percentile(data, 25, axis=0)
p_75 = numpy.percentile(data, 75, axis=0)
return median, (p_75 - p_25)
def transform(data, median, var_25_75):
"""Scale data using robust estimators.
Scale the data by subtracting the median and dividing by the
variance, i.e. the difference between the 75th and 25th percentiles.
Parameters
----------
data : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all Raman spectra.
median : ndarray, shape (n_freq_point,)
Median for each wavelength.
var_25_75 : ndarray, shape (n_freq_point,)
Variance (difference between the 75th and 25th
percentiles) for each wavelength.
Returns
-------
data_scaled : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all scaled Raman spectra.
"""
return (data - median) / var_25_75
median, var_25_75 = fit_params(stot)
stot_scaled = transform(stot, median, var_25_75)
s4_scaled = transform(s4, median, var_25_75)
from sklearn.decomposition import PCA
from sklearn.linear_model import RidgeCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import make_pipeline
for reg in [RidgeCV(), RandomForestRegressor(random_state=0)]:
p = make_pipeline(PCA(n_components=100), reg)
p.fit(stot_scaled, c)
pred = p.predict(s4_scaled)
plot_regression(c4, pred, 'Regression using {}'.format(reg.__class__.__name__)) | Day_2_Software_engineering_best_practices/solutions/02_docstring.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
DataStructureBase is the base class for implementing data structures
DataStructureVisualization is the class that visualizes data structures in GUI
DataStructureBase class
Any data structure, which is to be implemented, has to be derived from this class. Now we shall see data members and member functions of this class:
Data Members
name - Name of the DS
file_path - Path to store output of DS operations
Member Functions
__init__(self, name, file_path) - Initializes DS with a name and a file_path to store the output
insert(self, item) - Inserts item into the DS
delete(Self, item) - Deletes item from the DS, <br/>            if item is not present in the DS, throws a ValueError
find(self, item) - Finds the item in the DS
<br/>          returns True if found, else returns False<br/>          similar to __contains__(self, item)
get_root(self) - Returns the root (for graph and tree DS)
get_graph(self, rt) - Gets the dict representation between the parent and children (for graph and tree DS)
draw(self, nth=None) - Draws the output to visualize the operations performed on the DS<br/>             nth is used to pass an item to visualize a find operation
DataStructureVisualization class
This class is used for visualizing data structures in a GUI (using GTK+ 3). Now we shall see data members and member functions of this class:
Data Members
ds - Any DS, which is an instance of DataStructureBase
Member Functions
__init__(self, ds) - Initializes ds with an instance of DS that is to be visualized
run(self) - Opens a GUI window to visualize the DS operations
An example ..... Binary Search Tree
Now we shall implement the class BinarySearchTree | class BinarySearchTree(DataStructureBase): # Derived from DataStructureBase
class Node: # Class for creating a node
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def __str__(self):
return str(self.data)
def __init__(self):
DataStructureBase.__init__(self, "Binary Search Tree", "t.png") # Initializing with name and path
self.root = None
self.count = 0
def get_root(self): # Returns root node of the tree
return self.root
def insert(self, item): # Inserts item into the tree
newNode = BinarySearchTree.Node(item)
insNode = self.root
parent = None
while insNode is not None:
parent = insNode
if insNode.data > newNode.data:
insNode = insNode.left
else:
insNode = insNode.right
if parent is None:
self.root = newNode
else:
if parent.data > newNode.data:
parent.left = newNode
else:
parent.right = newNode
self.count += 1
def find(self, item): # Finds if item is present in tree or not
node = self.root
while node is not None:
if item < node.data:
node = node.left
elif item > node.data:
node = node.right
else:
return True
return False
def min_value_node(self): # Returns the minimum value node
current = self.root
while current.left is not None:
current = current.left
return current
def delete(self, item): # Deletes item from tree if present
# else shows Value Error
if item not in self:
dialog = gtk.MessageDialog(None, 0, gtk.MessageType.ERROR,
gtk.ButtonsType.CANCEL, "Value not found ERROR")
dialog.format_secondary_text(
"Element not found in the %s" % self.name)
dialog.run()
dialog.destroy()
else:
self.count -= 1
if self.root.data == item and (self.root.left is None or self.root.right is None):
if self.root.left is None and self.root.right is None:
self.root = None
elif self.root.data == item and self.root.left is None:
self.root = self.root.right
elif self.root.data == item and self.root.right is None:
self.root = self.root.left
return self.root
if item < self.root.data:
temp = self.root
self.root = self.root.left
temp.left = self.delete(item)
self.root = temp
elif item > self.root.data:
temp = self.root
self.root = self.root.right
temp.right = self.delete(item)
self.root = temp
else:
if self.root.left is None:
return self.root.right
elif self.root.right is None:
return self.root.left
temp = self.root
self.root = self.root.right
min_node = self.min_value_node()
temp.data = min_node.data
temp.right = self.delete(min_node.data)
self.root = temp
return self.root
def get_graph(self, rt): # Populates self.graph with elements depending
# upon the parent-children relation
if rt is None:
return
self.graph[rt.data] = {}
if rt.left is not None:
self.graph[rt.data][rt.left.data] = {'child_status': 'left'}
self.get_graph(rt.left)
if rt.right is not None:
self.graph[rt.data][rt.right.data] = {'child_status': 'right'}
self.get_graph(rt.right) | doc/OpenAnalysis/05 - Data Structures.ipynb | sytays/openanalysis | gpl-3.0 |
Now, this program can be executed as follows: | DataStructureVisualization(BinarySearchTree).run()
import io
import base64
from IPython.display import HTML
video = io.open('../res/bst.mp4', 'r+b').read()
encoded = base64.b64encode(video)
HTML(data='''<video alt="test" controls>
<source src="data:video/mp4;base64,{0}" type="video/mp4" />
</video>'''.format(encoded.decode('ascii'))) | doc/OpenAnalysis/05 - Data Structures.ipynb | sytays/openanalysis | gpl-3.0 |
This notebook is designed to reproduce several findings from Ted Underwood and Jordan Sellers's article "How Quickly Do Literary Standards Change?" (draft (2015), forthcoming in <i>Modern Language Quarterly</i>). See especially Fig 1 and reported classifier accuracy (p 8).
Underwood and Sellers have made their corpus of poems and their code available here: https://github.com/tedunderwood/paceofchange
Underwood and Sellers | metadata_tb = Table.read_table('data/poemeta.csv', keep_default_na=False)
metadata_tb.show(5) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We see above a recept column that has their reception status. We want to look at reviewed and random, just like Underwood and Sellers did: | reception_mask = (metadata_tb['recept']=='reviewed') + (metadata_tb['recept']=='random')
clf_tb = metadata_tb.where(reception_mask)
clf_tb.show(5) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Great, now we've successfully subsetted our data!
No we're going to import Term Frequencies by Text. This script is specifically tailored to the format of
textual data made available from Hathi Trust. This consists of a series of spreadsheets, each containing book-level term frequencies.
Each spreadsheet will become a row in our Document-Term Matrix. | # Create list that will contain a series of dictionaries
freqdict_list = []
# Iterate through texts in our spreadsheet
for _id in clf_tb['docid']:
# Each text will have its own dictionary
# Keys are terms and values are frequencies
termfreq_dict = {}
# Open the given text's spreadsheet
with open('data/poems/' + _id + '.poe.tsv', encoding='utf-8') as f:
filelines = f.readlines()
# Each line in the spreadsheet contains a unique term and its frequency
for line in filelines:
termfreq = line.split('\t')
# 'If' conditions throw out junk lines in the spreadsheet
if len(termfreq) > 2 or len(termfreq) > 2:
continue
term, freq = termfreq[0], int(termfreq[1])
if len(term)>0 and term[0].isalpha():
# Create new entry in text's dictionary for the term
termfreq_dict[term] = freq
freqdict_list.append(termfreq_dict) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We can use sklearn's DictVectorizer to turn this into a DTM: | from sklearn.feature_extraction import DictVectorizer
dv = DictVectorizer()
dtm = dv.fit_transform(freqdict_list)
term_list = dv.feature_names_
dtm | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Feature Selection, Training, Prediction
We can put this DTM into a pandas dataframe, very similar to what you know from Table: | dtm_df = pd.DataFrame(dtm.toarray(), columns = term_list)
dtm_df.head() | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Let's add in the docid as the index instead of just a counter for the row: | dtm_df.set_index(clf_tb['docid'], inplace=True)
dtm_df.head() | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Inputs and Outputs
Underwood and Sellers create a unique model for each author in the corpus. They set aside a given author from the training set and then use the model to predict whether she was likely to be reviewed or not. Create a list of authors and an "empty" array in which to record probabilities. | authors = list(set(clf_tb['author']))
probabilities = np.zeros([len(clf_tb['docid'])]) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Now we'll set up the regression model with sklearn.
Underwood and Sellers use a regularization constant ('C') to prevent overfitting, since this is a major concern when observing thousands of variables. | from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(C = 0.00007) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We'll then write a function set_author_aside that sifts out the target author's works from the dataset. Recall that Underwood and Sellers trained a model for each author when they were taken out. | def set_author_aside(author, tb, df):
'''
Set aside each author's texts from training set
'''
train_ids = tb.where(tb['author']!=author).column('docid')
test_ids = tb.where(tb['author']==author).column('docid')
train_df_ = df.loc[train_ids]
test_df_ = df.loc[test_ids]
train_targets_ = tb.where(tb['author']!=author)['recept']=='reviewed'
return train_df_, test_df_, train_targets_ | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We also need to get out the most common words by their document frequency for each model. The function below, top_vocab_by_docfreq will do this each time we loop and create a new model: | def top_vocab_by_docfreq(df, num_words):
'''
Retrieve the most common words (by document frequency) for a given model
'''
docfreq_df = df > 0
wordcolumn_sums = docfreq_df.sum()
words_by_freq = wordcolumn_sums.sort_values(ascending=False)
top_words = words_by_freq[:num_words]
top_words_list = top_words.index.tolist()
return top_words_list | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We then need to normalize the frequencies: | def normalize_model(train_df_, test_df_, vocabulary):
'''
Normalize the model's term frequencies and put them into standard units
'''
# Select columns for only the most common words
train_df_ = train_df_[vocabulary]
test_df_ = test_df_[vocabulary]
# Normalize each value by the sum of all values in its row
train_df_ = train_df_.apply(lambda x: x/sum(x), axis=1)
test_df_ = test_df_.apply(lambda x: x/sum(x), axis=1)
# Get mean and stdev for each column
train_mean = np.mean(train_df_)
train_std = np.std(train_df_)
# Transform each value to standard units for its column
train_df_ = ( train_df_ - train_mean ) / train_std
test_df_ = ( test_df_ - train_mean ) / train_std
return train_df_, test_df_ | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Training and Prediction
The cell below will build a model for just 1 author, let's see how long it takes: | import time
start = time.time()
for author in authors[:1]:
# Set aside each author's texts from training set
train_df, test_df, train_targets = set_author_aside(author, clf_tb, dtm_df)
# Retrieve the most common words (by document frequency) for a given model
vocab_list = top_vocab_by_docfreq(train_df, 3200)
# Normalize the model's term frequencies and put them into standard units
train_df, test_df = normalize_model(train_df, test_df, vocab_list)
# Learn the Logistic Regression over our model
clf.fit(train_df, train_targets)
# Some authors have more than one text in the corpus, so we retrieve all
for _id in test_df.index.tolist():
# Make prediction whether text was reviewed
text = test_df.loc[_id]
probability = clf.predict_proba([text])[0][1]
# Record predictions in same order as the metadata spreadsheet
_index = list(clf_tb.column('docid')).index(_id)
probabilities[_index] = probability
end = time.time()
print(end - start) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
So how long is this going to take us? | len(authors) * (end-start) / 60 | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We don't have 100 minutes!
Efficiency
A lot of that time is figuring out the vocabulary: | len(term_list) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Let's read in a preprocessed vocabulary file. This contains only words that will be used in classification. This list was created by simply iterating through each model and observing the words that appeared in it. | import pickle
with open('data/preprocessed_vocab.pickle', 'rb') as f:
pp_vocab = pickle.load(f)
len(pp_vocab) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Now let's select only columns for words in our pre-processed vocabulary. This will make our computation more efficient later: | dtm_df = dtm_df[pp_vocab] | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We'll use the unique IDs from our metadata to keep track of each text: | dtm_df.set_index(clf_tb['docid'], inplace=True)
dtm_df.head() | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Document Frequency | # Create new DataFrame that simply lists whether a term appears in
# each document, so that we don't have to repeat this process evey iteration
term_in_doc_df = dtm_df>0
term_in_doc_df
# Re-write the model-building function
def set_author_aside(author, tb, dtm_df_, dfreq_df_):
train_ids = tb.where(tb['author']!=author).column('docid')
test_ids = tb.where(tb['author']==author).column('docid')
train_df_ = dtm_df_.loc[train_ids]
dfreq_df_ = dfreq_df_.loc[train_ids] # Include only term_in_doc values for texts in training set
test_df_ = dtm_df_.loc[test_ids]
train_targets_ = tb.where(tb['author']!=author)['recept']=='reviewed'
return train_df_, test_df_, train_targets_, dfreq_df_
# Re-write our vocabulary selection function
def top_vocab_by_docfreq(df, num_words):
# Removed the test of whether a term is in a given document (i.e. df>0)
wordcolumn_sums = sum(df)
words_by_freq = wordcolumn_sums.sort_values(ascending=False)
top_words = words_by_freq[:num_words]
top_words_list = top_words.index.tolist()
return top_words_list | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Parallel Processing | # Parallel Processing means running our script on multiple cores simultaneously
# This can be used in situations where we might otherwise use a 'FOR' loop
# (when it doesn't matter what order we go through the list of values!)
clf = LogisticRegression(C = 0.00007)
def master_function(author):
# Note: Our only input is the name of the author.
# Remember that we had iterated over the list of authors previously.
train_df, test_df, train_targets, dfreq_df = set_author_aside(author, clf_tb, dtm_df, term_in_doc_df)
vocab_list = top_vocab_by_docfreq(dfreq_df, 3200)
train_df, test_df = normalize_model(train_df, test_df, vocab_list)
clf.fit(train_df, train_targets)
# Create a list of each text's probability of review AND its index in the metadata table
index_probability_tuples = []
for _id in test_df.index.tolist():
text = test_df.loc[_id]
probability = clf.predict_proba([text])[0][1]
_index = list(clf_tb.column('docid')).index(_id)
index_probability_tuples.append( (_index, probability) )
return index_probability_tuples
# Multiprocessing enables Python to parallelize
import multiprocessing
# Return number of cores
multiprocessing.cpu_count()
# By default, the Pool contains one worker for each core
# Since we are working on a shared server, we'll set the number
# of workers to 4.
pool = multiprocessing.Pool(4, maxtasksperchild=1)
# Efficiently applies the master_function() to our list of authors
# Returns a list where each entry is an item returned by the function
# Timing the process again
start = time.time()
output = pool.map(master_function, authors)
end = time.time()
print(end-start)
output[:10]
# In this case, each element in output is itself a list ('index_probability_tuples'),
# the length of which is the number of texts by a given author. We'll flatten it for
# ease of use.
flat_output = [tup for lst in output for tup in lst]
flat_output[:10]
# Use the indices returned with the output to arrange probabilities properly
probabilities = np.zeros([len(clf_tb['docid'])])
for tup in flat_output:
probabilities[tup[0]] = tup[1]
clf_tb['P(reviewed)'] = probabilities
clf_tb.select(['docid', 'firstpub','author', 'title', 'recept', 'P(reviewed)']) | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Evaluation | # Visualize the probability each text was reviewed
colors = ['r' if recept=='reviewed' else 'b' for recept in clf_tb['recept']]
clf_tb.scatter('firstpub', 'P(reviewed)', c=colors, fit_line=True)
# Does the Logistic Regression Model think its likely each book was reviewed?
predictions = probabilities>0.5
predictions
from sklearn.metrics import accuracy_score
# Creates array where '1' indicates a reviewed book and '0' indicates not
targets = clf_tb['recept']=='reviewed'
print(accuracy_score(predictions, targets))
# Note: Often we prefer to evaluate accuracy based on the F1-score, which
# weighs the number of times we correctly predicted reviewed texts against
# the number of times we incorrectly predicted them as 'random'.
from sklearn.metrics import f1_score
print(f1_score(predictions, targets))
## EX. Change the regularization parameter ('C') in our Logistic Regression function.
## How does this change the classifier's accuracy?
## EX. Reduce the size of the vocabulary used for classification. How does accuracy change?
## Q. Are there cases when we might not want to set the classification threshold
## to 50% likelihood? How certain are we that 51% is different from a 49% probability? | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
Classification | # Train model using full set of 'reviewed' and 'random' texts
# Use this to predict the probability that other prestigious texts
# (i.e. ones that we haven't trained on) might have been reviewed
# ...if they had been published! The new texts include, for example,
# Emily Dickinson and Gerard Manley Hopkins.
# Re-run script from scratch
%pylab inline
matplotlib.style.use('ggplot')
from datascience import *
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction import DictVectorizer
corpus_path = 'poems/'
# Read metadata from spreadsheet
metadata_tb = Table.read_table('poemeta.csv', keep_default_na=False)
# We'll copy just our new texts into a separate table as well, for later
canon_tb = metadata_tb.where('recept','addcanon')
# Read Term Frequencies from files
freqdict_list = []
# Iterate through texts in our spreadsheet
for _id in metadata_tb['docid']:
# Each text will have its own dictionary
# Keys are terms and values are frequencies
termfreq_dict = {}
# Open the given text's spreadsheet
with open(corpus_path+_id+'.poe.tsv', encoding='utf-8') as file_in:
filelines = file_in.readlines()
# Each line in the spreadsheet contains a unique term and its frequency
for line in filelines:
termfreq = line.split('\t')
# 'If' conditions throw out junk lines in the spreadsheet
if len(termfreq) > 2 or len(termfreq) > 2:
continue
term, freq = termfreq[0], int(termfreq[1])
if len(term)>0 and term[0].isalpha():
# Create new entry in text's dictionary for the term
termfreq_dict[term] = freq
freqdict_list.append(termfreq_dict)
# Create the Document-Term-Matrix
dv = DictVectorizer()
dtm = dv.fit_transform(freqdict_list)
term_list = dv.feature_names_
# Place the DTM into a Pandas DataFrame for further manipulation
dtm_df = pd.DataFrame(dtm.toarray(), columns = term_list)
dtm_df.set_index(metadata_tb['docid'], inplace=True)
# These are Feature Selection functions like the ones we originally defined,
# not their efficiency minded counterparts, since we only train once
# Set aside each canonic texts from training set
def set_canon_aside(tb, df):
train_ids = tb.where(tb['recept']!='addcanon').column('docid')
classify_ids = tb.where(tb['recept']=='addcanon').column('docid')
train_df_ = df.loc[train_ids]
classify_df_ = df.loc[classify_ids]
train_targets_ = tb.where(tb['recept']!='addcanon')['recept']=='reviewed'
return train_df_, classify_df_, train_targets_
# Retrieve the most common words (by document frequency) for a given model
def top_vocab_by_docfreq(df, num_words):
docfreq_df = df > 0
wordcolumn_sums = sum(docfreq_df)
words_by_freq = wordcolumn_sums.sort_values(ascending=False)
top_words = words_by_freq[:num_words]
top_words_list = top_words.index.tolist()
return top_words_list
# Normalize the model's term frequencies and put them into standard units
def normalize_model(train_df_, classify_df_, vocabulary):
# Select columns for only the most common words
train_df_ = train_df_[vocabulary]
classify_df_ = classify_df_[vocabulary]
# Normalize each value by the sum of all values in its row
train_df_ = train_df_.apply(lambda x: x/sum(x), axis=1)
classify_df_ = classify_df_.apply(lambda x: x/sum(x), axis=1)
# Get mean and stdev for each column
train_mean = np.mean(train_df_)
train_std = np.std(train_df_)
# Transform each value to standard units for its column
train_df_ = ( train_df_ - train_mean ) / train_std
classify_df_ = ( classify_df_ - train_mean ) / train_std
return train_df_, classify_df_
# Train our Logistic Regression Model
clf = LogisticRegression(C = 0.00007)
model_df, classify_df, model_targets = set_canon_aside(metadata_tb, dtm_df)
vocab_list = top_vocab_by_docfreq(model_df, 3200)
model_df, classify_df = normalize_model(model_df, classify_df, vocab_list)
clf.fit(model_df, model_targets)
# Predict whether our new prestigious texts might have been reviewed
probabilities = numpy.zeros([len(canon_tb.column('docid'))])
for _id in classify_df.index.tolist():
text = classify_df.loc[_id]
probability = clf.predict_proba([text])[0][1]
_index = list(canon_tb.column('docid')).index(_id)
probabilities[_index] = probability
# Add this probability as a new column to our table of canonic texts
canon_tb['P(reviewed)'] = probabilities
# Visualize
canon_tb.scatter('firstpub','P(reviewed)', fit_line=True)
## Q. Two of the prestigious texts are assigned less than 50% probability
## that they were reviewed. How do we make sense of that? | 08-Classification/02-Underwood-Sellers.ipynb | henchc/Rediscovering-Text-as-Data | mit |
We have 1460 observations, and 81 columns. There quite a few strings too, which we would have to encode later on.
Let's have a look at the number of missing values. | tmp = train.isnull().sum()
# get top 10 results
tmp.sort_values(ascending=False).head(10).plot(kind='bar', figsize=(8,8)) | Python/Machine Learning/Kaggle/AdvancedHousingPrediction/KaggleAdvancedHousingPrediction.ipynb | jaabberwocky/jaabberwocky.github.io | mit |
One way to handle this is to drop the first 4, given that almost all observations are missing. | drop_cols = ['PoolQC','MiscFeature','Alley','Fence']
# write custom transformer to drop these 4 cols for use in Pipeline later
from sklearn.base import BaseEstimator, TransformerMixin
def DropColumnsTransform(BaseEstimator, TransformerMixin):
def __init__(self, attribs_drop):
self.attribs_drop = attribs_drop
def fit(self, X):
return self
def transform(self, X):
return X.drop(self.attribs_drop, axis=1).values
# look at categorical data
train_cat = train.select_dtypes(include=['object'])
train_cat.shape
# use this to impute missing values as "?"
train_cat = train_cat.fillna("?")
print("43/%d or %.2f%% of columns are categorical" % (train.shape[1], 43/train.shape[1]*100))
from sklearn.preprocessing import LabelBinarizer, Imputer
LabelBinarizer = LabelBinarizer()
# loop to apply LB to each column individually, then combine them back together
list_cols = []
for col in list(train_cat.columns):
x = train_cat[col].values
x_trans = LabelBinarizer.fit_transform(x)
list_cols.append(x_trans)
train_cat_transformed = np.concatenate(list_cols,axis=1)
train_cat_transformed
# numerical data now
Imp = Imputer(strategy="median")
train_num = train.select_dtypes(include=['number'])
train_num.shape
# look at correlation
cor = train_num.corr()
f = plt.figure(figsize=(15,15))
sns.heatmap(cor, cmap='plasma') | Python/Machine Learning/Kaggle/AdvancedHousingPrediction/KaggleAdvancedHousingPrediction.ipynb | jaabberwocky/jaabberwocky.github.io | mit |
Many features (e.g. LotArea, GarageCars) are indeed correlated highly with SalePrice. | tmp = cor['SalePrice'].sort_values(ascending=False)
tmp[1:11].plot(kind='bar', figsize=(8,8))
# we will have to remove SalePrice before imputing
train_num_wsp = train_num.drop('SalePrice',axis=1)
train_num_tr = Imp.fit_transform(train_num_wsp)
train_num_tr
X = np.concatenate([train_num_tr, train_cat_transformed],axis=1)
y = train_num['SalePrice'].values
print("Shape of X:", X.shape)
print("Shape of y:", y.shape) | Python/Machine Learning/Kaggle/AdvancedHousingPrediction/KaggleAdvancedHousingPrediction.ipynb | jaabberwocky/jaabberwocky.github.io | mit |
Fit Models
Linear Regression
RandomForest | from sklearn.model_selection import train_test_split
# split into 10% for validation at end
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.1)
# Linear Regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_error as mse
linreg = LinearRegression()
scores = cross_val_score(linreg, X_train, y_train, scoring="neg_mean_squared_error", cv=10, verbose=1)
def printscorespretty(scores):
sc = np.sqrt(-scores)
print("Scores:", sc)
print("Mean:", np.mean(sc))
print("SD:", np.sqrt(np.var(sc)))
printscorespretty(scores)
#Decision Tree Regressor
from sklearn.tree import DecisionTreeRegressor
dtr = DecisionTreeRegressor()
scores = cross_val_score(dtr, X_train, y_train, scoring="neg_mean_squared_error", cv=10, verbose=1)
printscorespretty(scores) | Python/Machine Learning/Kaggle/AdvancedHousingPrediction/KaggleAdvancedHousingPrediction.ipynb | jaabberwocky/jaabberwocky.github.io | mit |
DecisionTree Regressor is performing much better than Linear Regression here, perhaps capturing some non-linearity in data. | from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor()
scores = cross_val_score(rf, X_train, y_train, scoring="neg_mean_squared_error", cv=10, verbose=1)
printscorespretty(scores) | Python/Machine Learning/Kaggle/AdvancedHousingPrediction/KaggleAdvancedHousingPrediction.ipynb | jaabberwocky/jaabberwocky.github.io | mit |
Best performance thus far is from RF. | # XGBoost
from xgboost import XGBRegressor
XGB = XGBRegressor()
scores = cross_val_score(XGB, X_train, y_train, scoring="neg_mean_squared_error", cv=10, verbose=1)
printscorespretty(scores) | Python/Machine Learning/Kaggle/AdvancedHousingPrediction/KaggleAdvancedHousingPrediction.ipynb | jaabberwocky/jaabberwocky.github.io | mit |
# Travail préalable : Hello World
Objectif de formation : Exécuter un programme TensorFlow dans le navigateur.
Voici un programme TensorFlow "Hello World" : | from __future__ import print_function
import tensorflow as tf
c = tf.constant('Hello, world!')
with tf.Session() as sess:
print(sess.run(c)) | ml/cc/prework/fr/hello_world.ipynb | google/eng-edu | apache-2.0 |
On Windows: multiprocessing spawns with subprocess.Popen | if __name__ == '__main__':
from multiprocessing import freeze_support
freeze_support()
# Then, do multiprocessing stuff... | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Data parallelism versus task parallelism
Multithreading versus multiple threads
The global interpreter lock
Processes versus threads
Shared memory and shared objects
Shared objects: Value and Array | %%file sharedobj.py
'''demonstrate shared objects in multiprocessing
'''
from multiprocessing import Process, Value, Array
def f(n, a):
n.value = 3.1415927
for i in range(len(a)):
a[i] = -a[i]
if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10))
p = Process(target=f, args=(num, arr))
p.start()
p.join()
print num.value
print arr[:]
# EOF
!python2.7 sharedobj.py | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Manager and proxies | %%file sharedproxy.py
'''demonstrate sharing objects by proxy through a manager
'''
from multiprocessing import Process, Manager
def f(d, l):
d[1] = '1'
d['2'] = 2
d[0.25] = None
l.reverse()
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
l = manager.list(range(10))
p = Process(target=f, args=(d, l))
p.start()
p.join()
print d
print l
# EOF
!python2.7 sharedproxy.py | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
See: https://docs.python.org/2/library/multiprocessing.html
Working in C with ctypes and numpy | %%file numpyshared.py
'''demonstrating shared objects using numpy and ctypes
'''
import multiprocessing as mp
from multiprocessing import sharedctypes
from numpy import ctypeslib
def fill_arr(arr_view, i):
arr_view.fill(i)
if __name__ == '__main__':
ra = sharedctypes.RawArray('i', 4)
arr = ctypeslib.as_array(ra)
arr.shape = (2, 2)
p1 = mp.Process(target=fill_arr, args=(arr[:1, :], 1))
p2 = mp.Process(target=fill_arr, args=(arr[1:, :], 2))
p1.start(); p2.start()
p1.join(); p2.join()
print arr
!python2.7 numpyshared.py | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Issues: threading and locks
Low-level task parallelism: point to point communication
Process | %%file mprocess.py
'''demonstrate the process claas
'''
import multiprocessing as mp
from time import sleep
from random import random
def worker(num):
sleep(2.0 * random())
name = mp.current_process().name
print "worker {},name:{}".format(num, name)
if __name__ == '__main__':
master = mp.current_process().name
print "Master name: {}".format(master)
for i in range(2):
p = mp.Process(target=worker, args=(i,))
p.start()
# Close all child processes spawn
[p.join() for p in mp.active_children()]
!python2.7 mprocess.py | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Queue and Pipe | %%file queuepipe.py
'''demonstrate queues and pipes
'''
import multiprocessing as mp
import pickle
def qworker(q):
v = q.get() # blocking!
print "queue worker got '{}' from parent".format(v)
def pworker(p):
import pickle # needed for encapsulation
msg = 'hello hello hello'
print "pipe worker sending {!r} to parent".format(msg)
p.send(msg)
v = p.recv()
print "pipe worker got {!r} from parent".format(v)
print "unpickled to {}".format(pickle.loads(v))
if __name__ == '__main__':
q = mp.Queue()
p = mp.Process(target=qworker, args=(q,))
p.start() # blocks at q.get()
v = 'python rocks!'
print "putting '{}' on queue".format(v)
q.put(v)
p.join()
print ''
# The two ends of the pipe: the parent and the child connections
p_conn, c_conn = mp.Pipe()
p = mp.Process(target=pworker, args=(c_conn,))
p.start()
msg = pickle.dumps([1,2,3],-1)
print "got {!r} from child".format(p_conn.recv())
print "sending {!r} to child".format(msg)
p_conn.send(msg)
import datetime
print "\nfinished: {}".format(datetime.date.today())
p.join()
!python2.7 queuepipe.py | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Synchronization with Lock and Event | %%file multi_sync.py
'''demonstrating locks
'''
import multiprocessing as mp
def print_lock(lk, i):
name = mp.current_process().name
lk.acquire()
for j in range(5):
print i, "from process", name
lk.release()
if __name__ == '__main__':
lk = mp.Lock()
ps = [mp.Process(target=print_lock, args=(lk,i)) for i in range(5)]
[p.start() for p in ps]
[p.join() for p in ps]
!python2.7 multi_sync.py
'''events
'''
import multiprocessing as mp
def wait_on_event(e):
name = mp.current_process().name
e.wait()
print name, "finished waiting"
if __name__ == '__main__':
e = mp.Event()
ps = [mp.Process(target=wait_on_event, args=(e,)) for i in range(10)]
[p.start() for p in ps]
print "e.is_set()", e.is_set()
#raw_input("press any key to set event")
e.set()
[p.join() for p in ps] | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
High-level task parallelism: collective communication
The task Pool
pipes (apply) and map | import multiprocessing as mp
def random_mean(x):
import numpy as np
return round(np.mean(np.random.randint(-x,x+1,10000)), 3)
if __name__ == '__main__':
# create a pool with cpu_count() procsesses
p = mp.Pool()
results = p.map(random_mean, range(1,10))
print results
print p.apply(random_mean, [100])
p.close()
p.join() | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Variants: blocking, iterative, unordered, and asynchronous | import multiprocessing as mp
def random_mean_count(x):
import numpy as np
return x + round(np.mean(np.random.randint(-x,x+1,10000)), 3)
if __name__ == '__main__':
# create a pool with cpu_count() procsesses
p = mp.Pool()
results = p.imap_unordered(random_mean_count, range(1,10))
print "[",
for i in results:
print i,
if abs(i) <= 1.0:
print "...] QUIT"
break
list(results)
p.close()
p.join()
import multiprocessing as mp
def random_mean_count(x):
import numpy as np
return x + round(np.mean(np.random.randint(-x,x+1,10000)), 3)
if __name__ == '__main__':
# create a pool with cpu_count() procsesses
p = mp.Pool()
results = p.map_async(random_mean_count, range(1,10))
print "Waiting .",
i = 0
while not results.ready():
if not i%4000:
print ".",
i += 1
print results.get()
print "\n", p.apply_async(random_mean_count, [100]).get()
p.close()
p.join() | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Issues: random number generators | import numpy as np
def walk(x, n=100, box=.5, delta=.2):
"perform a random walk"
w = np.cumsum(x + np.random.uniform(-delta,delta,n))
w = np.where(abs(w) > box)[0]
return w[0] if len(w) else n
N = 10
# run N trials, all starting from x=0
pwalk = np.vectorize(walk)
print pwalk(np.zeros(N))
# run again, using list comprehension instead of ufunc
print [walk(0) for i in range(N)]
# run again, using multiprocessing's map
import multiprocessing as mp
p = mp.Pool()
print p.map(walk, [0]*N)
%%file state.py
"""some good state utilities
"""
def check_pickle(x, dill=False):
"checks the pickle across a subprocess"
import pickle
import subprocess
if dill:
import dill as pickle
pik = "dill"
else:
pik = "pickle"
fail = True
try:
_x = pickle.dumps(x)
fail = False
finally:
if fail:
print "DUMP FAILED"
msg = "python -c import {0}; print {0}.loads({1})".format(pik,repr(_x))
print "SUCCESS" if not subprocess.call(msg.split(None,2)) else "LOAD FAILED"
def random_seed(s=None):
"sets the seed for calls to 'random()'"
import random
random.seed(s)
try:
from numpy import random
random.seed(s)
except:
pass
return
def random_state(module='random', new=False, seed='!'):
"""return a (optionally manually seeded) random generator
For a given module, return an object that has random number generation (RNG)
methods available. If new=False, use the global copy of the RNG object.
If seed='!', do not reseed the RNG (using seed=None 'removes' any seeding).
If seed='*', use a seed that depends on the process id (PID); this is useful
for building RNGs that are different across multiple threads or processes.
"""
import random
if module == 'random':
rng = random
elif not isinstance(module, type(random)):
# convienence for passing in 'numpy'
if module == 'numpy': module = 'numpy.random'
try:
import importlib
rng = importlib.import_module(module)
except ImportError:
rng = __import__(module, fromlist=module.split('.')[-1:])
elif module.__name__ == 'numpy': # convienence for passing in numpy
from numpy import random as rng
else: rng = module
_rng = getattr(rng, 'RandomState', None) or \
getattr(rng, 'Random') # throw error if no rng found
if new:
rng = _rng()
if seed == '!': # special case: don't reset the seed
return rng
if seed == '*': # special case: random seeding for multiprocessing
try:
try:
import multiprocessing as mp
except ImportError:
import processing as mp
try:
seed = mp.current_process().pid
except AttributeError:
seed = mp.currentProcess().getPid()
except:
seed = 0
import time
seed += int(time.time()*1e6)
# set the random seed (or 'reset' with None)
rng.seed(seed)
return rng
# EOF | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Issues: serialization
Better serialization: multiprocess | import multiprocess
print multiprocess.Pool().map(lambda x:x**2, range(10)) | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
EXERCISE: << Either the mystic multi-solve or one of the pathos tests or with rng >>
Code-based versus object-based serialization: pp(ft) | %%file runppft.py
'''demonstrate ppft
'''
import ppft
def squared(x):
return x*x
server = ppft.Server() # can take 'localhost:8000' or remote:port
result = server.submit(squared, (5,))
result.wait()
print result.finished
print result()
!python2.7 runppft.py | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Programming efficiency: pathos
Multi-argument map functions
Unified API for threading, multiprocessing, and serial and parallel python (pp) | %%file allpool.py
'''demonstrate pool API
'''
import pathos
def sum_squared(x,y):
return (x+y)**2
x = range(5)
y = range(0,10,2)
if __name__ == '__main__':
sp = pathos.pools.SerialPool()
pp = pathos.pools.ParallelPool()
mp = pathos.pools.ProcessPool()
tp = pathos.pools.ThreadPool()
for pool in [sp,pp,mp,tp]:
print pool.map(sum_squared, x, y)
pool.close()
pool.join()
!python2.7 allpool.py | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Strives for natural programming constructs in parallel code | from itertools import izip
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
import math
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def sleep_add1(x):
from time import sleep
if x < 4: sleep(x/10.0)
return x+1
def sleep_add2(x):
from time import sleep
if x < 4: sleep(x/10.0)
return x+2
def test_with_multipool(Pool):
inputs = range(10)
with Pool() as pool1:
res1 = pool1.amap(sleep_add1, inputs)
with Pool() as pool2:
res2 = pool2.amap(sleep_add2, inputs)
with Pool() as pool3:
for number, prime in izip(PRIMES, pool3.imap(is_prime, PRIMES)):
assert prime if number != PRIMES[-1] else not prime
assert res1.get() == [i+1 for i in inputs]
assert res2.get() == [i+2 for i in inputs]
print "OK"
if __name__ == '__main__':
from pathos.pools import ProcessPool
test_with_multipool(ProcessPool) | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Programming models and hierarchical computing | import pathos
from math import sin, cos
if __name__ == '__main__':
mp = pathos.pools.ProcessPool()
tp = pathos.pools.ThreadPool()
print mp.amap(tp.map, [sin, cos], [range(3),range(3)]).get()
mp.close(); tp.close()
mp.join(); tp.join() | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Pool caching
Not covered: IPython.parallel and scoop
EXERCISE: Let's take another swing at Monte Carlo betting. You'll want to focus on roll.py, trials.py and optimize.py. Can you speed things up with careful placement of a Pool? Are there small modifications to the code that would allow hierarchical parallelism? Can we speed up the calculation, or does parallel computing lose to spin-up overhead? Where are we now hitting the wall?
See: 'solution'
Remote execution
Easy: the pp.Server
Even easier: Pool().server in pathos
Not covered: rpyc, pyro, and zmq
Related: secure authentication with ssh
pathos.secure: connection and tunnel | import pathos
import sys
rhost = 'localhost'
rport = 23
if __name__ == '__main__':
tunnel = pathos.secure.Tunnel()
lport = tunnel.connect(rhost, rport)
print 'SSH Tunnel to:', rhost
print 'Remote port:', rport
print 'Local port:', lport
print 'Press <Enter> to disconnect'
sys.stdin.readline()
tunnel.disconnect() | multiprocessing.ipynb | jiumem/tuthpc | bsd-3-clause |
Getting the data ready
We will be using the same LendingClub dataset as in the previous assignment. | loans = graphlab.SFrame('lending-club-data.gl/') | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Extracting the target and the feature columns
We will now repeat some of the feature processing steps that we saw in the previous assignment:
First, we re-assign the target to have +1 as a safe (good) loan, and -1 as a risky (bad) loan.
Next, we select four categorical features:
1. grade of the loan
2. the length of the loan term
3. the home ownership status: own, mortgage, rent
4. number of years of employment. | features = ['grade', # grade of the loan
'term', # the term of the loan
'home_ownership', # home ownership status: own, mortgage or rent
'emp_length', # number of years of employment
]
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans.remove_column('bad_loans')
target = 'safe_loans'
loans = loans[features + [target]] | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Subsample dataset to make sure classes are balanced
Just as we did in the previous assignment, we will undersample the larger class (safe loans) in order to balance out our dataset. This means we are throwing away many data points. We use seed=1 so everyone gets the same results. | safe_loans_raw = loans[loans[target] == 1]
risky_loans_raw = loans[loans[target] == -1]
# Undersample the safe loans.
percentage = len(risky_loans_raw)/float(len(safe_loans_raw))
risky_loans = risky_loans_raw
safe_loans = safe_loans_raw.sample(percentage, seed=1)
loans_data = risky_loans_raw.append(safe_loans)
print "Percentage of safe loans :", len(safe_loans) / float(len(loans_data))
print "Percentage of risky loans :", len(risky_loans) / float(len(loans_data))
print "Total number of loans in our new dataset :", len(loans_data) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Note: There are many approaches for dealing with imbalanced data, including some where we modify the learning algorithm. These approaches are beyond the scope of this course, but some of them are reviewed in this paper. For this assignment, we use the simplest possible approach, where we subsample the overly represented class to get a more balanced dataset. In general, and especially when the data is highly imbalanced, we recommend using more advanced methods.
Transform categorical data into binary features
In this assignment, we will work with binary decision trees. Since all of our features are currently categorical features, we want to turn them into binary features using 1-hot encoding.
We can do so with the following code block (see the first assignments for more details): | loans_data = risky_loans.append(safe_loans)
for feature in features:
loans_data_one_hot_encoded = loans_data[feature].apply(lambda x: {x: 1})
loans_data_unpacked = loans_data_one_hot_encoded.unpack(column_name_prefix=feature)
# Change None's to 0's
for column in loans_data_unpacked.column_names():
loans_data_unpacked[column] = loans_data_unpacked[column].fillna(0)
loans_data.remove_column(feature)
loans_data.add_columns(loans_data_unpacked) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Let's see what the feature columns look like now: | features = loans_data.column_names()
features.remove('safe_loans') # Remove the response variable
features | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Train-test split
We split the data into training and test sets with 80% of the data in the training set and 20% of the data in the test set. We use seed=1 so that everyone gets the same result. | train_data, test_data = loans_data.random_split(0.8, seed=1) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Weighted decision trees
Let's modify our decision tree code from Module 5 to support weighting of individual data points.
Weighted error definition
Consider a model with $N$ data points with:
* Predictions $\hat{y}_1 ... \hat{y}_n$
* Target $y_1 ... y_n$
* Data point weights $\alpha_1 ... \alpha_n$.
Then the weighted error is defined by:
$$
\mathrm{E}(\mathbf{\alpha}, \mathbf{\hat{y}}) = \frac{\sum_{i=1}^{n} \alpha_i \times 1[y_i \neq \hat{y_i}]}{\sum_{i=1}^{n} \alpha_i}
$$
where $1[y_i \neq \hat{y_i}]$ is an indicator function that is set to $1$ if $y_i \neq \hat{y_i}$.
Write a function to compute weight of mistakes
Write a function that calculates the weight of mistakes for making the "weighted-majority" predictions for a dataset. The function accepts two inputs:
* labels_in_node: Targets $y_1 ... y_n$
* data_weights: Data point weights $\alpha_1 ... \alpha_n$
We are interested in computing the (total) weight of mistakes, i.e.
$$
\mathrm{WM}(\mathbf{\alpha}, \mathbf{\hat{y}}) = \sum_{i=1}^{n} \alpha_i \times 1[y_i \neq \hat{y_i}].
$$
This quantity is analogous to the number of mistakes, except that each mistake now carries different weight. It is related to the weighted error in the following way:
$$
\mathrm{E}(\mathbf{\alpha}, \mathbf{\hat{y}}) = \frac{\mathrm{WM}(\mathbf{\alpha}, \mathbf{\hat{y}})}{\sum_{i=1}^{n} \alpha_i}
$$
The function intermediate_node_weighted_mistakes should first compute two weights:
* $\mathrm{WM}{-1}$: weight of mistakes when all predictions are $\hat{y}_i = -1$ i.e $\mathrm{WM}(\mathbf{\alpha}, \mathbf{-1}$)
* $\mathrm{WM}{+1}$: weight of mistakes when all predictions are $\hat{y}_i = +1$ i.e $\mbox{WM}(\mathbf{\alpha}, \mathbf{+1}$)
where $\mathbf{-1}$ and $\mathbf{+1}$ are vectors where all values are -1 and +1 respectively.
After computing $\mathrm{WM}{-1}$ and $\mathrm{WM}{+1}$, the function intermediate_node_weighted_mistakes should return the lower of the two weights of mistakes, along with the class associated with that weight. We have provided a skeleton for you with YOUR CODE HERE to be filled in several places. | def intermediate_node_weighted_mistakes(labels_in_node, data_weights):
# Sum the weights of all entries with label +1
total_weight_positive = sum(data_weights[labels_in_node == +1])
# Weight of mistakes for predicting all -1's is equal to the sum above
### YOUR CODE HERE
weighted_mistakes_all_negative = total_weight_positive
# Sum the weights of all entries with label -1
### YOUR CODE HERE
total_weight_negative = sum(data_weights[labels_in_node == -1])
# Weight of mistakes for predicting all +1's is equal to the sum above
### YOUR CODE HERE
weighted_mistakes_all_positive = total_weight_negative
# Return the tuple (weight, class_label) representing the lower of the two weights
# class_label should be an integer of value +1 or -1.
# If the two weights are identical, return (weighted_mistakes_all_positive,+1)
### YOUR CODE HERE
if weighted_mistakes_all_positive <= weighted_mistakes_all_negative:
return weighted_mistakes_all_positive, +1
else:
return weighted_mistakes_all_negative, -1 | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Checkpoint: Test your intermediate_node_weighted_mistakes function, run the following cell: | example_labels = graphlab.SArray([-1, -1, 1, 1, 1])
example_data_weights = graphlab.SArray([1., 2., .5, 1., 1.])
if intermediate_node_weighted_mistakes(example_labels, example_data_weights) == (2.5, -1):
print 'Test passed!'
else:
print 'Test failed... try again!' | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Recall that the classification error is defined as follows:
$$
\mbox{classification error} = \frac{\mbox{# mistakes}}{\mbox{# all data points}}
$$
Quiz Question: If we set the weights $\mathbf{\alpha} = 1$ for all data points, how is the weight of mistakes $\mbox{WM}(\mathbf{\alpha}, \mathbf{\hat{y}})$ related to the classification error?
Function to pick best feature to split on
We continue modifying our decision tree code from the earlier assignment to incorporate weighting of individual data points. The next step is to pick the best feature to split on.
The best_splitting_feature function is similar to the one from the earlier assignment with two minor modifications:
1. The function best_splitting_feature should now accept an extra parameter data_weights to take account of weights of data points.
2. Instead of computing the number of mistakes in the left and right side of the split, we compute the weight of mistakes for both sides, add up the two weights, and divide it by the total weight of the data.
Complete the following function. Comments starting with DIFFERENT HERE mark the sections where the weighted version differs from the original implementation. | # If the data is identical in each feature, this function should return None
def best_splitting_feature(data, features, target, data_weights):
print data_weights
# These variables will keep track of the best feature and the corresponding error
best_feature = None
best_error = float('+inf')
num_points = float(len(data))
# Loop through each feature to consider splitting on that feature
for feature in features:
# The left split will have all data points where the feature value is 0
# The right split will have all data points where the feature value is 1
left_split = data[data[feature] == 0]
right_split = data[data[feature] == 1]
# Apply the same filtering to data_weights to create left_data_weights, right_data_weights
## YOUR CODE HERE
left_data_weights = data_weights[data[feature] == 0]
right_data_weights = data_weights[data[feature] == 1]
# DIFFERENT HERE
# Calculate the weight of mistakes for left and right sides
## YOUR CODE HERE
left_weighted_mistakes, left_class = intermediate_node_weighted_mistakes(left_split[target], left_data_weights)
right_weighted_mistakes, right_class = intermediate_node_weighted_mistakes(right_split[target], right_data_weights)
# DIFFERENT HERE
# Compute weighted error by computing
# ( [weight of mistakes (left)] + [weight of mistakes (right)] ) / [total weight of all data points]
## YOUR CODE HERE
error = (left_weighted_mistakes + right_weighted_mistakes) / (sum(left_data_weights) + sum(right_data_weights))
# If this is the best error we have found so far, store the feature and the error
if error < best_error:
best_feature = feature
best_error = error
# Return the best feature we found
return best_feature | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Checkpoint: Now, we have another checkpoint to make sure you are on the right track. | example_data_weights = graphlab.SArray(len(train_data)* [1.5])
if best_splitting_feature(train_data, features, target, example_data_weights) == 'term. 36 months':
print 'Test passed!'
else:
print 'Test failed... try again!' | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Note. If you get an exception in the line of "the logical filter has different size than the array", try upgradting your GraphLab Create installation to 1.8.3 or newer.
Very Optional. Relationship between weighted error and weight of mistakes
By definition, the weighted error is the weight of mistakes divided by the weight of all data points, so
$$
\mathrm{E}(\mathbf{\alpha}, \mathbf{\hat{y}}) = \frac{\sum_{i=1}^{n} \alpha_i \times 1[y_i \neq \hat{y_i}]}{\sum_{i=1}^{n} \alpha_i} = \frac{\mathrm{WM}(\mathbf{\alpha}, \mathbf{\hat{y}})}{\sum_{i=1}^{n} \alpha_i}.
$$
In the code above, we obtain $\mathrm{E}(\mathbf{\alpha}, \mathbf{\hat{y}})$ from the two weights of mistakes from both sides, $\mathrm{WM}(\mathbf{\alpha}{\mathrm{left}}, \mathbf{\hat{y}}{\mathrm{left}})$ and $\mathrm{WM}(\mathbf{\alpha}{\mathrm{right}}, \mathbf{\hat{y}}{\mathrm{right}})$. First, notice that the overall weight of mistakes $\mathrm{WM}(\mathbf{\alpha}, \mathbf{\hat{y}})$ can be broken into two weights of mistakes over either side of the split:
$$
\mathrm{WM}(\mathbf{\alpha}, \mathbf{\hat{y}})
= \sum_{i=1}^{n} \alpha_i \times 1[y_i \neq \hat{y_i}]
= \sum_{\mathrm{left}} \alpha_i \times 1[y_i \neq \hat{y_i}]
+ \sum_{\mathrm{right}} \alpha_i \times 1[y_i \neq \hat{y_i}]\
= \mathrm{WM}(\mathbf{\alpha}{\mathrm{left}}, \mathbf{\hat{y}}{\mathrm{left}}) + \mathrm{WM}(\mathbf{\alpha}{\mathrm{right}}, \mathbf{\hat{y}}{\mathrm{right}})
$$
We then divide through by the total weight of all data points to obtain $\mathrm{E}(\mathbf{\alpha}, \mathbf{\hat{y}})$:
$$
\mathrm{E}(\mathbf{\alpha}, \mathbf{\hat{y}})
= \frac{\mathrm{WM}(\mathbf{\alpha}{\mathrm{left}}, \mathbf{\hat{y}}{\mathrm{left}}) + \mathrm{WM}(\mathbf{\alpha}{\mathrm{right}}, \mathbf{\hat{y}}{\mathrm{right}})}{\sum_{i=1}^{n} \alpha_i}
$$
Building the tree
With the above functions implemented correctly, we are now ready to build our decision tree. Recall from the previous assignments that each node in the decision tree is represented as a dictionary which contains the following keys:
{
'is_leaf' : True/False.
'prediction' : Prediction at the leaf node.
'left' : (dictionary corresponding to the left tree).
'right' : (dictionary corresponding to the right tree).
'features_remaining' : List of features that are posible splits.
}
Let us start with a function that creates a leaf node given a set of target values: | def create_leaf(target_values, data_weights):
# Create a leaf node
leaf = {'splitting_feature' : None,
'is_leaf': True}
# Computed weight of mistakes.
weighted_error, best_class = intermediate_node_weighted_mistakes(target_values, data_weights)
# Store the predicted class (1 or -1) in leaf['prediction']
leaf['prediction'] = best_class ## YOUR CODE HERE
return leaf | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
We provide a function that learns a weighted decision tree recursively and implements 3 stopping conditions:
1. All data points in a node are from the same class.
2. No more features to split on.
3. Stop growing the tree when the tree depth reaches max_depth. | def weighted_decision_tree_create(data, features, target, data_weights, current_depth = 1, max_depth = 10):
remaining_features = features[:] # Make a copy of the features.
target_values = data[target]
print "--------------------------------------------------------------------"
print "Subtree, depth = %s (%s data points)." % (current_depth, len(target_values))
# Stopping condition 1. Error is 0.
if intermediate_node_weighted_mistakes(target_values, data_weights)[0] <= 1e-15:
print "Stopping condition 1 reached."
return create_leaf(target_values, data_weights)
# Stopping condition 2. No more features.
if remaining_features == []:
print "Stopping condition 2 reached."
return create_leaf(target_values, data_weights)
# Additional stopping condition (limit tree depth)
if current_depth > max_depth:
print "Reached maximum depth. Stopping for now."
return create_leaf(target_values, data_weights)
# If all the datapoints are the same, splitting_feature will be None. Create a leaf
splitting_feature = best_splitting_feature(data, features, target, data_weights)
remaining_features.remove(splitting_feature)
left_split = data[data[splitting_feature] == 0]
right_split = data[data[splitting_feature] == 1]
left_data_weights = data_weights[data[splitting_feature] == 0]
right_data_weights = data_weights[data[splitting_feature] == 1]
print "Split on feature %s. (%s, %s)" % (\
splitting_feature, len(left_split), len(right_split))
# Create a leaf node if the split is "perfect"
if len(left_split) == len(data):
print "Creating leaf node."
return create_leaf(left_split[target], data_weights)
if len(right_split) == len(data):
print "Creating leaf node."
return create_leaf(right_split[target], data_weights)
# Repeat (recurse) on left and right subtrees
left_tree = weighted_decision_tree_create(
left_split, remaining_features, target, left_data_weights, current_depth + 1, max_depth)
right_tree = weighted_decision_tree_create(
right_split, remaining_features, target, right_data_weights, current_depth + 1, max_depth)
return {'is_leaf' : False,
'prediction' : None,
'splitting_feature': splitting_feature,
'left' : left_tree,
'right' : right_tree} | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Here is a recursive function to count the nodes in your tree: | def count_nodes(tree):
if tree['is_leaf']:
return 1
return 1 + count_nodes(tree['left']) + count_nodes(tree['right']) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Run the following test code to check your implementation. Make sure you get 'Test passed' before proceeding. | example_data_weights = graphlab.SArray([1.0 for i in range(len(train_data))])
small_data_decision_tree = weighted_decision_tree_create(train_data, features, target,
example_data_weights, max_depth=2)
if count_nodes(small_data_decision_tree) == 7:
print 'Test passed!'
else:
print 'Test failed... try again!'
print 'Number of nodes found:', count_nodes(small_data_decision_tree)
print 'Number of nodes that should be there: 7' | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Let us take a quick look at what the trained tree is like. You should get something that looks like the following
{'is_leaf': False,
'left': {'is_leaf': False,
'left': {'is_leaf': True, 'prediction': -1, 'splitting_feature': None},
'prediction': None,
'right': {'is_leaf': True, 'prediction': 1, 'splitting_feature': None},
'splitting_feature': 'grade.A'
},
'prediction': None,
'right': {'is_leaf': False,
'left': {'is_leaf': True, 'prediction': 1, 'splitting_feature': None},
'prediction': None,
'right': {'is_leaf': True, 'prediction': -1, 'splitting_feature': None},
'splitting_feature': 'grade.D'
},
'splitting_feature': 'term. 36 months'
} | small_data_decision_tree | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Making predictions with a weighted decision tree
We give you a function that classifies one data point. It can also return the probability if you want to play around with that as well. | def classify(tree, x, annotate = False):
# If the node is a leaf node.
if tree['is_leaf']:
if annotate:
print "At leaf, predicting %s" % tree['prediction']
return tree['prediction']
else:
# Split on feature.
split_feature_value = x[tree['splitting_feature']]
if annotate:
print "Split on %s = %s" % (tree['splitting_feature'], split_feature_value)
if split_feature_value == 0:
return classify(tree['left'], x, annotate)
else:
return classify(tree['right'], x, annotate) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Evaluating the tree
Now, we will write a function to evaluate a decision tree by computing the classification error of the tree on the given dataset.
Again, recall that the classification error is defined as follows:
$$
\mbox{classification error} = \frac{\mbox{# mistakes}}{\mbox{# all data points}}
$$
The function called evaluate_classification_error takes in as input:
1. tree (as described above)
2. data (an SFrame)
The function does not change because of adding data point weights. | def evaluate_classification_error(tree, data):
# Apply the classify(tree, x) to each row in your data
prediction = data.apply(lambda x: classify(tree, x))
# Once you've made the predictions, calculate the classification error
return (prediction != data[target]).sum() / float(len(data))
evaluate_classification_error(small_data_decision_tree, test_data) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Example: Training a weighted decision tree
To build intuition on how weighted data points affect the tree being built, consider the following:
Suppose we only care about making good predictions for the first 10 and last 10 items in train_data, we assign weights:
* 1 to the last 10 items
* 1 to the first 10 items
* and 0 to the rest.
Let us fit a weighted decision tree with max_depth = 2. | # Assign weights
example_data_weights = graphlab.SArray([1.] * 10 + [0.]*(len(train_data) - 20) + [1.] * 10)
# Train a weighted decision tree model.
small_data_decision_tree_subset_20 = weighted_decision_tree_create(train_data, features, target,
example_data_weights, max_depth=2) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Now, we will compute the classification error on the subset_20, i.e. the subset of data points whose weight is 1 (namely the first and last 10 data points). | subset_20 = train_data.head(10).append(train_data.tail(10))
evaluate_classification_error(small_data_decision_tree_subset_20, subset_20) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Now, let us compare the classification error of the model small_data_decision_tree_subset_20 on the entire test set train_data: | evaluate_classification_error(small_data_decision_tree_subset_20, train_data) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
The model small_data_decision_tree_subset_20 performs a lot better on subset_20 than on train_data.
So, what does this mean?
* The points with higher weights are the ones that are more important during the training process of the weighted decision tree.
* The points with zero weights are basically ignored during training.
Quiz Question: Will you get the same model as small_data_decision_tree_subset_20 if you trained a decision tree with only the 20 data points with non-zero weights from the set of points in subset_20?
Implementing your own Adaboost (on decision stumps)
Now that we have a weighted decision tree working, it takes only a bit of work to implement Adaboost. For the sake of simplicity, let us stick with decision tree stumps by training trees with max_depth=1.
Recall from the lecture the procedure for Adaboost:
1. Start with unweighted data with $\alpha_j = 1$
2. For t = 1,...T:
* Learn $f_t(x)$ with data weights $\alpha_j$
* Compute coefficient $\hat{w}t$:
$$\hat{w}_t = \frac{1}{2}\ln{\left(\frac{1- \mbox{E}(\mathbf{\alpha}, \mathbf{\hat{y}})}{\mbox{E}(\mathbf{\alpha}, \mathbf{\hat{y}})}\right)}$$
* Re-compute weights $\alpha_j$:
$$\alpha_j \gets \begin{cases}
\alpha_j \exp{(-\hat{w}_t)} & \text{ if }f_t(x_j) = y_j\
\alpha_j \exp{(\hat{w}_t)} & \text{ if }f_t(x_j) \neq y_j
\end{cases}$$
* Normalize weights $\alpha_j$:
$$\alpha_j \gets \frac{\alpha_j}{\sum{i=1}^{N}{\alpha_i}} $$
Complete the skeleton for the following code to implement adaboost_with_tree_stumps. Fill in the places with YOUR CODE HERE. | from math import log
from math import exp
def adaboost_with_tree_stumps(data, features, target, num_tree_stumps):
# start with unweighted data
alpha = graphlab.SArray([1.]*len(data))
weights = []
tree_stumps = []
target_values = data[target]
for t in xrange(num_tree_stumps):
print '====================================================='
print 'Adaboost Iteration %d' % t
print '====================================================='
# Learn a weighted decision tree stump. Use max_depth=1
tree_stump = weighted_decision_tree_create(data, features, target, data_weights=alpha, max_depth=1)
tree_stumps.append(tree_stump)
# Make predictions
predictions = data.apply(lambda x: classify(tree_stump, x))
# Produce a Boolean array indicating whether
# each data point was correctly classified
is_correct = predictions == target_values
is_wrong = predictions != target_values
# Compute weighted error
# YOUR CODE HERE
weighted_error = sum(alpha * is_wrong) / sum(alpha)
# Compute model coefficient using weighted error
# YOUR CODE HERE
weight = .5 * log((1 - weighted_error) / weighted_error)
weights.append(weight)
# Adjust weights on data point
adjustment = is_correct.apply(lambda is_correct : exp(-weight) if is_correct else exp(weight))
# Scale alpha by multiplying by adjustment
# Then normalize data points weights
## YOUR CODE HERE
alpha *= adjustment
alpha /= sum(alpha)
return weights, tree_stumps | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Checking your Adaboost code
Train an ensemble of two tree stumps and see which features those stumps split on. We will run the algorithm with the following parameters:
* train_data
* features
* target
* num_tree_stumps = 2 | stump_weights, tree_stumps = adaboost_with_tree_stumps(train_data, features, target, num_tree_stumps=2)
def print_stump(tree):
split_name = tree['splitting_feature'] # split_name is something like 'term. 36 months'
if split_name is None:
print "(leaf, label: %s)" % tree['prediction']
return None
split_feature, split_value = split_name.split('.')
print ' root'
print ' |---------------|----------------|'
print ' | |'
print ' | |'
print ' | |'
print ' [{0} == 0]{1}[{0} == 1] '.format(split_name, ' '*(27-len(split_name)))
print ' | |'
print ' | |'
print ' | |'
print ' (%s) (%s)' \
% (('leaf, label: ' + str(tree['left']['prediction']) if tree['left']['is_leaf'] else 'subtree'),
('leaf, label: ' + str(tree['right']['prediction']) if tree['right']['is_leaf'] else 'subtree')) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Here is what the first stump looks like: | print_stump(tree_stumps[0]) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Here is what the next stump looks like: | print_stump(tree_stumps[1])
print stump_weights | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
If your Adaboost is correctly implemented, the following things should be true:
tree_stumps[0] should split on term. 36 months with the prediction -1 on the left and +1 on the right.
tree_stumps[1] should split on grade.A with the prediction -1 on the left and +1 on the right.
Weights should be approximately [0.158, 0.177]
Reminders
- Stump weights ($\mathbf{\hat{w}}$) and data point weights ($\mathbf{\alpha}$) are two different concepts.
- Stump weights ($\mathbf{\hat{w}}$) tell you how important each stump is while making predictions with the entire boosted ensemble.
- Data point weights ($\mathbf{\alpha}$) tell you how important each data point is while training a decision stump.
Training a boosted ensemble of 10 stumps
Let us train an ensemble of 10 decision tree stumps with Adaboost. We run the adaboost_with_tree_stumps function with the following parameters:
* train_data
* features
* target
* num_tree_stumps = 10 | stump_weights, tree_stumps = adaboost_with_tree_stumps(train_data, features,
target, num_tree_stumps=10) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Making predictions
Recall from the lecture that in order to make predictions, we use the following formula:
$$
\hat{y} = sign\left(\sum_{t=1}^T \hat{w}_t f_t(x)\right)
$$
We need to do the following things:
- Compute the predictions $f_t(x)$ using the $t$-th decision tree
- Compute $\hat{w}_t f_t(x)$ by multiplying the stump_weights with the predictions $f_t(x)$ from the decision trees
- Sum the weighted predictions over each stump in the ensemble.
Complete the following skeleton for making predictions: | def predict_adaboost(stump_weights, tree_stumps, data):
scores = graphlab.SArray([0.]*len(data))
for i, tree_stump in enumerate(tree_stumps):
predictions = data.apply(lambda x: classify(tree_stump, x))
# Accumulate predictions on scaores array
# YOUR CODE HERE
scores += stump_weights[i] * predictions
return scores.apply(lambda score : +1 if score > 0 else -1)
predictions = predict_adaboost(stump_weights, tree_stumps, test_data)
accuracy = graphlab.evaluation.accuracy(test_data[target], predictions)
print 'Accuracy of 10-component ensemble = %s' % accuracy | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Now, let us take a quick look what the stump_weights look like at the end of each iteration of the 10-stump ensemble: | stump_weights | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Quiz Question: Are the weights monotonically decreasing, monotonically increasing, or neither?
Reminder: Stump weights ($\mathbf{\hat{w}}$) tell you how important each stump is while making predictions with the entire boosted ensemble.
Performance plots
In this section, we will try to reproduce some of the performance plots dicussed in the lecture.
How does accuracy change with adding stumps to the ensemble?
We will now train an ensemble with:
* train_data
* features
* target
* num_tree_stumps = 30
Once we are done with this, we will then do the following:
* Compute the classification error at the end of each iteration.
* Plot a curve of classification error vs iteration.
First, lets train the model. | # this may take a while...
stump_weights, tree_stumps = adaboost_with_tree_stumps(train_data,
features, target, num_tree_stumps=30) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Computing training error at the end of each iteration
Now, we will compute the classification error on the train_data and see how it is reduced as trees are added. | error_all = []
for n in xrange(1, 31):
predictions = predict_adaboost(stump_weights[:n], tree_stumps[:n], train_data)
error = 1.0 - graphlab.evaluation.accuracy(train_data[target], predictions)
error_all.append(error)
print "Iteration %s, training error = %s" % (n, error_all[n-1]) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Visualizing training error vs number of iterations
We have provided you with a simple code snippet that plots classification error with the number of iterations. | plt.rcParams['figure.figsize'] = 7, 5
plt.plot(range(1,31), error_all, '-', linewidth=4.0, label='Training error')
plt.title('Performance of Adaboost ensemble')
plt.xlabel('# of iterations')
plt.ylabel('Classification error')
plt.legend(loc='best', prop={'size':15})
plt.rcParams.update({'font.size': 16}) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Quiz Question: Which of the following best describes a general trend in accuracy as we add more and more components? Answer based on the 30 components learned so far.
Training error goes down monotonically, i.e. the training error reduces with each iteration but never increases.
Training error goes down in general, with some ups and downs in the middle.
Training error goes up in general, with some ups and downs in the middle.
Training error goes down in the beginning, achieves the best error, and then goes up sharply.
None of the above
Evaluation on the test data
Performing well on the training data is cheating, so lets make sure it works on the test_data as well. Here, we will compute the classification error on the test_data at the end of each iteration. | test_error_all = []
for n in xrange(1, 31):
predictions = predict_adaboost(stump_weights[:n], tree_stumps[:n], test_data)
error = 1.0 - graphlab.evaluation.accuracy(test_data[target], predictions)
test_error_all.append(error)
print "Iteration %s, test error = %s" % (n, test_error_all[n-1]) | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Visualize both the training and test errors
Now, let us plot the training & test error with the number of iterations. | plt.rcParams['figure.figsize'] = 7, 5
plt.plot(range(1,31), error_all, '-', linewidth=4.0, label='Training error')
plt.plot(range(1,31), test_error_all, '-', linewidth=4.0, label='Test error')
plt.title('Performance of Adaboost ensemble')
plt.xlabel('# of iterations')
plt.ylabel('Classification error')
plt.rcParams.update({'font.size': 16})
plt.legend(loc='best', prop={'size':15})
plt.tight_layout() | ml-classification/module-8-boosting-assignment-2-solution.ipynb | dnc1994/MachineLearning-UW | mit |
First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the characters to and from integers. Encoding the characters as integers makes it easier to use as input in the network. | with open('anna.txt', 'r') as f:
text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
chars = np.array([vocab_to_int[c] for c in text], dtype=np.int32) | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
And we can see the characters encoded as integers. | chars[:100] | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Since the network is working with individual characters, it's similar to a classification problem in which we are trying to predict the next character from the previous text. Here's how many 'classes' our network has to pick from. | np.max(chars)+1 | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Making training and validation batches
Now I need to split up the data into batches, and into training and validation sets. I should be making a test set here, but I'm not going to worry about that. My test will be if the network can generate new text.
Here I'll make both input and target arrays. The targets are the same as the inputs, except shifted one character over. I'll also drop the last bit of data so that I'll only have completely full batches.
The idea here is to make a 2D matrix where the number of rows is equal to the batch size. Each row will be one long concatenated string from the character data. We'll split this data into a training set and validation set using the split_frac keyword. This will keep 90% of the batches in the training set, the other 10% in the validation set. | def split_data(chars, batch_size, num_steps, split_frac=0.9):
"""
Split character data into training and validation sets, inputs and targets for each set.
Arguments
---------
chars: character array
batch_size: Size of examples in each of batch
num_steps: Number of sequence steps to keep in the input and pass to the network
split_frac: Fraction of batches to keep in the training set
Returns train_x, train_y, val_x, val_y
"""
slice_size = batch_size * num_steps
n_batches = int(len(chars) / slice_size)
# Drop the last few characters to make only full batches
x = chars[: n_batches*slice_size]
y = chars[1: n_batches*slice_size + 1]
# Split the data into batch_size slices, then stack them into a 2D matrix
x = np.stack(np.split(x, batch_size))
y = np.stack(np.split(y, batch_size))
# Now x and y are arrays with dimensions batch_size x n_batches*num_steps
# Split into training and validation sets, keep the first split_frac batches for training
split_idx = int(n_batches*split_frac)
train_x, train_y= x[:, :split_idx*num_steps], y[:, :split_idx*num_steps]
val_x, val_y = x[:, split_idx*num_steps:], y[:, split_idx*num_steps:]
return train_x, train_y, val_x, val_y | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Now I'll make my data sets and we can check out what's going on here. Here I'm going to use a batch size of 10 and 50 sequence steps. | train_x, train_y, val_x, val_y = split_data(chars, 10, 50)
train_x.shape | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Looking at the size of this array, we see that we have rows equal to the batch size. When we want to get a batch out of here, we can grab a subset of this array that contains all the rows but has a width equal to the number of steps in the sequence. The first batch looks like this: | train_x[:,:50] | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
I'll write another function to grab batches out of the arrays made by split_data. Here each batch will be a sliding window on these arrays with size batch_size X num_steps. For example, if we want our network to train on a sequence of 100 characters, num_steps = 100. For the next batch, we'll shift this window the next sequence of num_steps characters. In this way we can feed batches to the network and the cell states will continue through on each batch. | def get_batch(arrs, num_steps):
batch_size, slice_size = arrs[0].shape
n_batches = int(slice_size/num_steps)
for b in range(n_batches):
yield [x[:, b*num_steps: (b+1)*num_steps] for x in arrs] | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Building the model
Below is a function where I build the graph for the network. | def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2,
learning_rate=0.001, grad_clip=5, sampling=False):
# When we're using this network for sampling later, we'll be passing in
# one character at a time, so providing an option for that
if sampling == True:
batch_size, num_steps = 1, 1
tf.reset_default_graph()
# Declare placeholders we'll feed into the graph
inputs = tf.placeholder(tf.int32, [batch_size, num_steps], name='inputs')
targets = tf.placeholder(tf.int32, [batch_size, num_steps], name='targets')
# Keep probability placeholder for drop out layers
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
# One-hot encoding the input and target characters
x_one_hot = tf.one_hot(inputs, num_classes)
y_one_hot = tf.one_hot(targets, num_classes)
### Build the RNN layers
# Use a basic LSTM cell
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
# Add dropout to the cell
drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
# Stack up multiple LSTM layers, for deep learning
cell = tf.contrib.rnn.MultiRNNCell([drop] * num_layers)
initial_state = cell.zero_state(batch_size, tf.float32)
### Run the data through the RNN layers
# This makes a list where each element is on step in the sequence
rnn_inputs = [tf.squeeze(i, squeeze_dims=[1]) for i in tf.split(x_one_hot, num_steps, 1)]
# Run each sequence step through the RNN and collect the outputs
outputs, state = tf.contrib.rnn.static_rnn(cell, rnn_inputs, initial_state=initial_state)
final_state = state
# Reshape output so it's a bunch of rows, one output row for each step for each batch
seq_output = tf.concat(outputs, axis=1)
output = tf.reshape(seq_output, [-1, lstm_size])
# Now connect the RNN outputs to a softmax layer
with tf.variable_scope('softmax'):
softmax_w = tf.Variable(tf.truncated_normal((lstm_size, num_classes), stddev=0.1))
softmax_b = tf.Variable(tf.zeros(num_classes))
# Since output is a bunch of rows of RNN cell outputs, logits will be a bunch
# of rows of logit outputs, one for each step and batch
logits = tf.matmul(output, softmax_w) + softmax_b
# Use softmax to get the probabilities for predicted characters
preds = tf.nn.softmax(logits, name='predictions')
# Reshape the targets to match the logits
y_reshaped = tf.reshape(y_one_hot, [-1, num_classes])
loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_reshaped)
cost = tf.reduce_mean(loss)
# Optimizer for training, using gradient clipping to control exploding gradients
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), grad_clip)
train_op = tf.train.AdamOptimizer(learning_rate)
optimizer = train_op.apply_gradients(zip(grads, tvars))
# Export the nodes
# NOTE: I'm using a namedtuple here because I think they are cool
export_nodes = ['inputs', 'targets', 'initial_state', 'final_state',
'keep_prob', 'cost', 'preds', 'optimizer']
Graph = namedtuple('Graph', export_nodes)
local_dict = locals()
graph = Graph(*[local_dict[each] for each in export_nodes])
return graph | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Hyperparameters
Here I'm defining the hyperparameters for the network.
batch_size - Number of sequences running through the network in one pass.
num_steps - Number of characters in the sequence the network is trained on. Larger is better typically, the network will learn more long range dependencies. But it takes longer to train. 100 is typically a good number here.
lstm_size - The number of units in the hidden layers.
num_layers - Number of hidden LSTM layers to use
learning_rate - Learning rate for training
keep_prob - The dropout keep probability when training. If you're network is overfitting, try decreasing this.
Here's some good advice from Andrej Karpathy on training the network. I'm going to write it in here for your benefit, but also link to where it originally came from.
Tips and Tricks
Monitoring Validation Loss vs. Training Loss
If you're somewhat new to Machine Learning or Neural Networks it can take a bit of expertise to get good models. The most important quantity to keep track of is the difference between your training loss (printed during training) and the validation loss (printed once in a while when the RNN is run on the validation data (by default every 1000 iterations)). In particular:
If your training loss is much lower than validation loss then this means the network might be overfitting. Solutions to this are to decrease your network size, or to increase dropout. For example you could try dropout of 0.5 and so on.
If your training/validation loss are about equal then your model is underfitting. Increase the size of your model (either number of layers or the raw number of neurons per layer)
Approximate number of parameters
The two most important parameters that control the model are lstm_size and num_layers. I would advise that you always use num_layers of either 2/3. The lstm_size can be adjusted based on how much data you have. The two important quantities to keep track of here are:
The number of parameters in your model. This is printed when you start training.
The size of your dataset. 1MB file is approximately 1 million characters.
These two should be about the same order of magnitude. It's a little tricky to tell. Here are some examples:
I have a 100MB dataset and I'm using the default parameter settings (which currently print 150K parameters). My data size is significantly larger (100 mil >> 0.15 mil), so I expect to heavily underfit. I am thinking I can comfortably afford to make lstm_size larger.
I have a 10MB dataset and running a 10 million parameter model. I'm slightly nervous and I'm carefully monitoring my validation loss. If it's larger than my training loss then I may want to try to increase dropout a bit and see if that helps the validation loss.
Best models strategy
The winning strategy to obtaining very good models (if you have the compute time) is to always err on making the network larger (as large as you're willing to wait for it to compute) and then try different dropout values (between 0,1). Whatever model has the best validation performance (the loss, written in the checkpoint filename, low is good) is the one you should use in the end.
It is very common in deep learning to run many different models with many different hyperparameter settings, and in the end take whatever checkpoint gave the best validation performance.
By the way, the size of your training and validation splits are also parameters. Make sure you have a decent amount of data in your validation set or otherwise the validation performance will be noisy and not very informative. | batch_size = 100
num_steps = 100
lstm_size = 512
num_layers = 2
learning_rate = 0.001
keep_prob = 0.5 | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Training
Time for training which is pretty straightforward. Here I pass in some data, and get an LSTM state back. Then I pass that state back in to the network so the next batch can continue the state from the previous batch. And every so often (set by save_every_n) I calculate the validation loss and save a checkpoint.
Here I'm saving checkpoints with the format
i{iteration number}_l{# hidden layer units}_v{validation loss}.ckpt | epochs = 20
# Save every N iterations
save_every_n = 200
train_x, train_y, val_x, val_y = split_data(chars, batch_size, num_steps)
model = build_rnn(len(vocab),
batch_size=batch_size,
num_steps=num_steps,
learning_rate=learning_rate,
lstm_size=lstm_size,
num_layers=num_layers)
saver = tf.train.Saver(max_to_keep=100)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# Use the line below to load a checkpoint and resume training
#saver.restore(sess, 'checkpoints/______.ckpt')
n_batches = int(train_x.shape[1]/num_steps)
iterations = n_batches * epochs
for e in range(epochs):
# Train network
new_state = sess.run(model.initial_state)
loss = 0
for b, (x, y) in enumerate(get_batch([train_x, train_y], num_steps), 1):
iteration = e*n_batches + b
start = time.time()
feed = {model.inputs: x,
model.targets: y,
model.keep_prob: keep_prob,
model.initial_state: new_state}
batch_loss, new_state, _ = sess.run([model.cost, model.final_state, model.optimizer],
feed_dict=feed)
loss += batch_loss
end = time.time()
print('Epoch {}/{} '.format(e+1, epochs),
'Iteration {}/{}'.format(iteration, iterations),
'Training loss: {:.4f}'.format(loss/b),
'{:.4f} sec/batch'.format((end-start)))
if (iteration%save_every_n == 0) or (iteration == iterations):
# Check performance, notice dropout has been set to 1
val_loss = []
new_state = sess.run(model.initial_state)
for x, y in get_batch([val_x, val_y], num_steps):
feed = {model.inputs: x,
model.targets: y,
model.keep_prob: 1.,
model.initial_state: new_state}
batch_loss, new_state = sess.run([model.cost, model.final_state], feed_dict=feed)
val_loss.append(batch_loss)
print('Validation loss:', np.mean(val_loss),
'Saving checkpoint!')
saver.save(sess, "checkpoints/i{}_l{}_v{:.3f}.ckpt".format(iteration, lstm_size, np.mean(val_loss))) | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Sampling
Now that the network is trained, we'll can use it to generate new text. The idea is that we pass in a character, then the network will predict the next character. We can use the new one, to predict the next one. And we keep doing this to generate all new text. I also included some functionality to prime the network with some text by passing in a string and building up a state from that.
The network gives us predictions for each character. To reduce noise and make things a little less random, I'm going to only choose a new character from the top N most likely characters. | def pick_top_n(preds, vocab_size, top_n=5):
p = np.squeeze(preds)
p[np.argsort(p)[:-top_n]] = 0
p = p / np.sum(p)
c = np.random.choice(vocab_size, 1, p=p)[0]
return c
def sample(checkpoint, n_samples, lstm_size, vocab_size, prime="The "):
samples = [c for c in prime]
model = build_rnn(vocab_size, lstm_size=lstm_size, sampling=True)
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, checkpoint)
new_state = sess.run(model.initial_state)
for c in prime:
x = np.zeros((1, 1))
x[0,0] = vocab_to_int[c]
feed = {model.inputs: x,
model.keep_prob: 1.,
model.initial_state: new_state}
preds, new_state = sess.run([model.preds, model.final_state],
feed_dict=feed)
c = pick_top_n(preds, len(vocab))
samples.append(int_to_vocab[c])
for i in range(n_samples):
x[0,0] = c
feed = {model.inputs: x,
model.keep_prob: 1.,
model.initial_state: new_state}
preds, new_state = sess.run([model.preds, model.final_state],
feed_dict=feed)
c = pick_top_n(preds, len(vocab))
samples.append(int_to_vocab[c])
return ''.join(samples) | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Here, pass in the path to a checkpoint and sample from the network. | checkpoint = "checkpoints/____.ckpt"
samp = sample(checkpoint, 2000, lstm_size, len(vocab), prime="Far")
print(samp) | nanodegrees/deep_learning_foundations/unit_2/lesson_24_intro_to_recurrent_neural_networks/.ipynb_checkpoints/Anna KaRNNa-checkpoint.ipynb | broundy/udacity | unlicense |
Introduce Parallelism
As we can see in the solution, a plain scalar iterative approach only uses one thread, while modern CPUs have typically 4 cores and 8 threads.
Fortunately, .Net and C# provide an intuitive construct to leverage parallelism : Parallel.For.
Modify 01-vector-add.cs to distribute the work among multiple threads.
If you get stuck, you can refer to the solution. | !hybridizer-cuda ./01-vector-add/01-vector-add.cs -o ./01-vector-add/parallel-vectoradd.exe -run | Jupyter/Labs/02_VectorAdd/HYB_CUDA_CSHARP.ipynb | altimesh/hybridizer-basic-samples | mit |
Run Code on the GPU
Using Hybridizer to run the above code on a GPU is quite straightforward. We need to
- Decorate methods we want to run on the GPU
This is done by adding [EntryPoint] attribute on methods of interest.
- "Wrap" current object into a dynamic object able to dispatch code on the GPU
This is done by the following boilerplate code:
csharp
dynamic wrapped = HybRunner.Cuda().Wrap(new Program());
wrapped.mymethod(...)
wrapped object has the same methods signatures (static or instance) as the current object, but dispatches calls to GPU.
Modify the 02-vector-add.cs so the Add method runs on a GPU.
If you get stuck, you can refer to the solution. | !hybridizer-cuda ./02-gpu-vector-add/02-gpu-vector-add.cs -o ./02-gpu-vector-add/gpu-vectoradd.exe -run | Jupyter/Labs/02_VectorAdd/HYB_CUDA_CSHARP.ipynb | altimesh/hybridizer-basic-samples | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.