<jupyter_start><jupyter_text>Building Predictive Models<jupyter_code>import pandas as pd
import numpy as np
import os<jupyter_output><empty_output><jupyter_text>Import Data<jupyter_code># set path of processed data
processed_data = os.path.join(os.path.pardir,'data', 'processed')
train_file = os.path.join(processed_data, 'train.csv')
test_file = os.path.join(processed_data, 'test.csv')
train_df = pd.read_csv(train_file, index_col = 'PassengerId')
test_df = pd.read_csv(test_file, 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              418 non-null int64
Title_Mrs             418 non-null int64
Title_Officer         418 n[...]<jupyter_text>Data Prep<jupyter_code>X = train_df.loc[:, 'Age':].as_matrix().astype('float')
y = train_df['Survived'].ravel()
print(X.shape, y.shape)
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
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-learn version<jupyter_code>import sklearn
sklearn.__version__<jupyter_output><empty_output><jupyter_text>Baseline model<jupyter_code># import function
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)
print('score for baseline', model_dummy.score(X_test, y_test))
from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix
# accuracy_score
print('accuracy is : {0}'.format(accuracy_score(y_test, model_dummy.predict(X_test))))
# confusion_matrix
print('confusion matrix is : \n {0}'.format(confusion_matrix(y_test, model_dummy.predict(X_test))))
# precision and recall scores
print('precision is : {0}'.format(precision_score(y_test, model_dummy.predict(X_test))))
print('recall is : {0}'.format(recall_score(y_test, model_dummy.predict(X_test))))<jupyter_output>precision is : 0.0
recall is : 0.0<jupyter_text>First Kaggle Submission<jupyter_code># converting to matrix
test_X = test_df.as_matrix().astype('float')
# get predicitons
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):
    # converting to matrix
    test_X = test_df.as_matrix().astype('float')
    # get predicitons
    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 file
    df_submission.to_csv(submission_file_path, index=False)
# get submission file
get_submission_file(model_dummy, '01_dummy.csv')<jupyter_output>D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\ipykernel_launcher.py:3: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
  This is separate from the ipykernel package so we can avoid doing imports until<jupyter_text>Logistic Regression Model<jupyter_code>#import function
from sklearn.linear_model import LogisticRegression
# create model
model_lr_1 = LogisticRegression(random_state=0)
# train model
model_lr_1.fit(X_train, y_train)
# evauluate model
print('accuracy of logistic regression model - version 1: {0}'.format(model_lr_1.score(X_test, y_test)))
# confusion_matrix
print('confusion matrix is : \n {0}'.format(confusion_matrix(y_test, model_lr_1.predict(X_test))))
# precision and recall scores
print('precision is : {0}'.format(precision_score(y_test, model_lr_1.predict(X_test))))
print('recall is : {0}'.format(recall_score(y_test, model_lr_1.predict(X_test))))
# model coefficients
model_lr_1.coef_      # these are the model weights<jupyter_output><empty_output><jupyter_text>Second Kaggle Submission<jupyter_code>get_submission_file(model_lr_1, '02_lr.csv')<jupyter_output>D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\ipykernel_launcher.py:3: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
  This is separate from the ipykernel package so we can avoid doing imports until<jupyter_text>Part 2  Hyper parameter optimization<jupyter_code># base_model
model_lr = LogisticRegression(random_state=0)
from sklearn.model_selection import GridSearchCV
parameters = {'C': [1, 10, 100, 1000], 'penalty': ['l1', 'l2']}
clf = GridSearchCV(model_lr, param_grid=parameters, cv=3)
clf.fit(X_train, y_train)
clf.best_params_do
print('Best score is : {0}'.format(clf.best_score_))
# evaluate the model
print('The best score for the logistic regression model is : {0}'.format(clf.score(X_test, y_test)))<jupyter_output>The best score for the logistic regression model is : 0.8268156424581006<jupyter_text>Making third submission<jupyter_code>get_submission_file(clf, '03_lr.csv')<jupyter_output>D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\ipykernel_launcher.py:3: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
  This is separate from the ipykernel package so we can avoid doing imports until<jupyter_text>Feature Normalization and Standardization<jupyter_code>from sklearn.preprocessing import MinMaxScaler, StandardScaler<jupyter_output><empty_output><jupyter_text>Feature Normalization<jupyter_code>scaler = MinMaxScaler()
# normalize the train data
X_train_scaled_norm = scaler.fit_transform(X_train)
# normalize the test data
X_test_scaled_norm = scaler.transform(X_test)
X_train_scaled_norm[:,0].min(), X_train_scaled_norm[:,0].max()<jupyter_output><empty_output><jupyter_text>Feature Standardization<jupyter_code>scaler = StandardScaler()
# standardize the train data
X_train_scaled_stand = scaler.fit_transform(X_train)
# normalize the test data
X_test_scaled_stand = scaler.transform(X_test)
X_train_scaled_stand[:,0].min(), X_train_scaled_stand[:,0].max()<jupyter_output><empty_output><jupyter_text>Create model after scaling  After Normalization<jupyter_code>#### After Normalization

# base model
model_lr = LogisticRegression(random_state=0)
parameters = {'C': [1, 10, 100, 1000], 'penalty': ['l1', 'l2']}
clf = GridSearchCV(model_lr, param_grid=parameters, cv=3)
clf.fit(X_train_scaled_norm, y_train)

clf.best_score_

# evaluate performance
print('Score for logistic regression after feature normalization : {0}'.format(clf.score(X_test_scaled_norm, y_test)))<jupyter_output>Score for logistic regression after feature normalization : 0.8268156424581006<jupyter_text>After Standardization<jupyter_code>#### After Standardization

# base model
model_lr = LogisticRegression(random_state=0)
parameters = {'C': [1, 10, 100, 1000], 'penalty': ['l1', 'l2']}
clf = GridSearchCV(model_lr, param_grid=parameters, cv=3)
clf.fit(X_train_scaled_stand, y_train)

clf.best_score_

# evaluate performance
print('Score for logistic regression after feature standardization : {0}'.format(clf.score(X_test_scaled_stand, y_test)))<jupyter_output>D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\sklearn\linear_model\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\sklearn\linear_model\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\sklearn\linear_model\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\sklearn\linear_model\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-pa[...]<jupyter_text>Submitting the standardized model<jupyter_code>get_submission_file(clf, '04_Standardized_lr.csv')<jupyter_output>D:\Users\gianni.acquisto\AppData\Roaming\Python\Python37\site-packages\ipykernel_launcher.py:3: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
  This is separate from the ipykernel package so we can avoid doing imports until<jupyter_text>Model Persistance<jupyter_code>import pickle
# create the file paths
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 pickle files to write
model_file_pickle = open(model_file_path, 'wb')
scaler_file_pickle = open(scaler_file_path, 'wb')
# persist the model and scaler
pickle.dump(clf, model_file_pickle)
pickle.dump(scaler, scaler_file_pickle)
# close the file
model_file_pickle.close()
scaler_file_pickle.close()<jupyter_output><empty_output><jupyter_text>Load the persisted file<jupyter_code># open files in read mode
model_file_pickle = open(model_file_path, 'rb')
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 the loaded standard scaler object
X_test_scaled = scaler_loaded.transform(X_test)
# calculate the score using the loaded model object
print('Score for the persisted lr model : {}'.format(clf_loaded.score(X_test_scaled, y_test)))<jupyter_output>Score for the persisted lr model : 0.8435754189944135
{'fraction_non_alphanumeric': 0.1044962903369983, 'fraction_numerical': 0.02869401984446232, 'mean_word_length': 5.966376089663761, 'pattern_counts': {'":': 0, '<': 63, '<?xml version=': 0, '>': 63, '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': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '631375', 'license': 'MIT', 'n_tokens_mistral': 4063, 'n_tokens_neox': 3796, 'n_words': 826, 'path': 'notebooks/3 - Building Predictive Model.ipynb', 'repo_name': 'Gacqsto/titanic_disaster', 'size': '11187'}