forked from Charles57-CWU/DSCVizTests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfusionMatrixGenerator.py
77 lines (58 loc) · 1.8 KB
/
ConfusionMatrixGenerator.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
"""
Generate a confusion matrix.
Written by: Lincoln Huber
"""
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.metrics import confusion_matrix, accuracy_score
import pandas as pd
import numpy as np
import math
import sys
import os
# get data file
path = 'iris_dataset.csv'
# get printing
printing = bool(sys.stdout)
if os.path.exists(path):
# create dataframe from file
dataframe = pd.read_csv(path)
# get data and labels
labels = dataframe['class'].values.reshape(-1, 1)
data = dataframe.drop(['class'], axis=1)
# get LDA
lda = LinearDiscriminantAnalysis(n_components=1)
# train
lda.fit(data, labels.ravel())
# get weights
angles = lda.coef_[0].copy()
# normalize
angles = angles / max(abs(angles))
# get degrees
for i in range(len(angles)):
angles[i] = np.arccos(angles[i])
angles[i] = math.degrees(angles[i])
# print angles
if printing:
for i in range(len(angles)):
print(angles[i])
# normalize weights
weights = lda.coef_[0].copy()
weights = weights / max(abs(weights))
# apply weights to class means
weightedMeans = lda.means_ * weights
# get sum of feature values for each class
weightedMeanSum1 = sum(weightedMeans[0])
weightedMeanSum2 = sum(weightedMeans[1])
# add weighted class sums then divide by 2 to get threshold
if printing:
print((weightedMeanSum1 + weightedMeanSum2) / 2)
# get predictions
predictions = lda.predict(data)
# get confusion matrix
cm = confusion_matrix(labels, predictions)
# print confusion matrix
for i in range(len(cm)):
for j in range(len(cm[i])):
print(cm[i][j])
# print accuracy
print(f"Accuracy: {round(accuracy_score(labels, predictions) * 100, 2)}%")