<jupyter_start><jupyter_text>Building Predictive models<jupyter_code>import os
import numpy as np
import pandas as pd<jupyter_output><empty_output><jupyter_text>Import data<jupyter_code># path of the processed data
processed_data_path = os.path.join(os.path.pardir,'data','processed')
train_data_path = os.path.join(processed_data_path,'train.csv')
test_data_path = os.path.join(processed_data_path,'test.csv')
train_df = pd.read_csv(train_data_path,index_col='PassengerId')
test_df = pd.read_csv(test_data_path,index_col='PassengerId')
train_df.info()
test_df.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
Int64Index: 418 entries, 892 to 1309
Data columns (total 32 columns):
Age                        418 non-null float64
Fare                       418 non-null float64
FamilySize                 418 non-null int64
IsMother                   418 non-null int64
IsMale                     418 non-null int64
Deck_A                     418 non-null int64
Deck_B                     418 non-null int64
Deck_C                     418 non-null int64
Deck_D                     418 non-null int64
Deck_E                     418 non-null int64
Deck_F                     418 non-null int64
Deck_G                     418 non-null int64
Deck_z                     418 non-null int64
Pclass_1                   418 non-null int64
Pclass_2                   418 non-null int64
Pclass_3                   418 non-null int64
Title_Lady                 418 non-null int64
Title_Master               418 non-null int64
Title_Miss                 418 non-null int64
Title_Mr      [...]<jupyter_text>Data Preparation<jupyter_code># creating the matrix
# here we considered all the rows and all columns beginning from Age thus we did not consider Survived here
# the value is then converted to float
X = train_df.loc[:,'Age':].as_matrix().astype('float')
y = train_df['Survived'].ravel()<jupyter_output><empty_output><jupyter_text>upper case letter for matrix and lower case letter for 1D array<jupyter_code>print(X.shape,y.shape)<jupyter_output>(891, 32) (891,)<jupyter_text>Train test Split<jupyter_code>from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)
print(X_train.shape,y_train.shape)
print(X_test.shape,y_test.shape)
# survival in train and test
print('mean survival in train: {0:.3f}'.format(np.mean(y_train)))
print('mean survival in test: {0:.3f}'.format(np.mean(y_test)))<jupyter_output>mean survival in train: 0.383
mean survival in test: 0.385<jupyter_text>Check scikit version<jupyter_code>import sklearn
sklearn.__version__<jupyter_output><empty_output><jupyter_text>Baseline Model<jupyter_code>from sklearn.dummy import DummyClassifier 
# create model
model_dummy = DummyClassifier(strategy='most_frequent',random_state=0)
# train model
model_dummy.fit(X_train,y_train)
# obtaining the score
print('score for baseline model: {0:.2f}'.format(model_dummy.score(X_test,y_test)))
# performance metrics
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score
# accuracy score which is same as baseline model score
print('accuracy for baseline model: {0:.2f}'.format(accuracy_score(y_test,model_dummy.predict(X_test))))
print('confusion matrix for baseline model: \n {0}'.format(confusion_matrix(y_test,model_dummy.predict(X_test))))
print('precision for baseline model: {0:.2f}'.format(precision_score(y_test,model_dummy.predict(X_test))))
print('Recall for baseline model: {0:.2f}'.format(recall_score(y_test,model_dummy.predict(X_test))))<jupyter_output>Recall for baseline model: 0.00<jupyter_text>First Kaggle submission<jupyter_code># preparing the actual test data
test_X = test_df.as_matrix().astype('float')
predictions = model_dummy.predict(test_X)
df_submission = pd.DataFrame({'PassengerId':test_df.index,'Survived' : predictions})
df_submission.head()
submission_data_path = os.path.join(os.path.pardir,'data','external')
submission_file_path = os.path.join(submission_data_path,'01_dummy.csv')
df_submission.to_csv(submission_file_path,index=False)
def get_submission_file(model,filename):
    test_X = test_df.as_matrix().astype('float')
    predictions = model.predict(test_X)
    df_submission = pd.DataFrame({'PassengerId': test_df.index,'Survived': predictions})
    submission_data_path = os.path.join(os.path.pardir,'data','external')
    submission_file_path = os.path.join(submission_data_path,filename)
    df_submission.to_csv(submission_file_path,index=False)
get_submission_file(model_dummy,'01_dummy.csv')<jupyter_output><empty_output><jupyter_text>Logistic Regression<jupyter_code>from sklearn.linear_model import LogisticRegression
model_lr_1 = LogisticRegression(random_state=0)
model_lr_1.fit(X_train,y_train)
print('score for logistic regression - version 1: {0:.2f}'.format(model_lr_1.score(X_test,y_test)))
print('accuracy for logistic regression model: {0:.2f}'.format(accuracy_score(y_test,model_lr_1.predict(X_test))))
print('confusion matrix for logistic regression model: \n {0}'.format(confusion_matrix(y_test,model_lr_1.predict(X_test))))
print('precision for logistic regression model: {0:.2f}'.format(precision_score(y_test,model_lr_1.predict(X_test))))
print('Recall for logistic regression model: {0:.2f}'.format(recall_score(y_test,model_lr_1.predict(X_test))))
# model coefficients
model_lr_1.coef_<jupyter_output><empty_output><jupyter_text>Second Kaggle submission<jupyter_code>get_submission_file(model_lr_1,'02_lr.csv')<jupyter_output><empty_output><jupyter_text>Part 2  Hyperparameter Optimization<jupyter_code>model_lr = LogisticRegression(random_state=0)
from sklearn.model_selection import GridSearchCV
parameters = {'C':[1.0,10.0,50.0,100.0,1000.0], 'penalty' : ['l1','l2']}
clf = GridSearchCV(model_lr,param_grid=parameters,cv=3) # 3-fold cross-validation
clf.fit(X_train,y_train)
clf.best_params_
print('best score : {0:.2f}'.format(clf.best_score_))
print('score for logistic regression - version 2: {0:.2f}'.format(clf.score(X_test,y_test)))<jupyter_output>score for logistic regression - version 2: 0.83<jupyter_text>Third Kaggle Submission<jupyter_code>get_submission_file(clf,'03_lr.csv')<jupyter_output><empty_output><jupyter_text>Feature normalization and standardization  Feature Normalization<jupyter_code>from sklearn.preprocessing import MinMaxScaler,StandardScaler
 scaler = MinMaxScaler()
 X_train_scaled = scaler.fit_transform(X_train)
 X_train_scaled[:,0].min(),X_train_scaled[:,0].max()
 X_test_scaled = scaler.transform(X_test) # normalize test data<jupyter_output><empty_output><jupyter_text>Feature Standardization<jupyter_code>scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)<jupyter_output><empty_output><jupyter_text>Create model after standardization<jupyter_code>model_lr_2 = LogisticRegression()
parameters = {'C':[0.5,1.0,10.0,50.0,100.0,1000.0],'penalty':['l1','l2']}
clf = GridSearchCV(model_lr_2,param_grid=parameters,cv=3)
clf.fit(X_train_scaled,y_train)
clf.best_params_
clf.best_score_
print('score for standardized model - version 2 : {0:.2f}'.format(clf.score(X_test_scaled,y_test)))<jupyter_output>score for standardized model - version 2 : 0.84<jupyter_text>Model Persistence<jupyter_code>import pickle
model_file_path = os.path.join(os.path.pardir,'models','lr_model.pkl')
scaler_file_path = os.path.join(os.path.pardir,'models','lr_scaler.pkl')
# opening the file in binary format
model_file_pickle = open(model_file_path,'wb')
scaler_file_pickle = open(scaler_file_path,'wb')
pickle.dump(clf,model_file_pickle)
pickle.dump(scaler,scaler_file_pickle)
model_file_pickle.close()
scaler_file_pickle.close()<jupyter_output><empty_output><jupyter_text>load the persisted file<jupyter_code>model_file_pickle = open(model_file_path,'rb')
scaler_file_pickle = open(scaler_file_path,'rb')
clf_loaded = pickle.load(model_file_pickle)
scaler_loaded = pickle.load(scaler_file_pickle)
model_file_pickle.close()
scaler_file_pickle.close()
clf_loaded
scaler_loaded
X_test_scaled = scaler_loaded.transform(X_test)
print('score for persisted logistic regression: {0:.2f}'.format(clf_loaded.score(X_test_scaled,y_test)))<jupyter_output>score for persisted logistic regression: 0.84
StarcoderdataJupyterStructuredCleanDedup