<jupyter_start><jupyter_text>Building Predictive Models<jupyter_code>import pandas as pd
import os
import numpy as np<jupyter_output><empty_output><jupyter_text>Import Data<jupyter_code>#set the path of the processed data
processed_data_path = os.path.join(os.path.pardir,'data','processed')
train_file_path = os.path.join(processed_data_path,'train.csv')
test_file_path = os.path.join(processed_data_path,'test.csv')
#create train and test dataframes using pandas
train_df = pd.read_csv(train_file_path,index_col='PassengerId')
test_df = pd.read_csv(test_file_path,index_col='PassengerId')
train_df.columns()
#See info on dataframes to check if everything is ok
train_df.info()
test_df.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
Int64Index: 418 entries, 892 to 1309
Data columns (total 32 columns):
 #   Column              Non-Null Count  Dtype  
---  ------              --------------  -----  
 0   Age                 418 non-null    float64
 1   Fare                418 non-null    float64
 2   FamilySize          418 non-null    int64  
 3   IsMother            418 non-null    int64  
 4   IsMale              418 non-null    int64  
 5   Deck_A              418 non-null    int64  
 6   Deck_B              418 non-null    int64  
 7   Deck_C              418 non-null    int64  
 8   Deck_D              418 non-null    int64  
 9   Deck_E              418 non-null    int64  
 10  Deck_F              418 non-null    int64  
 11  Deck_G              418 non-null    int64  
 12  Deck_Z              418 non-null    int64  
 13  Pclass_1            418 non-null    int64  
 14  Pclass_2            418 non-null    int64  
 15  Pclass_3            418 non-null    int64  
 16  Title[...]<jupyter_text>Data Preparation<jupyter_code>X = train_df.loc[:,'Age':].to_numpy().astype('float') #input matrix
y = train_df['Survived'].ravel() #output array
print (X.shape, y.shape)
#ML train test split 80/20 (80% will be used to train, 20% to test)
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)
#average survival in train and test, without ML 
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>Baseline Model<jupyter_code>import sklearn
#import function
from sklearn.dummy import DummyClassifier
#create a model
model_dummy = DummyClassifier(strategy='most_frequent',random_state=0)
#train a model
model_dummy.fit(X_train,y_train) #input,output params are necessary for fit training function
#calculate model score (baseline considers most frequent data, a.k.a 0 == non survived titanic)
print('score for baseline model : {0:.2f}'.format(model_dummy.score(X_test,y_test)))
#So, without any ML algorithm, if we simply predict that a passenger in the titanic disaster dies, we will be right in 61% of the cases
#let's try to improve that with ML! 
#First, lets import some performance metrics
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score
#accuracy score
print('accuracy for baseline model : {0:.2f}'.format(accuracy_score(y_test,model_dummy.predict(X_test))))
#confusion matrix
print('confusion matrix for baseline model : \n {0}'.format(confusion_matrix(y_test,model_dummy.predict(X_test))))
#precision and recall scores
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>precision for baseline model : 0.00
recall for baseline model : 0.00<jupyter_text>First Kaggle Submission - Baseline Data<jupyter_code>#converting to the matrix
test_X = test_df.to_numpy().astype('float')
#get predictions
predictions = model_dummy.predict(test_X)
#submission dataframe
df_submission = pd.DataFrame({'PassengerId' : test_df.index, 'Survived' : predictions})
df_submission.head()
#submission file
submission_data_path = os.path.join(os.path.pardir,'data','external')
submission_file_path = os.path.join(submission_data_path,'01_dummy.csv')
#write to the file
df_submission.to_csv(submission_file_path,index=False)
def get_submission_file(model,filename):
    #converting to the matrix
    test_X = test_df.to_numpy().astype('float')
    #get predictions
    predictions = model.predict(test_X)
    #submission dataframe
    df_submission = pd.DataFrame({'PassengerId' : test_df.index, 'Survived' : predictions})
    #submission file
    submission_data_path = os.path.join(os.path.pardir,'data','external')
    submission_file_path = os.path.join(submission_data_path,filename)
    #write to the file
    df_submission.to_csv(submission_file_path,index=False)
    
#use the method we created above with all steps to get the submission file
get_submission_file(model_dummy,'01_dummy.csv')<jupyter_output><empty_output><jupyter_text>Logistic Regression Model<jupyter_code>#import logistic regression function from sklearn
from sklearn.linear_model import LogisticRegression
#create our model 
model_lr_1 = LogisticRegression(random_state=0)
#train our model
model_lr_1.fit(X_train,y_train)
#evaluate model
print('score for logistic regression - version 1 : {0:.2f}'.format(model_lr_1.score(X_test,y_test)))
#performance metrics

#accuracy score
print('accuracy for logistic regression v1 model : {0:.2f}'.format(accuracy_score(y_test,model_lr_1.predict(X_test))))
#confusion matrix
print('confusion matrix for logistic regression v1 model : \n {0}'.format(confusion_matrix(y_test,model_lr_1.predict(X_test))))
#precision 
print('precision for logistic regression v1 model : {0:.2f}'.format(precision_score(y_test,model_lr_1.predict(X_test))))
#recall
print('recall for logistic regression v1 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
get_submission_file(model_lr_1,'02_lr.csv')<jupyter_output><empty_output><jupyter_text>Part 2  Hyperparameter Optimization<jupyter_code># base model
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)
clf.fit(X_train,y_train)
clf.best_params_
print('best score: {0:.2f}'.format(clf.best_score_))
#evaluate model
print('score for logistic regression v2 : {0:.2f}'.format(clf.score(X_test,y_test)))<jupyter_output>score for logistic regression v2 : 0.83<jupyter_text>Making thrird Kaggle Submission<jupyter_code>#get submission file
get_submission_file(clf,'04_lr.csv')<jupyter_output><empty_output><jupyter_text>Feature Normalization and Standardization<jupyter_code>#import functions
from sklearn.preprocessing import MinMaxScaler, StandardScaler<jupyter_output><empty_output><jupyter_text>Feature Normalization - put features in similar scale!<jupyter_code>scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
#check in one column the min and max of our scale
X_train_scaled[:,0].min(),X_train_scaled[:,0].max()
#normalize test data
X_test_scaled = scaler.transform(X_test)<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>#base model
model_lr = LogisticRegression(random_state=0)
parameters = {'C':[1.0,10.0,50.0,100.0,1000.0],'penalty':['l1','l2']}
clf = GridSearchCV(model_lr,param_grid=parameters,cv=3)
clf.fit(X_train_scaled,y_train)
print('best score: {0:.2f}'.format(clf.best_score_))
#evaluate model
print('score for logistic regression v2 - standardized : {0:.2f}'.format(clf.score(X_test_scaled,y_test)))<jupyter_output>score for logistic regression v2 - standardized : 0.84<jupyter_text>Model Persistence<jupyter_code>#import pickle lib to persist our model to the disk
import pickle
#create the file path
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')
#open the files to write
model_file_pickle = open(model_file_path,'wb') #wb = write bytes
scaler_file_pickle = open(scaler_file_path,'wb')
#persist model and scaler to the disk using pickle
pickle.dump(clf,model_file_pickle)
pickle.dump(scaler,scaler_file_pickle)
#close the files
model_file_pickle.close()
scaler_file_pickle.close()<jupyter_output><empty_output><jupyter_text>load the persisted file<jupyter_code>#open the files in read mode
model_file_pickle = open(model_file_path,'rb') #rb = read bytes
scaler_file_pickle = open(scaler_file_path,'rb')
#load files
clf_loaded = pickle.load(model_file_pickle)
scaler_loaded = pickle.load(scaler_file_pickle)
#close files
model_file_pickle.close()
scaler_file_pickle.close()
clf_loaded
scaler_loaded
#transform the test data using loaded scaler object
X_test_scaled = scaler_loaded.transform(X_test)
#calculate the score using loaded model object
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
{'fraction_non_alphanumeric': 0.10852876222526028, 'fraction_numerical': 0.027658008202755286, 'mean_word_length': 5.73036093418259, 'pattern_counts': {'":': 0, '<': 56, '<?xml version=': 0, '>': 56, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '332255', 'license': 'MIT', 'n_tokens_mistral': 3471, 'n_tokens_neox': 3254, 'n_words': 706, 'path': 'notebooks/3 - Building a predictive model.ipynb', 'repo_name': 'gutospinelli/titanic', 'size': '9509'}