-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathregression_log_10features.py
190 lines (148 loc) · 4.87 KB
/
regression_log_10features.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
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
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix,
f1_score,
plot_confusion_matrix,
)
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
import utils
def draw_confusion_matrix(Clf, X, y):
titles_options = [
("Confusion matrix, without normalization", None),
("Rules Based Confusion matrix", "true"),
]
for title, normalize in titles_options:
disp = plot_confusion_matrix(Clf, X, y, cmap="RdPu", normalize=normalize)
disp.ax_.set_title(title)
plt.show()
class_name = ("album", "type")
df = utils.load_small_tracks(outliers=True, buckets="continuous")
df["album", "type"] = df["album", "type"].replace(
["Single Tracks", "Live Performance", "Radio Program"],
["NotAlbum", "NotAlbum", "NotAlbum"],
)
# feature to reshape
label_encoders = dict()
column2encode = [
("album", "type"),
]
for col in column2encode:
le = LabelEncoder()
df[col] = le.fit_transform(df[col])
label_encoders[col] = le
def normalize(feature):
scaler = StandardScaler()
df[feature] = scaler.fit_transform(df[[feature]])
colum2encode = [col for col in df.columns if col not in [("album", "type")]]
for col in colum2encode:
normalize(col)
print(df.info())
attributes = [col for col in df.columns if col != class_name]
X = df[attributes].values
y = df[class_name]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=100, stratify=y
)
clf = LogisticRegression(random_state=0, max_iter=1000, C=0.1, penalty="l2")
clf.fit(X_train, y_train)
# get importance
importance = clf.coef_[0]
# test
top_n = 10
feat_imp = pd.DataFrame(columns=["columns", "importance"])
for col, imp in zip(attributes, importance):
feat_imp = feat_imp.append({"columns": col, "importance": imp}, ignore_index=True)
print(feat_imp)
feat_imp = feat_imp.reindex(
feat_imp.importance.abs().sort_values(ascending=False).index
)
feat_imp = feat_imp.iloc[:top_n]
feat_imp.plot(
title="Top 10 coefficient of the features in the decision function",
x="columns",
fontsize=8.4,
rot=15,
y="importance",
kind="bar",
colormap="PiYG",
)
plt.axhline(y=0, color="b", linestyle="-")
plt.show()
# test
"""
n = -2
for col in df.columns:
n = n + 1
plt.scatter(X_train[:, n], y_train)
print("ok")
plt.xlabel(col, fontsize=16)
plt.ylabel('Album = 0 NotAlbum = 1', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show()
"""
# Apply the decision tree on the training set
print("Apply the decision tree on the training set: \n")
y_pred = clf.predict(X_train)
print("Accuracy %s" % accuracy_score(y_train, y_pred))
print("F1-score %s" % f1_score(y_train, y_pred, average=None))
print(classification_report(y_train, y_pred))
confusion_matrix(y_train, y_pred)
# Apply the decision tree on the test set and evaluate the performance
print("Apply the decision tree on the test set and evaluate the performance: \n")
y_pred = clf.predict(X_test)
print("Accuracy %s" % accuracy_score(y_test, y_pred))
print("F1-score %s" % f1_score(y_test, y_pred, average=None))
print(classification_report(y_test, y_pred))
draw_confusion_matrix(clf, X_test, y_test)
from sklearn.metrics import (
accuracy_score,
auc,
classification_report,
confusion_matrix,
f1_score,
roc_auc_score,
roc_curve,
)
fpr, tpr, _ = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)
print(roc_auc)
roc_auc = roc_auc_score(y_test, y_pred, average=None)
plt.figure(figsize=(8, 5))
plt.plot(fpr, tpr, label="ROC curve (area = %0.2f)" % (roc_auc))
plt.plot([0, 1], [0, 1], "k--")
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel("False Positive Rate", fontsize=20)
plt.ylabel("True Positive Rate", fontsize=20)
plt.tick_params(axis="both", which="major", labelsize=22)
plt.legend(loc="lower right", fontsize=14, frameon=False)
plt.show()
"""
n = -2
for col in df.columns:
n +=1
loss = expit(sorted(X_test[:, n]) * clf.coef_[:, n] + clf.intercept_).ravel()
plt.plot(sorted(X_test[:, n]), loss, color='red', linewidth=3)
plt.scatter(X_train[:, n], y_train)
plt.xlabel(col, fontsize=16)
plt.ylabel('Album Type', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show()
"""
"""
print("GRID SEARCH:")
# Grid search cross validation
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
grid={"C":np.logspace(-3,3,7), "penalty":['none' ,"l2"]}# l1 lasso l2 ridge
logreg=LogisticRegression(random_state=0, max_iter=1000)
logreg_cv=GridSearchCV(logreg,grid,cv=10)
logreg_cv.fit(X_train,y_train)
print("tuned hpyerparameters :(best parameters) ",logreg_cv.best_params_)
print("accuracy :",logreg_cv.best_score_)
"""