<jupyter_start><jupyter_text>Building Predictive Models - Part 1<jupyter_code>import pandas as pd
import numpy as np
import os<jupyter_output><empty_output><jupyter_text>Import Data<jupyter_code># set the path of 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')
train_df = pd.read_csv(train_file_path, index_col = 'PassengerId')
test_df = pd.read_csv(test_file_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 20 columns):
Pclass           418 non-null int64
AgeBand          418 non-null int64
FareBand         418 non-null int64
IsSenior         418 non-null int64
FamilySize       418 non-null int64
IsAlone          418 non-null int64
IsMother         418 non-null int64
IsMale           418 non-null int64
IsAdult          418 non-null int64
DeckLevel        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 non-null int64
Title_Sir        418 non-null int64
Embarked_C       418 non-null int64
Embarked_Q       418 non-null int64
Embarked_S       418 non-null int64
dtypes: int64(20)
memory usage: 68.6 KB<jupyter_text>Data Preparation<jupyter_code>X = train_df.loc[:, 'Pclass':].values.astype('float')
y = train_df['Survived'].ravel()
print(X.shape, y.shape)
# train test split
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:0.3f}'.format(np.mean(y_train)))
print('mean survival in test: {0: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>Make sure you have Scikit-Learn v0.19 or newer. Otherwise update it and restart kernel.<jupyter_code>#!conda update -y scikit-learn<jupyter_output><empty_output><jupyter_text>Baseline Model<jupyter_code># import function
from sklearn.dummy import DummyClassifier
# create baseline model
model_dummy = DummyClassifier(strategy = 'most_frequent', random_state = 0)
# train model
model_dummy.fit(X_train, y_train)
# default score - accuracy
print('score for baseline model: {0: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
print('accuracy for baseline model: {0: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:0.2f}'.format(precision_score(y_test, model_dummy.predict(X_test))))
print('recall for baseline model: {0: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<jupyter_code># converting to matrix
test_X = test_df.values.astype('float')
# get predictions
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')
print(submission_file_path)
df_submission.to_csv(submission_file_path, index = False)
def get_submission_file(model, filename, message):
    # converting to matrix
    test_X = test_df.values.astype('float')
    # make 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 file
    df_submission.to_csv(submission_file_path, index = False)
    # submit using Kaggle API
    from subprocess import call
    call(['kaggle', 'competitions', 'submit', 'titanic', '-f', submission_file_path, '-m', message])
# get submission file
get_submission_file(model_dummy, '01_dummy.csv', 'Baseline Model Submission')<jupyter_output><empty_output><jupyter_text>Logistic Regression Model<jupyter_code># import function
from sklearn.linear_model import LogisticRegression
# create model
model_lr_1 = LogisticRegression(random_state = 0, solver = 'liblinear')
# train model
model_lr_1.fit(X, y)
# evaluate model
print('score for logistic regression - version 1: {0:0.2f}'.format(model_lr_1.score(X_test, y_test)))
# performance metrics
# accuracy
print('accuracy for logistic regression - version 1: {0:0.2f}'.format(accuracy_score(y_test, model_lr_1.predict(X_test))))
# confusion matrix
print('confusion matrix logistic regression - version 1: \n {0}'.format(confusion_matrix(y_test, model_lr_1.predict(X_test))))
# precision
print('precision for logistic regression - version 1: {0:0.2f}'.format(precision_score(y_test, model_lr_1.predict(X_test))))
# recall
print('recall for logistic regression - version 1: {0: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', 'Logistic Regression Model v1 Submission')<jupyter_output><empty_output><jupyter_text>Building Predictive Models - Part 2  Hyperparameter Optimization<jupyter_code># base model
model_lr = LogisticRegression(random_state = 0, solver = 'liblinear')
# import function
from sklearn.model_selection import GridSearchCV
# create parameter grid
parameters = {
    'C': [ 0.1, 0.2, 0.5, 1.0, 10.0, 50.0, 100.0, 1000.0 ],
    'penalty': [ 'l1', 'l2' ]
}
clf = GridSearchCV(model_lr, param_grid = parameters, cv = 5) # 5-fold crossvalidation
clf.fit(X, y)
clf.best_params_
print('best score: {0:0.2f}'.format(clf.best_score_))
# evaluate model
print('score for logistic regression - version 2: {0:0.2f}'.format(clf.score(X_test, y_test)))<jupyter_output>score for logistic regression - version 2: 0.85<jupyter_text>Third Kaggle Submission<jupyter_code># get submission file
get_submission_file(clf, '03_lr.csv', 'Logistic Regression Model v2 Submission')<jupyter_output><empty_output><jupyter_text>Feature Normalization and Standardization<jupyter_code># import function
from sklearn.preprocessing import MinMaxScaler, StandardScaler<jupyter_output><empty_output><jupyter_text>Feature Normalization<jupyter_code># feature normalization
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
X_scaled[:,0].min(), X_scaled[:,0].max()
# normalize test data
X_test_scaled = scaler.transform(X_test)<jupyter_output><empty_output><jupyter_text>Create Model after Normalization<jupyter_code>model_lr = LogisticRegression(random_state = 0, solver = 'liblinear')
parameters = {
    'C': [ 0.1, 0.2, 0.5, 1.0, 10.0, 50.0, 100.0, 1000.0 ],
    'penalty': [ 'l1', 'l2' ]
}
clf = GridSearchCV(model_lr, param_grid = parameters, cv = 5)
clf.fit(X_scaled, y)
clf.best_params_
clf.best_score_
# evaluate model
print('score for logistic regression - after normalization: {0:0.2f}'.format(clf.score(X_test_scaled, y_test)))<jupyter_output>score for logistic regression - after normalization: 0.85<jupyter_text>Submit to Kaggle<jupyter_code># get submission file
get_submission_file(clf, '04_lr.csv', 'Logistic Regression Model (Post Normalization) Submission')<jupyter_output><empty_output><jupyter_text>Feature Standardization<jupyter_code># feature standardization
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_test_scaled = scaler.transform(X_test)<jupyter_output><empty_output><jupyter_text>Create Model after Standardization<jupyter_code>model_lr = LogisticRegression(random_state = 0, solver = 'liblinear')
parameters = {
    'C': [ 0.1, 0.2, 0.5, 1.0, 10.0, 50.0, 100.0, 1000.0 ],
    'penalty': [ 'l1', 'l2' ]
}
clf = GridSearchCV(model_lr, param_grid = parameters, cv = 5)
clf.fit(X_scaled, y)
clf.best_params_
clf.best_score_
# evaluate model
print('score for logistic regression - after standardization: {0:0.2f}'.format(clf.score(X_test_scaled, y_test)))<jupyter_output>score for logistic regression - after standardization: 0.85<jupyter_text>Submit to Kaggle<jupyter_code># get submission file
get_submission_file(clf, '05_lr.csv', 'Logistic Regression Model (Post Standardization) Submission')<jupyter_output><empty_output><jupyter_text>Model Persistance<jupyter_code># import pickle library
import pickle
# create file paths
model_file_path = os.path.join(os.path.pardir, 'models', 'lr_model.pkl')
print(model_file_path)
scaler_file_path = os.path.join(os.path.pardir, 'models', 'lr_scaler.pkl')
print(scaler_file_path)
# open 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 files
model_file_pickle.close()
scaler_file_pickle.close()<jupyter_output><empty_output><jupyter_text>Load Persisted Files<jupyter_code># open files in read mode
model_file_pickle = open(model_file_path, 'rb')
scaler_file_pickle = open(scaler_file_path, 'rb')

# load model and scaler
clf_loaded = pickle.load(model_file_pickle)
scaler_loaded = pickle.load(scaler_file_pickle)

# close the files
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:0.2f}'.format(clf_loaded.score(X_test_scaled, y_test)))<jupyter_output>score for persisted logistic regression: 0.85
{'fraction_non_alphanumeric': 0.1138527297454828, 'fraction_numerical': 0.030891781620361377, 'mean_word_length': 6.487272727272727, 'pattern_counts': {'":': 0, '<': 75, '<?xml version=': 0, '>': 75, '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': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '60302', 'license': 'MIT', 'n_tokens_mistral': 3865, 'n_tokens_neox': 3622, 'n_words': 778, 'path': 'notebooks/3.0-building-predictive-model.ipynb', 'repo_name': 'h36yang/python-data-science-demo', 'size': '10294'}