forked from anastasia-stepanchenko/IntroML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perceptron.py
39 lines (31 loc) · 1.32 KB
/
Perceptron.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
## tested on Python 3.6.3
# work dir must contain: perceptron-train.csv, perceptron-test.csv
# performs perceptron method and compares accuracies with and without
# normalization of data
import pandas # http://pandas.pydata.org/
import sklearn # http://scikit-learn.org/stable/
#import os # https://docs.python.org/3/library/os.html
from sklearn.linear_model import Perceptron
from sklearn.preprocessing import StandardScaler
# set cd
#os.chdir('D:\Programming\Python\IntroML\Perceptron')
# load data from csv
datafit = pandas.read_csv('perceptron-train.csv', header=None)
datatest = pandas.read_csv('perceptron-test.csv', header=None)
X = datafit.iloc[:,1:3]
y = datafit.iloc[:,0]
Xtest = datatest.iloc[:,1:3]
ytest = datatest.iloc[:,0]
# fit and calculate accuracy of perceptron model
clf = Perceptron(random_state=241, max_iter = 1000)
fitted = clf.fit(X, y)
accur = sklearn.metrics.accuracy_score(ytest, clf.predict(Xtest))
print('Accuracy before normalization =', accur)
# normalize data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
Xtest_scaled = scaler.transform(Xtest)
# fit with normalized data and calculate accuracy
fitted2 = clf.fit(X_scaled, y)
accur_scaled = sklearn.metrics.accuracy_score(ytest, clf.predict(Xtest_scaled))
print('Accuracy after normalization =', accur_scaled)