-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutility.py
More file actions
228 lines (177 loc) · 7.55 KB
/
utility.py
File metadata and controls
228 lines (177 loc) · 7.55 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import pandas as pd
from datetime import datetime
import numpy as np
import re
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
from matplotlib import pyplot
import seaborn as sn
from sklearn.metrics import roc_auc_score
from scipy.stats import pearsonr
import csv
import statsmodels.api as sm
from sklearn import tree
from matplotlib import pyplot as plt
import graphviz
features_to_display = 5
from sklearn.utils import resample
import gensim
from gensim.models import word2vec
from sklearn.manifold import TSNE
def logisticRegression(X_train, X_test, y_train, y_test, features):
# define the model
model = LogisticRegression()
# fit the model
model.fit(X_train, y_train)
y_pred = model.predict_proba(X_test)[:, 1]
# score = roc_auc_score(y_test, y_pred)
score = model.score(X_test, y_test)
# get importance for class True (1)
importance = model.coef_
feature_importance = []
for i, j in enumerate(importance):
sorted_index = sorted(range(len(j)), key=j.__getitem__, reverse=True)
for index in range(features_to_display):
feature_index = sorted_index[index]
feature_importance.append(features[feature_index])
return score
def decisionTree(X_train, X_test, y_train, y_test, features):
# define the model
model = DecisionTreeClassifier()
# fit the model
model.fit(X_train, y_train)
y_pred = model.predict_proba(X_test)[:, 1]
# score = roc_auc_score(y_test, y_pred)
score = model.score(X_test, y_test)
# get importance for class True (1)
importance = model.feature_importances_
feature_importance = []
sorted_index = sorted(range(len(importance)), key=importance.__getitem__, reverse=True)
for index in range(features_to_display):
feature_index = sorted_index[index]
feature_importance.append(features[feature_index])
return score
def randomForestClassifier(X_train, X_test, y_train, y_test, features):
# define the model
model = RandomForestClassifier()
# fit the model
model.fit(X_train, y_train)
y_pred = model.predict_proba(X_test)[:, 1]
y_pred_1 = model.predict(X_test)
score = accuracy_score(y_test, y_pred_1)
# score = roc_auc_score(y_test, y_pred)
score = model.score(X_test, y_test)
# get importance for class True (1)
importance = model.feature_importances_
feature_importance = []
sorted_index = sorted(range(len(importance)), key=importance.__getitem__, reverse=True)
for index in range(features_to_display):
feature_index = sorted_index[index]
feature_importance.append(features[feature_index])
return score
def gradientBoostingClassifier(X_train, X_test, y_train, y_test, features):
# define the model
model = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, max_depth=1, random_state=0)
# fit the model
model.fit(X_train, y_train)
y_pred = model.predict_proba(X_test)[:, 1]
y_pred_1 = model.predict(X_test)
score = accuracy_score(y_test, y_pred_1)
# score = roc_auc_score(y_test, y_pred)
score = model.score(X_test, y_test)
# get importance for class True (1)
importance = model.feature_importances_
feature_importance = []
sorted_index = sorted(range(len(importance)), key=importance.__getitem__, reverse=True)
for index in range(features_to_display):
feature_index = sorted_index[index]
feature_importance.append(features[feature_index])
return score
def xgbc(X_train, X_test, y_train, y_test, features):
# define the model
model = XGBClassifier()
# fit the model
model.fit(X_train, y_train)
#y_pred = model.predict_proba(X_test)[:, 1]
#score = roc_auc_score(y_test, y_pred)
y_pred = model.predict(X_test)
score = accuracy_score(y_test, y_pred)
y_pred_1 = model.predict(X_test)
score = accuracy_score(y_test, y_pred_1)
# get importance for class True (1)
importance = model.feature_importances_
feature_importance = []
sorted_index = sorted(range(len(importance)), key=importance.__getitem__, reverse=True)
for index in range(features_to_display):
feature_index = sorted_index[index]
feature_importance.append(features[feature_index])
return score
def pre_process_string_to_num(df, word_to_num=None):
if type(df).__module__ != np.__name__:
df = df.fillna('')
df = df.to_numpy()
# converting strings
if word_to_num is None:
word_to_num = {}
count = np.empty(shape=df.shape[1], dtype=int)
for s in range(count.shape[0]):
count[s] = 0
for i in range(0, df.shape[0]):
for j in range(df.shape[1]):
try:
df[i, j] = float(df[i, j])
except:
key = (j, df[i, j])
if key not in word_to_num:
word_to_num[key] = count[j]
count[j] = count[j] + 1
df[i, j] = float(word_to_num[key])
return df, word_to_num
def analyse_data(csv_name, label):
df = pd.read_csv(csv_name)
column_names = df.keys()
print(column_names)
df, word_to_num = pre_process_string_to_num(df)
df = pd.DataFrame(df, columns=column_names)
y = df[label].astype('int')
X = df.drop(label, axis=1)
features = X.keys()
print(X.shape)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
print(X_train.shape)
ML_models = ["logisticRegression", "decisionTree", "RandomForestClassifier", "GradientBoostingClassifier", "XGBoost"]
print("Original")
lr_result = logisticRegression(X_train, X_test, y_train, y_test, features)
print(ML_models[0] + ":" + str(lr_result) + "\n")
dt_result = decisionTree(X_train, X_test, y_train, y_test, features)
print(ML_models[1] + ":" + str(dt_result) + "\n")
rfc_result = randomForestClassifier(X_train, X_test, y_train, y_test, features)
print(ML_models[2] + ":" + str(rfc_result) + "\n")
gbc_result = gradientBoostingClassifier(X_train, X_test, y_train, y_test, features)
print(ML_models[3] + ":" + str(gbc_result) + "\n")
"""xgbc_result = xgbc(X_train, X_test, y_train, y_test, features)
print(ML_models[4] + ":" + str(xgbc_result) + "\n")"""
df_new = pd.read_csv("./synthetic_table/farmer_survey_synthetic_without_privacy.csv")
column_names = df.keys()
df_new = pre_process_string_to_num(df_new, word_to_num)[0]
df_new = pd.DataFrame(df_new, columns=column_names)
y_train = df_new[label].astype('int')
X_train = df_new.drop(label, axis=1)
print("Synthetic")
lr_result = logisticRegression(X_train, X_test, y_train, y_test, features)
print(ML_models[0] + ":" + str(lr_result) + "\n")
dt_result = decisionTree(X_train, X_test, y_train, y_test, features)
print(ML_models[1] + ":" + str(dt_result) + "\n")
rfc_result = randomForestClassifier(X_train, X_test, y_train, y_test, features)
print(ML_models[2] + ":" + str(rfc_result) + "\n")
gbc_result = gradientBoostingClassifier(X_train, X_test, y_train, y_test, features)
print(ML_models[3] + ":" + str(gbc_result) + "\n")
"""xgbc_result = xgbc(X_train, X_test, y_train, y_test, features)
print(ML_models[4] + ":" + str(xgbc_result) + "\n")"""
analyse_data("./data/farmer_survey.csv", "household_type")