utils.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import os
  2. import json
  3. import numpy as np
  4. import pandas as pd
  5. import dill as pickle
  6. from sklearn.externals import joblib
  7. from sklearn.model_selection import train_test_split, GridSearchCV
  8. from sklearn.base import BaseEstimator, TransformerMixin
  9. from sklearn.ensemble import RandomForestClassifier
  10. from sklearn.pipeline import make_pipeline
  11. import warnings
  12. warnings.filterwarnings("ignore")
  13. def build_and_train():
  14. data = pd.read_csv('../data/training.csv')
  15. data = data.dropna(subset=['Gender', 'Married', 'Credit_History', 'LoanAmount'])
  16. pred_var = ['Gender','Married','Dependents','Education','Self_Employed','ApplicantIncome','CoapplicantIncome',\
  17. 'LoanAmount','Loan_Amount_Term','Credit_History','Property_Area']
  18. X_train, X_test, y_train, y_test = train_test_split(data[pred_var], data['Loan_Status'], \
  19. test_size=0.25, random_state=42)
  20. y_train = y_train.replace({'Y':1, 'N':0}).as_matrix()
  21. y_test = y_test.replace({'Y':1, 'N':0}).as_matrix()
  22. pipe = make_pipeline(PreProcessing(),
  23. RandomForestClassifier())
  24. param_grid = {"randomforestclassifier__n_estimators" : [10, 20, 30],
  25. "randomforestclassifier__max_depth" : [None, 6, 8, 10],
  26. "randomforestclassifier__max_leaf_nodes": [None, 5, 10, 20],
  27. "randomforestclassifier__min_impurity_split": [0.1, 0.2, 0.3]}
  28. grid = GridSearchCV(pipe, param_grid=param_grid, cv=3)
  29. grid.fit(X_train, y_train)
  30. return(grid)
  31. class PreProcessing(BaseEstimator, TransformerMixin):
  32. """Custom Pre-Processing estimator for our use-case
  33. """
  34. def __init__(self):
  35. pass
  36. def transform(self, df):
  37. """Regular transform() that is a help for training, validation & testing datasets
  38. (NOTE: The operations performed here are the ones that we did prior to this cell)
  39. """
  40. pred_var = ['Gender','Married','Dependents','Education','Self_Employed','ApplicantIncome',\
  41. 'CoapplicantIncome','LoanAmount','Loan_Amount_Term','Credit_History','Property_Area']
  42. df = df[pred_var]
  43. df['Dependents'] = df['Dependents'].fillna(0)
  44. df['Self_Employed'] = df['Self_Employed'].fillna('No')
  45. df['Loan_Amount_Term'] = df['Loan_Amount_Term'].fillna(self.term_mean_)
  46. df['Credit_History'] = df['Credit_History'].fillna(1)
  47. df['Married'] = df['Married'].fillna('No')
  48. df['Gender'] = df['Gender'].fillna('Male')
  49. df['LoanAmount'] = df['LoanAmount'].fillna(self.amt_mean_)
  50. gender_values = {'Female' : 0, 'Male' : 1}
  51. married_values = {'No' : 0, 'Yes' : 1}
  52. education_values = {'Graduate' : 0, 'Not Graduate' : 1}
  53. employed_values = {'No' : 0, 'Yes' : 1}
  54. property_values = {'Rural' : 0, 'Urban' : 1, 'Semiurban' : 2}
  55. dependent_values = {'3+': 3, '0': 0, '2': 2, '1': 1}
  56. df.replace({'Gender': gender_values, 'Married': married_values, 'Education': education_values, \
  57. 'Self_Employed': employed_values, 'Property_Area': property_values, \
  58. 'Dependents': dependent_values}, inplace=True)
  59. return df.as_matrix()
  60. def fit(self, df, y=None, **fit_params):
  61. """Fitting the Training dataset & calculating the required values from train
  62. e.g: We will need the mean of X_train['Loan_Amount_Term'] that will be used in
  63. transformation of X_test
  64. """
  65. self.term_mean_ = df['Loan_Amount_Term'].mean()
  66. self.amt_mean_ = df['LoanAmount'].mean()
  67. return self
  68. if __name__ == '__main__':
  69. model = build_and_train()
  70. filename = 'model_v1.pk'
  71. with open('../flask_api/models/'+filename, 'wb') as file:
  72. pickle.dump(model, file)