forked from UTA-DataScience/DATA3402.Spring.2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab8.py
287 lines (220 loc) · 8.61 KB
/
lab8.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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# -*- coding: utf-8 -*-
"""lab8
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1p38yuveIxVpnsVAYYR6Ge34MVzSkUnlC
"""
# Commented out IPython magic to ensure Python compatibility.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
from IPython.display import HTML, display
import tabulate
!wget http://archive.ics.uci.edu/ml/machine-learning-databases/00279/SUSY.csv.gz
!gunzip SUSY.csv.gz
ls -lh
filename="SUSY.csv"
VarNames=["signal", "l_1_pT", "l_1_eta","l_1_phi", "l_2_pT", "l_2_eta",
"l_2_phi", "MET", "MET_phi", "MET_rel", "axial_MET",
"M_R", "M_TR_2", "R", "MT2", "S_R", "M_Delta_R", "dPhi_r_b", "cos_theta_r1"]
df = pd.read_csv(filename, dtype='float64', names=VarNames)
df.columns = VarNames
df.columns = VarNames
#target number of data points
num_data_points = 10000
#random sample
smaller_dataset = df.sample(n=num_data_points, random_state=42)
smaller_dataset.to_csv('smaller_SUSY_dataset.csv', index=False)
#1
!pip install scikit-learn
#2
import sklearn.discriminant_analysis as DA
Fisher=DA.LinearDiscriminantAnalysis()
N_Train=4000000
Train_Sample=df[:N_Train]
Test_Sample=df[N_Train:]
X_Train=Train_Sample[VarNames[1:]]
y_Train=Train_Sample["signal"]
X_Test=Test_Sample[VarNames[1:]]
y_Test=Test_Sample["signal"]
Test_sig=Test_Sample[Test_Sample.signal==1]
Test_bkg=Test_Sample[Test_Sample.signal==0]
Fisher.fit(X_Train,y_Train)
plt.figure()
plt.hist(Fisher.decision_function(Test_sig[VarNames[1:]]),bins=100,histtype="step", color="blue", label="signal",stacked=True)
plt.hist(Fisher.decision_function(Test_bkg[VarNames[1:]]),bins=100,histtype="step", color="red", label="background",stacked=True)
plt.legend(loc='upper right')
plt.show()
#import libraries
import sklearn.discriminant_analysis as DA
from sklearn.metrics import roc_curve, roc_auc_score
import matplotlib.pyplot as plt
#produces training and testing set predictions
y_train_pred = Fisher.predict_proba(X_Train)[:, 1]
y_test_pred = Fisher.predict_proba(X_Test)[:, 1]
#train set's ROC
fpr_train, tpr_train, _ = roc_curve(y_Train, y_train_pred)
#Test set roc
fpr_test, tpr_test, _ = roc_curve(y_Test, y_test_pred)
#Train-auc
auc_train = roc_auc_score(y_Train, y_train_pred)
#test-auc
auc_test = roc_auc_score(y_Test, y_test_pred)
#plot ROC curve
plt.figure(figsize=(8, 6))
plt.plot(fpr_train, tpr_train, label=f'Train ROC Curve (AUC = {auc_train:.2f})')
plt.plot(fpr_test, tpr_test, label=f'Test ROC Curve (AUC = {auc_test:.2f})')
plt.plot([0, 1], [0, 1], linestyle='--', color='gray', label='Random')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend()
plt.show()
#LDA classifier training using different input
#raw lda
Fisher_raw = DA.LinearDiscriminantAnalysis()
Fisher_raw.fit(X_Train, y_Train)
#just the features
Fisher_features = DA.LinearDiscriminantAnalysis()
Fisher_features.fit(X_Train[VarNames[1:]], y_Train)
#combine both ras and featurs
Fisher_combined = DA.LinearDiscriminantAnalysis()
Fisher_combined.fit(X_Train, y_Train)
#test set predicting
y_test_pred_raw = Fisher_raw.predict_proba(X_Test)[:, 1]
y_test_pred_features = Fisher_features.predict_proba(X_Test[VarNames[1:]])[:, 1]
y_test_pred_combined = Fisher_combined.predict_proba(X_Test)[:, 1]
#roc/auc curves calulated for each classifier
fpr_raw, tpr_raw, _ = roc_curve(y_Test, y_test_pred_raw)
auc_raw = roc_auc_score(y_Test, y_test_pred_raw)
fpr_features, tpr_features, _ = roc_curve(y_Test, y_test_pred_features)
auc_features = roc_auc_score(y_Test, y_test_pred_features)
fpr_combined, tpr_combined, _ = roc_curve(y_Test, y_test_pred_combined)
auc_combined = roc_auc_score(y_Test, y_test_pred_combined)
#plot ROC curves
plt.figure(figsize=(8, 6))
plt.plot(fpr_raw, tpr_raw, label=f'Raw (AUC = {auc_raw:.2f})')
plt.plot(fpr_features, tpr_features, label=f'Features (AUC = {auc_features:.2f})')
plt.plot(fpr_combined, tpr_combined, label=f'Combined (AUC = {auc_combined:.2f})')
plt.plot([0, 1], [0, 1], linestyle='--', color='gray', label='Random')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend()
plt.show()
#4 GradientBoostingClassifier, DecisionTreeClassifier, and SGDClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import SGDClassifier
import numpy as np
#this compares the 3 selected classifiers underneath one function
def compare(classifiers, X_train, y_train, X_test, y_test):
plt.figure(figsize=(8, 6))
for clf_name, clf in classifiers.items():
clf.fit(X_train, y_train)
if hasattr(clf, "decision_function"):
y_test_scores = clf.decision_function(X_test)
else:
y_test_scores = clf.predict(X_test)
fpr, tpr, _ = roc_curve(y_test, y_test_scores)
auc_score = roc_auc_score(y_test, y_test_scores)
plt.plot(fpr, tpr, label=f'{clf_name} (AUC = {auc_score:.2f})')
plt.plot([0, 1], [0, 1], linestyle='--', color='gray', label='Random')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend()
plt.show()
#//
classifiers = {
'DecisionTree': DecisionTreeClassifier(),
'GradientBoosting': GradientBoostingClassifier(),
'SGD': SGDClassifier()
}
#executing function
compare(classifiers, X_Train, y_Train, X_Test, y_Test)
#significance and optimal thresholds
thresholds = np.linspace(0, 1, 100)
significance = compute_significance(y_Test, y_test_pred, thresholds)
plot_significance_curve(significance, thresholds)
#looks for optimal threshold
optimal_threshold = thresholds[np.argmax(significance)]
print("Optimal Threshold:", optimal_threshold)
#training classifier
gb_classifier = GradientBoostingClassifier()
gb_classifier.fit(X_Train, y_Train)
#test set probabilityprediction
y_test_pred_proba = gb_classifier.predict_proba(X_Test)[:, 1]
#sig for dif thresholds
thresholds = np.linspace(0, 1, 100)
significance = compute_significance(y_Test, y_test_pred_proba, thresholds)
#sig curve
plot_significance_curve(significance, thresholds)
#optimal threshold
optimal_threshold = thresholds[np.argmax(significance)]
print("Optimal Threshold:", optimal_threshold)
#5
from sklearn.metrics import roc_curve, auc
fpr, tpr, _ = roc_curve(y_Test, Fisher.decision_function(X_Test))
roc_auc = auc(fpr, tpr)
plt.plot(fpr,tpr,color='darkorange',label='ROC curve (area = %0.2f)' % roc_auc)
plt.legend(loc="lower right")
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.show()
#importing metrics
from sklearn.metrics import precision_recall_curve, precision_score, recall_score, f1_score, accuracy_score
#function for computing metrics and significance
def compute_metrics(clf, X_train, y_train, X_test, y_test):
clf.fit(X_train, y_train)#classifier trainging
#test set probability predictions
y_pred_proba = clf.predict_proba(X_test)[:, 1]
#ROC curve and AUC
fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
auc = roc_auc_score(y_test, y_pred_proba)
#precision-recall curve
precision, recall, _ = precision_recall_curve(y_test, y_pred_proba)
#precision, recall, F1-score, and accuracy
y_pred = clf.predict(X_test)
precision_score_val = precision_score(y_test, y_pred)
recall_score_val = recall_score(y_test, y_pred)
f1_score_val = f1_score(y_test, y_pred)
accuracy = accuracy_score(y_test, y_pred)
#significance
thresholds = np.linspace(0, 1, 1000)
significance = compute_significance(y_test, y_pred_proba, thresholds)
max_significance = np.max(significance)
#returns the metrics
return {
'TPR': tpr,
'FPR': fpr,
'ROC': (fpr, tpr),
'AUC': auc,
'Precision': precision_score_val,
'Recall': recall_score_val,
'F1 Score': f1_score_val,
'Accuracy': accuracy,
'Max Significance': max_significance
}
#define scenarios, raw, features, combined
scenarios = {
'Raw': X_Train,
'Features': X_Train[VarNames[1:]],
'Combined': X_Train
}
#initializing dict to store results
results = {}
#compute metrics per scenario
for scenario, X_train_scenario in scenarios.items():
metrics = compute_metrics(gb_classifier, X_train_scenario, y_Train, X_Test, y_Test)
results[scenario] = metrics
#print results
print("Results:")
for scenario, metrics in results.items():
print("\nScenario:", scenario)
for metric, value in metrics.items():
print(f"{metric}: {value}")
df_table = pd.DataFrame.from_dict(results, orient='index')
df_table.index.name = 'scenario'
df_table