We need an in-house testing system to validate our machine learning algorithm. We need this in order to iterate towards better solutions. I am basing this in-house testing system on the Yu et al. JMLR Workshop and Conference Proceedings paper that the winning team submitted. The leaderboard contains the full list of submissions and links to papers.
In the Yu et al. paper, the main reason why they built their own testing system instead of just submitting to their answers and having the KDD Cup server score it was to avoid overfitting the solution.
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
# Get the data: Algebra 2005-2006 (A56) and/or Algebra 2008-2009 (A89)
a56_train_filepath = 'data/algebra0506/algebra_2005_2006_train.txt'
#a89_train_filepath = 'data/algebra0809/algebra_2008_2009_train.txt'
a56data = pd.read_table(a56_train_filepath)
#a89data = pd.read_table(a89_train_filepath)
hierarchy = a56data['Problem Hierarchy']
units, sections = [], []
for i in range(len(hierarchy)):
units.append(hierarchy[i].split(',')[0].strip())
sections.append(hierarchy[i].split(',')[1].strip())
# Now add 'Units' and 'Sections' as columns within the dataframe
a56data['Problem Unit'] = pd.Series(units, index=a56data.index)
a56data['Problem Section'] = pd.Series(sections, index=a56data.index)
# Rearrange order of columns
cols = a56data.columns.tolist()
cols = cols[0:3]+cols[-2::]+cols[3:-2]
a56data = a56data[cols]
df = a56data
students = set(a56data['Anon Student Id'])
print 'There are {0} students, so we will be adding as many columns to this dataframe.'.format(len(students))
There are 574 students, so we will be adding as many columns to this dataframe.
numrows = len(df)
# Add a column for every student and fill them with zeros
for stud in students:
df[stud] = pd.Series(np.zeros(numrows), index=df.index)
# For each student's problem entries in the dataframe, mark their column as 1
for stud in students:
df.loc[df['Anon Student Id'] == stud,stud] = 1
np.shape(df)
(809694, 595)
units = set(a56data['Problem Unit'])
print 'There are {0} unique problem units, so we will be adding as many columns to this dataframe.'.format(len(units))
There are 32 unique problem units, so we will be adding as many columns to this dataframe.
numrows = len(df)
# Add a column for every problem unit and fill them with zeros
for u in units:
df[u] = pd.Series(np.zeros(numrows), index=df.index)
# For each student's attempt at a problem, mark the appropriate problem unit as 1
for u in units:
df.loc[df['Problem Unit'] == u,u] = 1
np.shape(df)
(809694, 627)
sections = set(a56data['Problem Section'])
print 'There are {0} unique problem sections, so we will be adding as many columns to this dataframe.'.format(len(sections))
There are 138 unique problem sections, so we will be adding as many columns to this dataframe.
numrows = len(df)
# Add a column for every problem unit and fill them with zeros
for s in sections:
df[s] = pd.Series(np.zeros(numrows), index=df.index)
# For each student's attempt at a problem, mark the appropriate problem unit as 1
for s in sections:
df.loc[df['Problem Section'] == s,s] = 1
np.shape(df)
(809694, 765)
pnames = set(a56data['Problem Name'])
print 'There are {0} unique problem names, so we will be adding as many columns to this dataframe.'.format(len(pnames))
There are 1084 unique problem names, so we will be adding as many columns to this dataframe.
numrows = len(df)
# Add a column for every problem unit and fill them with zeros
for n in pnames:
df[n] = pd.Series(np.zeros(numrows), index=df.index)
# For each student's attempt at a problem, mark the appropriate problem unit as 1
for n in pnames:
df.loc[df['Problem Name'] == n,n] = 1
np.shape(df)
(809694, 1849)
snames = set(a56data['Step Name'])
print 'There are {0} unique step names, so we will be adding as many columns to this dataframe.'.format(len(snames))
There are 187539 unique step names, so we will be adding as many columns to this dataframe.
numrows = len(df)
# Add a column for every problem unit and fill them with zeros
for n in snames:
df[n] = pd.Series(np.zeros(numrows), index=df.index)
# For each student's attempt at a problem, mark the appropriate problem unit as 1
for n in snames:
df.loc[df['Step Name'] == n,n] = 1
# Create an empty testing dataframe
testdf = pd.DataFrame(columns=df.columns)
# Create the testing set
for i in range(len(unique_units)):
# Get the last problem of the current problem unit
lastProb = list(df[df['Problem Unit'] == unique_units[i]]['Problem Name'])[-1]
# Get all the rows corresponding to the last problem for the given problem unit
lastProbRows = a56data[(df['Problem Unit'] == unique_units[i]) & (df['Problem Name']==lastProb)]
# Concatenate test dataframe with the rows just found
testdf = pd.concat([testdf,lastProbRows])
# Create a training dataframe that is equal to original dataframe with all the test cases removed
trainIndex = df.index - testdf.index
traindf = df.loc[trainIndex]
# Get the target feature within the test set: the Correct First Attmpt
CFAs = np.array(testdf['Correct First Attempt'])
# Define a helper function for calculating the root-mean-square error
def RMSE(p,y):
''' The Root-Mean-Square Error takes the predicted values p for the target
variable y and takes the square root of the mean of the square of their
differences. '''
return np.sqrt(np.sum(np.square(p-y))/len(y))
# Test the RMSE for an array of all zeros
p = np.zeros(len(CFAs))
print 'An array of all zeros gives an RMSE of:',RMSE(p,CFAs)
# Test the RMSE for an array of all ones
p = np.ones(len(CFAs))
print 'An array of all ones gives an RMSE of:',RMSE(p,CFAs)
# Test the RMSE for an array of random 0s and 1s
p = np.random.randint(0,2,len(CFAs)).astype(float)
print 'An array of random ones and zeros gives an RMSE of:',RMSE(p,CFAs)
An array of all zeros gives an RMSE of: 0.863841709437 An array of all ones gives an RMSE of: 0.503763338322 An array of random ones and zeros gives an RMSE of: 0.710079831105
# Define the logistic function
def logisfunc(x):
return 1.0 / (1.0 + np.exp(-x))
def logit_plots(X,y,model,feat_names):
num_samples = np.shape(X)[0]
num_features = np.shape(X)[1]
print num_samples, 'number of samples'
print num_features, 'number of features'
# The coefficients and bias of the decision function
coefs = model.coef_.ravel()
bias = model.intercept_
# Plot the decision function separately for each feature
x_plt = np.linspace(-1.0,1.0,300)
fig = plt.figure(figsize=(3*num_features,6))
for feat in range(num_features):
x = x_plt * coefs[feat] + bias
decs = logisfunc(x)
fig.add_subplot(num_features,1,feat+1)
plt.plot(X[:,feat],y,'x')
plt.plot(x_plt,decs)
plt.axis((0,1,0,1))
plt.xlabel(feat_names[feat])
plt.tight_layout()
def error_metrics(p,yy):
'''Calculates the error metrics, i.e. the precision and recall.
Precision = True positives / Predicted positives
Recall = True positives / Actual positives'''
predicted_positives = len(p[p==1])
actual_positives = len(yy[yy==1])
# The predicted values for when actual values are 1
pp = p[yy==1]
# True positives are when these predicted values are also 1
true_positives = len(pp[pp==1])
false_positives = len(yy) - true_positives
precision = float(true_positives) / float(predicted_positives)
recall = float(true_positives) / float(actual_positives)
F_1score = 2.0 * precision * recall / (precision + recall)
print 'Root-mean-square error: ', RMSE(p,yy)
print '\nPrecision: Of all predicted CFAs, what fraction actually succeeded?'
print precision
print '\nRecall: Of all actual CFAs, what fraction did we predict correctly?'
print recall
print '\nF_1 Score: ', F_1score
traindf.columns
Index([u'Row', u'Anon Student Id', u'Problem Hierarchy', u'Problem Unit', u'Problem Section', u'Problem Name', u'Problem View', u'Step Name', u'Step Start Time', u'First Transaction Time', u'Correct Transaction Time', u'Step End Time', u'Step Duration (sec)', u'Correct Step Duration (sec)', u'Error Step Duration (sec)', u'Correct First Attempt', u'Incorrects', u'Hints', u'Corrects', u'KC(Default)', u'Opportunity(Default)', u'OCmTg4ha6w', u'M7hLaVJGvX', u'6bJ4auIa8L', u'D08sSQFrq3', u'J76B3lyQG9', u'77y7iIIXuv', u'k37lfl6ENf', u'olyVui8lHe', u'verm1Wp12u', u'S7E3jvZbGG', u'cua2tdf6zb', u'3Whv9UbPsR', u'3EWyQLUo83', u'XqBaV46VbC', u'qN6WN7C097', u'm9a501e1MM', u'8FcKH1d6A2', u'8eqtD31y66', u'7y5NJZ7S6u', u'rA9d62o2bb', u'5gtqSDwEt1', u'6d2wZ1x370', u'oeTCjHG37z', u'HvghFVBS5v', u'1to8tgu4IT', u'UO70mRwd30', u'XrH5AAPdtj', u'TAw598sUia', u'pI9Tpj13ty', u'v52MhQAVT9', u'nybp7zY98z', u'yuB6nxh3FX', u'bt0ZuHaCGY', u'dD5k5322J5', u'2AMmebFl86', u'45euP7C062', u'QS4cvQ8w0o', u'Dmq6441349', u'NX8N2fJ630', u'9hs21hUG5O', u'a47O44klh3', u'45TTYcotWk', u'U50h3ZFmGt', u'Vu26QoCms4', u'WmIXxzmmD3', u'6jCygPdswz', u'SH1cSNDIA8', u'eD0u9WOep7', u'X5eS5kvC8h', u'X223hIsDU4', u'Vc0J7iVot4', u'c8Gl35DPn4', u'EfN583275t', u'MPqJdqnPtc', u'hwF4tyWU50', u'0U9x5pNv8t', u'5x5fHvFFLv', u'RwM69ocq8e', u'DZXDgO0B3u', u'5ddRYL0LBA', u'4ajdr1a4Kc', u'st945Ucdi6', u'D431zXkvuC', u'ajPRq0Q08b', u'b2W4ZO3uLV', u'NZJd9Aq3De', u'3hSu07XfGd', u'80nlN05JQ6', u'z2zuhnARi6', u'w0FMzJORlK', u'ey9rvMnU57', u'XNEgfvXx50', u'On0ILT6rt5', u'XGFd357i6u', u'XHm4u4Y8OU', u'jx1ndu85oq', u'dc35t0IQHq', u'8r7mHkuKX9', u'c6LS9kDJe1', ...], dtype='object')
# Define a helper function to normalize the feature matrix X
import numba
def autonorm(X):
''' Calculates the mean and range of values of each column
in the matrix (features) subtracts the mean from each value
and divides by the range, thereby normalizing all values to
fall between -1 and 1.'''
x_means = np.mean(X,axis=0)
x_means = np.ones(np.shape(X))*x_means
x_maxs = np.max(X,axis=0)
x_mins = np.min(X,axis=0)
x_range = x_maxs - x_mins
X_normd = (X - x_means) / x_range
return X_normd
autonorm_jit = numba.jit(autonorm)
features_to_norm = ['Step Duration (sec)','Hints','Problem View']
binary_features = list(students)+list(units)+list(sections)+list(pnames)#+list(snames)
target_feature = ['Correct First Attempt']
all_features = features_to_norm + binary_features + target_feature
X = traindf[all_features].dropna()
y = np.array(X[target_feature]).astype(int).ravel()
X_to_norm = np.array(X[features_to_norm])
X_nonnorm = np.array(X[binary_features])
X_to_norm = autonorm(X_to_norm)
X = np.concatenate((X_to_norm,X_nonnorm), axis=1)
XX = testdf[all_features].dropna()
yy = np.array(XX[target_feature]).astype(int).ravel()
XX_to_norm = np.array(XX[features_to_norm])
XX_nonnorm = np.array(XX[binary_features])
XX_to_norm = autonorm(XX_to_norm)
XX = np.concatenate((XX_to_norm,XX_nonnorm), axis=1)
from sklearn import linear_model
model = linear_model.LogisticRegression()
np.shape(X)
(760650, 577)
model.fit(X,y)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, penalty='l2', random_state=None, tol=0.0001)
p = model.predict(XX).astype(float)
error_metrics(p,yy)
Root-mean-square error: 0.401917482001 Precision: Of all predicted CFAs, what fraction actually succeeded? 0.831047542873 Recall: Of all actual CFAs, what fraction did we predict correctly? 0.983518472118 F_1 Score: 0.900877237721
np.shape(X)
(760650, 577)
len(students)
574
traindf.columns
Index([u'Row', u'Anon Student Id', u'Problem Hierarchy', u'Problem Unit', u'Problem Section', u'Problem Name', u'Problem View', u'Step Name', u'Step Start Time', u'First Transaction Time', u'Correct Transaction Time', u'Step End Time', u'Step Duration (sec)', u'Correct Step Duration (sec)', u'Error Step Duration (sec)', u'Correct First Attempt', u'Incorrects', u'Hints', u'Corrects', u'KC(Default)', u'Opportunity(Default)', u'OCmTg4ha6w', u'M7hLaVJGvX', u'6bJ4auIa8L', u'D08sSQFrq3', u'J76B3lyQG9', u'77y7iIIXuv', u'k37lfl6ENf', u'olyVui8lHe', u'verm1Wp12u', u'S7E3jvZbGG', u'cua2tdf6zb', u'3Whv9UbPsR', u'3EWyQLUo83', u'XqBaV46VbC', u'qN6WN7C097', u'm9a501e1MM', u'8FcKH1d6A2', u'8eqtD31y66', u'7y5NJZ7S6u', u'rA9d62o2bb', u'5gtqSDwEt1', u'6d2wZ1x370', u'oeTCjHG37z', u'HvghFVBS5v', u'1to8tgu4IT', u'UO70mRwd30', u'XrH5AAPdtj', u'TAw598sUia', u'pI9Tpj13ty', u'v52MhQAVT9', u'nybp7zY98z', u'yuB6nxh3FX', u'bt0ZuHaCGY', u'dD5k5322J5', u'2AMmebFl86', u'45euP7C062', u'QS4cvQ8w0o', u'Dmq6441349', u'NX8N2fJ630', u'9hs21hUG5O', u'a47O44klh3', u'45TTYcotWk', u'U50h3ZFmGt', u'Vu26QoCms4', u'WmIXxzmmD3', u'6jCygPdswz', u'SH1cSNDIA8', u'eD0u9WOep7', u'X5eS5kvC8h', u'X223hIsDU4', u'Vc0J7iVot4', u'c8Gl35DPn4', u'EfN583275t', u'MPqJdqnPtc', u'hwF4tyWU50', u'0U9x5pNv8t', u'5x5fHvFFLv', u'RwM69ocq8e', u'DZXDgO0B3u', u'5ddRYL0LBA', u'4ajdr1a4Kc', u'st945Ucdi6', u'D431zXkvuC', u'ajPRq0Q08b', u'b2W4ZO3uLV', u'NZJd9Aq3De', u'3hSu07XfGd', u'80nlN05JQ6', u'z2zuhnARi6', u'w0FMzJORlK', u'ey9rvMnU57', u'XNEgfvXx50', u'On0ILT6rt5', u'XGFd357i6u', u'XHm4u4Y8OU', u'jx1ndu85oq', u'dc35t0IQHq', u'8r7mHkuKX9', u'c6LS9kDJe1', ...], dtype='object')
len(set(traindf['Step Name']))
171886
len(traindf.columns)
595
params = model.get_params(deep=True)
params
{'C': 1.0, 'class_weight': None, 'dual': False, 'fit_intercept': True, 'intercept_scaling': 1, 'penalty': 'l2', 'random_state': None, 'tol': 0.0001}
T = model.predict_proba(X)
T
array([[ 0.70539268, 0.29460732], [ 0.18470565, 0.81529435], [ 0.45739163, 0.54260837], ..., [ 0.17350595, 0.82649405], [ 0.70812947, 0.29187053], [ 0.14044815, 0.85955185]])