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.... | 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 ... | 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.
... | 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_le... | 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 prob... | 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.
... | 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:... | 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
... | 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" />
... | 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 o... | 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... | # 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 o... | 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_tar... | 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_li... | 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 al... | 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(tra... | 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']!... | 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 inp... | 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... | 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 ... | 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_d... | 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... | 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_... | 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=... | 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))
... | 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_ar... | 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_proce... | 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 ... | 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,... | 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_m... | 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 "[",
... | 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 agai... | 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.Pro... | 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... | 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? ... | 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.readlin... | 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 ... | 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(la... | 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 ... | 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 represente... | 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... | 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... | 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_n... | 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 c... | # 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')
nu... | 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 we... | 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... | 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... | 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:
... | 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':... | 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']]
... | 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 cal... | 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_cl... | 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
* an... | # 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 traini... | 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 ... | 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 Non... | 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... | 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... | 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
score... | 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 ... | # 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, wi... | 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.up... | 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 sa... | 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 kee... | 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... | 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:
... | 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 lon... | 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... | 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=ls... | 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 ne... | 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... | 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 mult... | !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 ... | !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.