-
Notifications
You must be signed in to change notification settings - Fork 0
/
classifier.py
164 lines (103 loc) · 3.67 KB
/
classifier.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
import math
import csv
def calcMean(propData, propIdx):
sumProps = 0
for x in propData:
sumProps += x[propIdx]
return sumProps/len(propData)
def calcVariance(propData, mean, propIdx):
k = 1.0 / (len(propData) - 1)
sumProps = 0
for x in propData:
sumProps += (x[propIdx] - mean)**2
return k * sumProps
def calcGauss(classData):
Gauss = []
propsCount = len(classData[0])
for propIdx in range(0, propsCount):
mean = calcMean(classData, propIdx)
variance = calcVariance(classData, mean, propIdx)
Gauss.append( (mean, variance) )
return Gauss
# Плонтость
def prob(propSample, propGauss):
mean = propGauss[0]
variance = propGauss[1]
exp = math.exp(-((propSample - mean) ** 2) / (2 * variance))
sqrt = 1.0/math.sqrt(2.0 * math.pi * variance)
return exp * sqrt
################################################################################
def parseData(row):
data = []
dataLen = len(row)
className = row[-1]
for idx in range(0, dataLen - 1):
val = 0
try:
val = float(row[idx])
except ValueError:
val = ord(row[idx]) / 10
data.append(val)
return className, data
def populateData(file):
Data = {}
with open(file, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
className, props = parseData(row)
if Data.get(className) is None :
Data[className] = []
Data[className].append(props)
return Data
def countAllRows(classesData):
sum = 0
for _, data in classesData.items():
sum += len(data)
return sum
def calcGaussians(classesData):
Gaussians = {}
for name, data in classesData.items():
Gaussians[name] = calcGauss(data)
return Gaussians
def calcClassProbability(classesData):
ClassProb = {}
allItems = countAllRows(classesData)
for name, data in classesData.items():
ClassProb[name] = len(data) / allItems
return ClassProb
def learn(file):
Data = populateData(file)
return Data, calcGaussians(Data), calcClassProbability(Data)
def getMaxProbClass(probabilities):
maxClass = ''
for className, value in probabilities.items():
if probabilities.get(maxClass) is None:
maxClass = className
elif probabilities[maxClass] < value:
maxClass = className
return maxClass
def predict(sample, Gaussians, ClassProb):
Probs = {}
for className, gauss in Gaussians.items():
Probs[className] = ClassProb[className]
propIdx = 0
for sampleProp in sample:
Probs[className] *= prob(sampleProp, gauss[propIdx])
propIdx += 1
return getMaxProbClass(Probs)
#==============================================================================#
Data, gauss, clProb = learn('Iris.csv') #'sobaki_i_volki.csv' #'Iris.csv'
TestData, _, _ = learn('Iris_test.csv')
count = 0
successPredictions = 0
print("Реальный | Угаданный\n")
for className, rowData in TestData.items():
for props in rowData:
predicted = predict(props, gauss, clProb)
if className == predicted:
successPredictions += 1
else:
print(className + " != " + predicted)
count += 1
print()
print("Точность классификации: " + "{0:.2f}".format((successPredictions/count) * 100) + "%")