markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Lets use apply to calculate a meaningful baseball statistics, slugging percentage: $$SLG = \frac{1B + (2 \times 2B) + (3 \times 3B) + (4 \times HR)}{AB}$$ And just for fun, we will format the resulting estimate.
slg = lambda x: (x['h']-x['X2b']-x['X3b']-x['hr'] + 2*x['X2b'] + 3*x['X3b'] + 4*x['hr'])/(x['ab']+1e-6) baseball.apply(slg, axis=1).apply(lambda x: '%.3f' % x)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Sorting and Ranking Pandas objects include methods for re-ordering data.
baseball_newind.sort_index().head() baseball_newind.sort_index(ascending=False).head() baseball_newind.sort_index(axis=1).head()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
We can also use order to sort a Series by value, rather than by label.
baseball.hr.order(ascending=False)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
For a DataFrame, we can sort according to the values of one or more columns using the by argument of sort_index:
baseball[['player','sb','cs']].sort_index(ascending=[False,True], by=['sb', 'cs']).head(10)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Ranking does not re-arrange data, but instead returns an index that ranks each value relative to others in the Series.
baseball.hr.rank()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Ties are assigned the mean value of the tied ranks, which may result in decimal values.
pd.Series([100,100]).rank()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Alternatively, you can break ties via one of several methods, such as by the order in which they occur in the dataset:
baseball.hr.rank(method='first')
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Calling the DataFrame's rank method results in the ranks of all columns:
baseball.rank(ascending=False).head() baseball[['r','h','hr']].rank(ascending=False).head()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Exercise Calculate on base percentage for each player, and return the ordered series of estimates. $$OBP = \frac{H + BB + HBP}{AB + BB + HBP + SF}$$ Hierarchical indexing In the baseball example, I was forced to combine 3 fields to obtain a unique index that was not simply an integer value. A more elegant way to have d...
baseball_h = baseball.set_index(['year', 'team', 'player']) baseball_h.head(10)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
This index is a MultiIndex object that consists of a sequence of tuples, the elements of which is some combination of the three columns used to create the index. Where there are multiple repeated values, Pandas does not print the repeats, making it easy to identify groups of values.
baseball_h.index[:10] baseball_h.index.is_unique baseball_h.ix[(2007, 'ATL', 'francju01')]
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Recall earlier we imported some microbiome data using two index columns. This created a 2-level hierarchical index:
mb = pd.read_csv("data/microbiome.csv", index_col=['Taxon','Patient']) mb.head(10) mb.index
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
With a hierachical index, we can select subsets of the data based on a partial index:
mb.ix['Proteobacteria']
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Hierarchical indices can be created on either or both axes. Here is a trivial example:
frame = pd.DataFrame(np.arange(12).reshape(( 4, 3)), index =[['a', 'a', 'b', 'b'], [1, 2, 1, 2]], columns =[['Ohio', 'Ohio', 'Colorado'], ['Green', 'Red', 'Green']]) frame
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
If you want to get fancy, both the row and column indices themselves can be given names:
frame.index.names = ['key1', 'key2'] frame.columns.names = ['state', 'color'] frame
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
With this, we can do all sorts of custom indexing:
frame.ix['a']['Ohio'] frame.ix['b', 2]['Colorado']
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Additionally, the order of the set of indices in a hierarchical MultiIndex can be changed by swapping them pairwise:
mb.swaplevel('Patient', 'Taxon').head()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Data can also be sorted by any index level, using sortlevel:
mb.sortlevel('Patient', ascending=False).head()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Missing data The occurence of missing data is so prevalent that it pays to use tools like Pandas, which seamlessly integrates missing data handling so that it can be dealt with easily, and in the manner required by the analysis at hand. Missing data are represented in Series and DataFrame objects by the NaN floating po...
foo = pd.Series([NaN, -3, None, 'foobar']) foo foo.isnull()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Missing values may be dropped or indexed out:
bacteria2 bacteria2.dropna() bacteria2[bacteria2.notnull()]
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
By default, dropna drops entire rows in which one or more values are missing.
data data.dropna()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
This can be overridden by passing the how='all' argument, which only drops a row when every field is a missing value.
data.dropna(how='all')
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
This can be customized further by specifying how many values need to be present before a row is dropped via the thresh argument.
data.ix[7, 'year'] = nan data data.dropna(thresh=4)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
This is typically used in time series applications, where there are repeated measurements that are incomplete for some subjects. If we want to drop missing values column-wise instead of row-wise, we use axis=1.
data.dropna(axis=1)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Rather than omitting missing data from an analysis, in some cases it may be suitable to fill the missing value in, either with a default value (such as zero) or a value that is either imputed or carried forward/backward from similar data points. We can do this programmatically in Pandas with the fillna argument.
bacteria2.fillna(0) data.fillna({'year': 2013, 'treatment':2})
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Notice that fillna by default returns a new object with the desired filling behavior, rather than changing the Series or DataFrame in place (in general, we like to do this, by the way!).
data
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
We can alter values in-place using inplace=True.
_ = data.year.fillna(2013, inplace=True) data
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Missing values can also be interpolated, using any one of a variety of methods:
bacteria2.fillna(method='bfill') bacteria2.fillna(bacteria2.mean())
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Data summarization We often wish to summarize data in Series or DataFrame objects, so that they can more easily be understood or compared with similar data. The NumPy package contains several functions that are useful here, but several summarization or reduction methods are built into Pandas data structures.
baseball.sum()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Clearly, sum is more meaningful for some columns than others. For methods like mean for which application to string variables is not just meaningless, but impossible, these columns are automatically exculded:
baseball.mean()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
The important difference between NumPy's functions and Pandas' methods is that the latter have built-in support for handling missing data.
bacteria2 bacteria2.mean()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Sometimes we may not want to ignore missing values, and allow the nan to propagate.
bacteria2.mean(skipna=False)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Passing axis=1 will summarize over rows instead of columns, which only makes sense in certain situations.
extra_bases = baseball[['X2b','X3b','hr']].sum(axis=1) extra_bases.order(ascending=False)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
A useful summarization that gives a quick snapshot of multiple statistics for a Series or DataFrame is describe:
baseball.describe()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
describe can detect non-numeric data and sometimes yield useful information about it.
baseball.player.describe()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
We can also calculate summary statistics across multiple columns, for example, correlation and covariance. $$cov(x,y) = \sum_i (x_i - \bar{x})(y_i - \bar{y})$$
baseball.hr.cov(baseball.X2b)
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
$$corr(x,y) = \frac{cov(x,y)}{(n-1)s_x s_y} = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_i (x_i - \bar{x})^2 \sum_i (y_i - \bar{y})^2}}$$
baseball.hr.corr(baseball.X2b) baseball.ab.corr(baseball.h) baseball.corr()
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
If we have a DataFrame with a hierarchical index (or indices), summary statistics can be applied with respect to any of the index levels:
mb.head() mb.sum(level='Taxon')
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Writing Data to Files As well as being able to read several data input formats, Pandas can also export data to a variety of storage formats. We will bring your attention to just a couple of these.
mb.to_csv("mb.csv")
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
The to_csv method writes a DataFrame to a comma-separated values (csv) file. You can specify custom delimiters (via sep argument), how missing values are written (via na_rep argument), whether the index is writen (via index argument), whether the header is included (via header argument), among other options. An efficie...
baseball.to_pickle("baseball_pickle")
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
The complement to to_pickle is the read_pickle function, which restores the pickle to a DataFrame or Series:
pd.read_pickle("baseball_pickle")
Day_01/01_Pandas/1. Introduction to Pandas.ipynb
kialio/gsfcpyboot
mit
Data Mining
# Reading in the data allmatches = pd.read_csv("../data/matches.csv") alldeliveries = pd.read_csv("../data/deliveries.csv") allmatches.head(10) # Selecting Seasons 2008 - 2015 matches_seasons = allmatches.loc[allmatches['season'] != 2016] deliveries_seasons = alldeliveries.loc[alldeliveries['match_id'] < 518] # Selec...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Building Features
# Team Strike rates for first 5 batsmen in the team (Higher the better) def getMatchDeliveriesDF(match_id): return deliveries.loc[deliveries['match_id'] == match_id] def getInningsOneBatsmen(match_deliveries): return match_deliveries.loc[match_deliveries['inning'] == 1].batsman.unique()[0:5] def getInningsTw...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Adding Columns
#Create Column for Team 1 Winning Status (1 = Won, 0 = Lost) matches['team1Winning'] = np.where(matches['team1'] == matches['winner'], 1, 0) #New Column for Difference of Average Strike rates (First Team SR - Second Team SR) [Negative value means Second team is better] firstTeamSR = [] secondTeamSR = [] for i in mat...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Visualisation
#Graph for Strike Rate matches.boxplot(column = 'Avg_SR_Difference', by='team1Winning', showfliers= False) #Graph for WPR Difference matches.boxplot(column = 'Avg_WPR_Difference', by='team1Winning', showfliers= False) # Graph for MVP Difference matches.boxplot(column = 'Total_MVP_Difference', by='team1Winning', sho...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Predictions for the data
from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn import svm from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.cross_validation import train_test_split from sklearn import metrics from patsy impor...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Training and testing on Entire Data
# instantiate a logistic regression model, and fit with X and y model = LogisticRegression() model = model.fit(X, y_arr) # check the accuracy on the training set print "Accuracy is", model.score(X, y_arr)*100, "%"
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Splitting train and test using train_test_split
# evaluate the model by splitting into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y_arr, random_state = 0) # Logistic Regression on train_test_split model2 = LogisticRegression() model2.fit(X_train, y_train) # predict class labels for the test set predicted = model2.predict(X_test) # ge...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Splitting Training Set (2008-2013) and Test Set (2013-2015) based on Seasons
#Splitting X_timetrain = X.loc[X.index < 398] Y_timetrain = y.loc[y.index < 398] Y_timetrain_arr = np.ravel(Y_timetrain) X_timetest = X.loc[X.index >= 398] Y_timetest = y.loc[y.index >= 398] Y_timetest_arr = np.ravel(Y_timetest) # Logistic Regression on time-based split sets model3 = LogisticRegression() model3.fit(X_...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Support Vector Machines
clf = svm.SVC(gamma=0.001, C=10) clf.fit(X_timetrain, Y_timetrain_arr) clf_pred = clf.predict(X_timetest) print "Accuracy is ", metrics.accuracy_score(Y_timetest_arr, clf_pred)*100, "%"
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Random Forests
rfc = RandomForestClassifier(n_jobs = -1, random_state = 1) rfc.fit(X_timetrain, Y_timetrain_arr) rfc_pred = rfc.predict(X_timetest) print "Accuracy is ", metrics.accuracy_score(Y_timetest_arr, rfc_pred)*100, "%" fi = zip(X.columns, rfc.feature_importances_) print "Feature Importance according to Random Forests Model\...
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Naive Bayes Classifier
gclf = GaussianNB() gclf.fit(X_timetrain, Y_timetrain_arr) gclf_pred = gclf.predict(X_timetest) print "Accuracy is ", metrics.accuracy_score(Y_timetest_arr, gclf_pred) *100, "%"
src/Match Outcome Prediction with IPL Data (Gursahej).ipynb
XInterns/IPL-Sparkers
mit
Setup We haven't really looked into the detail of how this works yet - so this is provided for self-study for those who are interested. We'll look at it closely next week.
path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt") text = open(path).read().lower() print('corpus length:', len(text)) !tail {path} -n25 #path = 'data/wiki/' #text = open(path+'small.txt').read().lower() #print('corpus length:', len(text)) #text = text[0:1000000] chars =...
fastAI/deeplearning1/nbs/char-rnn.ipynb
quoniammm/mine-tensorflow-examples
mit
Preprocess and create model
maxlen = 40 sentences = [] next_chars = [] for i in range(0, len(idx) - maxlen+1): sentences.append(idx[i: i + maxlen]) next_chars.append(idx[i+1: i+maxlen+1]) print('nb sequences:', len(sentences)) sentences = np.concatenate([[np.array(o)] for o in sentences[:-2]]) next_chars = np.concatenate([[np.array(o)] f...
fastAI/deeplearning1/nbs/char-rnn.ipynb
quoniammm/mine-tensorflow-examples
mit
Train
def print_example(): seed_string="ethics is a basic foundation of all that" for i in range(320): x=np.array([char_indices[c] for c in seed_string[-40:]])[np.newaxis,:] preds = model.predict(x, verbose=0)[0][-1] preds = preds/np.sum(preds) next_char = choice(chars, p=preds) ...
fastAI/deeplearning1/nbs/char-rnn.ipynb
quoniammm/mine-tensorflow-examples
mit
Polynomial regression, revisited We build on the material from Week 3, where we wrote the function to produce an SFrame with columns containing the powers of a given input. Copy and paste the function polynomial_sframe from Week 3:
def polynomial_sframe(feature, degree): # assume that degree >= 1 # initialize the SFrame: poly_sframe = graphlab.SFrame() # and set poly_sframe['power_1'] equal to the passed feature poly_sframe['power_1'] = feature # first check if degree > 1 if degree > 1: # then loop over the rem...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Let's use matplotlib to visualize what a polynomial regression looks like on the house data.
import matplotlib.pyplot as plt %matplotlib inline sales = graphlab.SFrame('kc_house_data.gl/')
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
As in Week 3, we will use the sqft_living variable. For plotting purposes (connecting the dots), you'll need to sort by the values of sqft_living. For houses with identical square footage, we break the tie by their prices.
sales = sales.sort(['sqft_living','price'])
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Let us revisit the 15th-order polynomial model using the 'sqft_living' input. Generate polynomial features up to degree 15 using polynomial_sframe() and fit a model with these features. When fitting the model, use an L2 penalty of 1e-5:
l2_small_penalty = 1e-5
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Note: When we have so many features and so few data points, the solution can become highly numerically unstable, which can sometimes lead to strange unpredictable results. Thus, rather than using no regularization, we will introduce a tiny amount of regularization (l2_penalty=1e-5) to make the solution numerically sta...
poly15_data = polynomial_sframe(sales['sqft_living'], 15) # use equivalent of `polynomial_sframe` poly15_features = poly15_data.column_names() # get the name of the features poly15_data['price'] = sales['price'] # add price to the data since it's the target model1 = graphlab.linear_regression.create(poly15_data, targe...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
QUIZ QUESTION: What's the learned value for the coefficient of feature power_1? Observe overfitting Recall from Week 3 that the polynomial fit of degree 15 changed wildly whenever the data changed. In particular, when we split the sales data into four subsets and fit the model of degree 15, the result came out to be v...
(semi_split1, semi_split2) = sales.random_split(.5,seed=0) (set_1, set_2) = semi_split1.random_split(0.5, seed=0) (set_3, set_4) = semi_split2.random_split(0.5, seed=0)
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Next, fit a 15th degree polynomial on set_1, set_2, set_3, and set_4, using 'sqft_living' to predict prices. Print the weights and make a plot of the resulting model. Hint: When calling graphlab.linear_regression.create(), use the same L2 penalty as before (i.e. l2_small_penalty). Also, make sure GraphLab Create doesn...
def get_poly_model(set_data, l2_penalty): poly15_data = polynomial_sframe(set_data['sqft_living'], 15) poly15_features = poly15_data.column_names() # get the name of the features poly15_data['price'] = set_data['price'] # add price to the data since it's the target model15 = graphlab.linear_regression.c...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
The four curves should differ from one another a lot, as should the coefficients you learned. QUIZ QUESTION: For the models learned in each of these training sets, what are the smallest and largest values you learned for the coefficient of feature power_1? (For the purpose of answering this question, negative numbers...
l2_new_penalty = 1e5 set_1_coef = get_coef(set_1, l2_new_penalty) print set_1_coef[set_1_coef['name'] == 'power_1'] plot_fitted_line(set_1, l2_new_penalty) set_2_coef = get_coef(set_2, l2_new_penalty) print set_2_coef[set_2_coef['name'] == 'power_1'] plot_fitted_line(set_2, l2_new_penalty) set_3_coef = get_coef(set_...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
These curves should vary a lot less, now that you applied a high degree of regularization. QUIZ QUESTION: For the models learned with the high level of regularization in each of these training sets, what are the smallest and largest values you learned for the coefficient of feature power_1? (For the purpose of answeri...
(train_valid, test) = sales.random_split(.9, seed=1) train_valid_shuffled = graphlab.toolkits.cross_validation.shuffle(train_valid, random_seed=1)
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Once the data is shuffled, we divide it into equal segments. Each segment should receive n/k elements, where n is the number of observations in the training set and k is the number of segments. Since the segment 0 starts at index 0 and contains n/k elements, it ends at index (n/k)-1. The segment 1 starts where the segm...
n = len(train_valid_shuffled) k = 10 # 10-fold cross-validation for i in xrange(k): start = (n*i)/k end = (n*(i+1))/k-1 print i, (start, end)
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Let us familiarize ourselves with array slicing with SFrame. To extract a continuous slice from an SFrame, use colon in square brackets. For instance, the following cell extracts rows 0 to 9 of train_valid_shuffled. Notice that the first index (0) is included in the slice but the last index (10) is omitted.
train_valid_shuffled[0:10] # rows 0 to 9
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Now let us extract individual segments with array slicing. Consider the scenario where we group the houses in the train_valid_shuffled dataframe into k=10 segments of roughly equal size, with starting and ending indices computed as above. Extract the fourth segment (segment 3) and assign it to a variable called validat...
print len(train_valid_shuffled) # start = (n*i)/k # end = (n*(i+1))/k-1 # validation4 = train_valid_shuffled[(n*3)/k : (n*(3+1))/k-1] #5818, 7757 validation4 = train_valid_shuffled[5818 : 7757]
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
To verify that we have the right elements extracted, run the following cell, which computes the average price of the fourth segment. When rounded to nearest whole number, the average should be $536,234.
print int(round(validation4['price'].mean(), 0))
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
After designating one of the k segments as the validation set, we train a model using the rest of the data. To choose the remainder, we slice (0:start) and (end+1:n) of the data and paste them together. SFrame has append() method that pastes together two disjoint sets of rows originating from a common dataset. For inst...
n = len(train_valid_shuffled) first_two = train_valid_shuffled[0:2] last_two = train_valid_shuffled[n-2:n] print first_two.append(last_two)
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Extract the remainder of the data after excluding fourth segment (segment 3) and assign the subset to train4.
first_part = train_valid_shuffled[0:5817] last_part = train_valid_shuffled[7758:] train4 = first_part.append(last_part) print len(train4)
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
To verify that we have the right elements extracted, run the following cell, which computes the average price of the data with fourth segment excluded. When rounded to nearest whole number, the average should be $539,450.
print int(round(train4['price'].mean(), 0))
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Now we are ready to implement k-fold cross-validation. Write a function that computes k validation errors by designating each of the k segments as the validation set. It accepts as parameters (i) k, (ii) l2_penalty, (iii) dataframe, (iv) name of output column (e.g. price) and (v) list of feature names. The function ret...
import numpy as np def k_fold_cross_validation(k, l2_penalty, data, output_name, features_list): rss_sum = 0 n = len(data) for i in xrange(k): start = (n*i)/k end = (n*(i+1))/k-1 validation_set = data[start:end+1] training_set = data[0:start].append(data[end+1:n]) ...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Once we have a function to compute the average validation error for a model, we can write a loop to find the model that minimizes the average validation error. Write a loop that does the following: * We will again be aiming to fit a 15th-order polynomial model using the sqft_living input * For l2_penalty in [10^1, 10^1...
poly_data = polynomial_sframe(train_valid_shuffled['sqft_living'], 15) my_features = poly_data.column_names() poly_data['price'] = train_valid_shuffled['price'] val_err_dict = {} for l2_penalty in np.logspace(1, 7, num=13): val_err = k_fold_cross_validation(10, l2_penalty, poly_data, 'price', my_features) ...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
QUIZ QUESTIONS: What is the best value for the L2 penalty according to 10-fold validation? You may find it useful to plot the k-fold cross-validation errors you have obtained to better understand the behavior of the method.
l2_penalty = graphlab.SArray(val_err_dict.keys()) validation_error = graphlab.SArray(val_err_dict.values()) sf = graphlab.SFrame({'l2_penalty':l2_penalty,'validation_error':validation_error}) print sf # Plot the l2_penalty values in the x axis and the cross-validation error in the y axis. # Using plt.xscale('log') wi...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Once you found the best value for the L2 penalty using cross-validation, it is important to retrain a final model on all of the training data using this value of l2_penalty. This way, your final model will be trained on the entire dataset.
poly_data = polynomial_sframe(train_valid_shuffled['sqft_living'], 15) features_list = poly_data.column_names() poly_data['price'] = train_valid_shuffled['price'] l2_penalty_best = 1000.0 model = graphlab.linear_regression.create(poly_data, target='price', features=features_lis...
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
QUIZ QUESTION: Using the best L2 penalty found above, train a model using all training data. What is the RSS on the TEST data of the model you learn with this L2 penalty?
poly_test = polynomial_sframe(test['sqft_living'], 15) predictions = model.predict(poly_test) errors = predictions-test['price'] rss = (errors*errors).sum() print rss
machine_learning/2_regression/assignment/week4/week-4-ridge-regression-assignment-1-exercise.ipynb
tuanavu/coursera-university-of-washington
mit
Users Involved There were about 1634 users involved in creating the data set, the top 10 of all users accounts for 40% of the created data. There is no direct evidence from the user name that any of them are bot-like users. This could be determined by further research. Many users (over 60%) have made less than 10 entri...
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_users(...): pipeline = [ {"$match": {"created.user": {"$exists": True}}}, {"$group": {"_id": "$created.user", "count": {"$sum": 1}}}, {"$sort": {"count": -1}} ] l = list(p...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Types of Amenities The attribute amenity inspired me to do further research in which kind of buildings / objects / facilities are stored in the Open Street Map data in larger quantities in order to do more detailed research on those objects. Especially Restaurants, Pubs and Churches / Places of Worship were investigate...
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_amenities(...): pipeline = [ {"$match": {"amenity": {"$exists": True}}}, {"$group": {"_id": "$amenity", "count": {"$sum": 1}}}, {"$sort": {"count": -1}} ] l = list(project...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Popular Leisure Activities The attribute leisure shows the types of leisure activities one can do in Dresden and inspired me to invesigate more on popular sports in the city (leisure=sports_center or leisure=stadium).
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_amenities(...): pipeline = [ {"$match": {"leisure": {"$exists": True}}}, {"$group": {"_id": "$leisure", "count": {"$sum": 1}}}, {"$sort": {"count": -1}} ] l = list(project...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Religions in Places of Worship Grouping and sorting by the occurences of the religion attribute for all amenities classified as place_of_worship or community_center gives us an indication, how prevalent religions are in our city: obviously, christian is the most prevalent here.
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_religions(...): pipeline = [ {"$match": {"amenity":{"$in": ["place_of_worship","community_center"]}}}, {"$group": {"_id": "$religion", "count": {"$sum": 1}}}, {"$sort": {"coun...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Cuisines in Restaurants We can list the types of cuisines in restaurants (elements with attribute amenity matching restaurant) and sort them in decending order. We can notice certain inconsistencies or overlaps in the classifications of this data: e.g., a kebab cuisine may very well be also classified as an arab cuisin...
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_cuisines(...): pipeline = [ {"$match": {"amenity": "restaurant"}}, {"$group": {"_id": "$cuisine", "count": {"$sum": 1}}}, {"$sort": {"count": -1}} ] l = list(project_coll....
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Beers in Pubs Germans do love their beers and the dataset shows that certain pubs, restaurants or bars are sponsored by certain beer brands (often advertised on the pubs entrance). We can analyze the prevalence of beer brands by grouping and sorting by occurence of the attribute brewery for all the amenities classified...
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_beers(...): pipeline = [ {"$match": {"amenity": {"$in":["pub","bar","restaurant"]}}}, {"$group": {"_id": "$brewery", "count": {"$sum": 1}}}, {"$sort": {"count": -1}} ] l =...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Popular Sports To investigate, which sports are popular, we can group and sort by the (occurence of the) sport attribute for all elements classified as sports_centre or stadium in their leisure attribute. Unsurprisingly for a german city, we notice that 9pin (bowling) and soccer are the most popular sports, followed by...
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_sports(...): pipeline = [ {"$match": {"leisure": {"$in": ["sports_centre","stadium"]}}}, {"$group": {"_id": "$sport", "count": {"$sum": 1}}}, {"$sort": {"count": -1}} ] l ...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Where to Dance in Dresden I am a passionate social dancer, so a list of dance schools in Dresden should not be abscent from this investigation. We can quickly grab all elements which have the leisure attribute set to dancing.
from Project.notebook_stub import project_coll import pprint # Query used - see function: Project.audit_stats_map.stats_dances(...): l = list(project_coll.distinct("name", {"leisure": "dance"})) pprint.pprint(l[1:10]+['...'])
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Problems Encountered in the Map / Data Quality Try it out: Use python project.py -q to obtain the data from this chapter. See Sample Output in file Project/output_project.py_-q.txt. The script also writes a CSV file to Project/data/audit_buildings.csv, which is also beautified into a Excel File. Leading Zeros As alread...
from Project.notebook_stub import project_coll # Query used - see function: Project.audit_quality_map.audit_phone_numbers(...): pipeline = [ {"$match": {"$or": [ {"phone": {"$exists": True}}, {"mobile_phone": {"$exists": True}}, {"address.phone": {"$exists": True...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Cleaning Phone Numbers Try it out: Use python project.py -C to clean in debug mode. See Sample Output in file Project/output_project.py_-C.txt. The script also writes a CSV file to Project/data/clean_phones.csv, which is also beautified into a Excel File. Cleaning the phone numbers involves: * unifying the different ph...
from Project.notebook_stub import project_coll # Query used - see function: Project.audit_quality_map.audit_streets(...): expectedStreetPattern = \ u"^.*(?<![Ss]tra\u00dfe)(?<![Ww]eg)(?<![Aa]llee)(?<![Rr]ing)(?<![Bb]erg)" + \ u"(?<![Pp]ark)(?<![Hh]\u00f6he)(?<![Pp]latz)(?<![Bb]r\u00fccke)(?<![Gg]rund)$" l = li...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Skimming through the list, it was noticable that the nature of the german language (and how in Germany streetnames work) results in the fact, that there are many small places without a suffix like "street" but "their own thing" (like Am Hang lit. 'At The Slope', Beerenhut lit. 'Berry Hat', Im Grunde lit. 'In The Ground...
from Project.notebook_stub import project_db # Query used - see function: Project.audit_quality_map.audit_buildings(...): buildings_with_streets = project_db.eval(''' db.osmnodes.ensureIndex({pos:"2dsphere"}); result = []; db.osmnodes.find( {"building": {"$exists...
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
The resulting objects are then iterated through and the best and worst fitting nearby street name are identified each using the Levenshtein distance. For each object, a row is created in a DataFrame which is subsequently exported to a csv file Project/data/audit_buildings.csv that was manually beautified into an Excel ...
from Project.audit_zipcode_map import audit_zipcode_map from Project.notebook_stub import project_server, project_port import pprint zipcodeJoined = audit_zipcode_map(project_server, project_port, quiet=True) pprint.pprint(zipcodeJoined[1:10]+['...'])
.ipynb_checkpoints/Data Analysis Project 3 - Data Wrangle OpenStreetMaps Data-checkpoint.ipynb
qwertzuhr/2015_Data_Analyst_Project_3
agpl-3.0
Post-training integer quantization with int16 activations <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/lite/performance/post_training_quant_16x8"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> ...
import logging logging.getLogger("tensorflow").setLevel(logging.DEBUG) import tensorflow as tf from tensorflow import keras import numpy as np import pathlib
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Check that the 16x8 quantization mode is available
tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Train and export the model
# Load MNIST dataset mnist = keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # Normalize the input image so that each pixel value is between 0 to 1. train_images = train_images / 255.0 test_images = test_images / 255.0 # Define the model architecture model = keras.Seq...
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
For the example, you trained the model for just a single epoch, so it only trains to ~96% accuracy. Convert to a TensorFlow Lite model Using the Python TFLiteConverter, you can now convert the trained model into a TensorFlow Lite model. Now, convert the model using TFliteConverter into default float32 format:
converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert()
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Write it out to a .tflite file:
tflite_models_dir = pathlib.Path("/tmp/mnist_tflite_models/") tflite_models_dir.mkdir(exist_ok=True, parents=True) tflite_model_file = tflite_models_dir/"mnist_model.tflite" tflite_model_file.write_bytes(tflite_model)
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
To instead quantize the model to 16x8 quantization mode, first set the optimizations flag to use default optimizations. Then specify that 16x8 quantization mode is the required supported operation in the target specification:
converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8]
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
As in the case of int8 post-training quantization, it is possible to produce a fully integer quantized model by setting converter options inference_input(output)_type to tf.int16. Set the calibration data:
mnist_train, _ = tf.keras.datasets.mnist.load_data() images = tf.cast(mnist_train[0], tf.float32) / 255.0 mnist_ds = tf.data.Dataset.from_tensor_slices((images)).batch(1) def representative_data_gen(): for input_value in mnist_ds.take(100): # Model has only one input so each data point has one element. yield ...
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Finally, convert the model as usual. Note, by default the converted model will still use float input and outputs for invocation convenience.
tflite_16x8_model = converter.convert() tflite_model_16x8_file = tflite_models_dir/"mnist_model_quant_16x8.tflite" tflite_model_16x8_file.write_bytes(tflite_16x8_model)
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Note how the resulting file is approximately 1/3 the size.
!ls -lh {tflite_models_dir}
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Run the TensorFlow Lite models Run the TensorFlow Lite model using the Python TensorFlow Lite Interpreter. Load the model into the interpreters
interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file)) interpreter.allocate_tensors() interpreter_16x8 = tf.lite.Interpreter(model_path=str(tflite_model_16x8_file)) interpreter_16x8.allocate_tensors()
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Test the models on one image
test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32) input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] interpreter.set_tensor(input_index, test_image) interpreter.invoke() predictions = interpreter.get_tensor(output_index) import m...
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Evaluate the models
# A helper function to evaluate the TF Lite model using "test" dataset. def evaluate_model(interpreter): input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] # Run predictions on every image in the "test" dataset. prediction_digits = [] for tes...
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0
Repeat the evaluation on the 16x8 quantized model:
# NOTE: This quantization mode is an experimental post-training mode, # it does not have any optimized kernels implementations or # specialized machine learning hardware accelerators. Therefore, # it could be slower than the float interpreter. print(evaluate_model(interpreter_16x8))
tensorflow/lite/g3doc/performance/post_training_integer_quant_16x8.ipynb
davidzchen/tensorflow
apache-2.0