-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
145 lines (104 loc) · 3.38 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
importing necessary libraries
"""
#Analysis packages
import numpy as np
import pandas as pd
#Visualization packages
import matplotlib.pyplot as plt
import seaborn as sns
#Machine Learning Packages
from sklearn.model_selection import train_test_split
from sklearn.metrics import mutual_info_score
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
import warnings
import pickle
warnings.filterwarnings("ignore")
"""
reading the data and checking the shape
"""
print("Loading data...")
try:
df = pd.read_csv("./data/creditcardmarketing-bbm.csv")
print("Loading successful")
except Exception as error:
print(error)
"""
Creating a copy of the dataset to be used for analysis
"""
data = df.copy()
data.columns = data.columns.str.lower().str.replace(" ", '_')
data.rename(columns={'#_bank_accounts_open':'bank_accounts_open', "#_homes_owned":"homes_owned",
'#_credit_cards_held':'credit_cards_held'}, inplace=True)
data['accepted_offer'] = (data['offer_accepted']=="Yes").astype(int)
del data['offer_accepted']
"""
dropping redundant columns
"""
data = data.drop(['index', 'customer_number'], axis=1)
"""
checking for missing values
"""
data.isnull().sum()
"""
dropping columns with missing values
"""
data.dropna(inplace=True)
numerical_cols = ['q1_balance', 'credit_cards_held',
'q2_balance', 'q3_balance', 'q4_balance', 'average_balance',
'household_size', 'bank_accounts_open', 'homes_owned']
categorical_cols = ['reward', 'mailer_type', 'income_level',
'overdraft_protection', 'credit_rating', 'own_your_home' ]
"""
Splitting the data
"""
df_full_train, df_test = train_test_split(data, test_size=0.2, random_state=1)
df_train, df_val = train_test_split(df_full_train, test_size=0.25, random_state=1)
y_full_train = df_full_train.accepted_offer.values
y_train = df_train.accepted_offer.values
y_val = df_val.accepted_offer.values
y_test = df_test.accepted_offer.values
del df_full_train['accepted_offer']
del df_train['accepted_offer']
del df_val['accepted_offer']
del df_test['accepted_offer']
def train(df, y):
"""
This function takes in a set of features and targets,
and fits them on a logistic regression model
params: features, target
returns: dict vectorizer, model objects
rtype: object
"""
train_dict = df.to_dict(orient='records')
dv = DictVectorizer()
X = dv.fit_transform(train_dict)
model = LogisticRegression(random_state=1)
model.fit(X, y)
return dv, model
def predict(df, dv, model):
"""
This function predicts a target class for a set of features
params: features, standard scaler and model objects
returns: target class
rtype: integer
"""
test_dict = df.to_dict(orient="records")
X = dv.transform(test_dict)
y_pred = model.predict(X)
return y_pred
"""
Evaluating model on test data
"""
dv, model = train(df_full_train, y_full_train)
y_pred = predict(df_test, dv, model)
round(accuracy_score(y_test, y_pred), 3)
#Saving the model
output_file = "model.bin"
with open(output_file, 'wb') as output_file:
pickle.dump((dv, model), output_file)
print(f"model successfully saved to {output_file}")