-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperceptron_example.py
170 lines (104 loc) · 3.84 KB
/
perceptron_example.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
import numpy as np
import random
import math
import time
random.seed(16)
import matplotlib.pyplot as plt
class create_Data:
def __init__(self, N=1000, dim = 2, bounds = None):
if bounds == None:
bounds = [(-1, 1) for _ in range(dim)]
self.dim = dim
self.bounds = bounds
self.Xdata = []
self.Ydata = []
self.w = []
self.generate_points(N)
def make_f(self, w = None):
X = np.asarray(self.Xdata)
#add a column of ones
X = np.hstack((X, np.ones((len(X), 1))))
if w == None:
w = np.zeros((X.shape[1], 1))
while (np.matmul(X, w) < 0).sum() < 0.3*len(X) or (np.matmul(X, w) < 0).sum() > 0.7*len(X):
rand_num = random.randint(0, 2)
w = ((-1)**(rand_num))*np.random.rand(X.shape[1], 1)
print "w: ", w
actual_y = np.matmul(X, w)
for i in range(0, len(actual_y)):
actual_y[i] = actual_y[i] + 0.07*((-1)**(random.randint(0, 1)))*random.random()
actual_y[actual_y>=0] = 1
actual_y[actual_y<0] = -1
self.w = w
self.Ydata = actual_y
self.Xdata = X
return self
def generate_points(self, N):
for i in range(N):
point = np.array([random.uniform(self.bounds[j][0], self.bounds[j][1]) for j in range(self.dim)])
self.Xdata.append(point)
#add in a column of ones
self.make_f()
return self
class perceptron():
def __init__(self, dim = 2, max_ep=100):
self.dim = dim
self.w = np.zeros(dim+1)
self.done = False
self.max_epoch = max_ep
self.iterations = 0
def predict(self, X_test, learned_w):
pred_y = np.matmul(X_test, learned_w)
pred_y[pred_y>=0] = +1
pred_y[pred_y<0] = -1
return pred_y
def train(self, X, Y, lr, eta, count_check):
dataset = np.hstack((X, Y))
np.random.shuffle(dataset)
X_t = dataset[:, 0:X.shape[1]]
Y_t = dataset[:, -1]
count = 0
w_list = []
for ep in range(self.max_epoch):
for i in range(0, len(X_t)):
count += 1
if Y_t[i]*(np.matmul(X_t[i, :], self.w)) <= eta:
self.w = self.w + self.w + lr*Y_t[i]*X_t[i, :]
self.w = self.w/(np.linalg.norm(self.w))
if np.isin(count, count_check):
print np.isin(count, count_check)
w_list.append(self.w)
print "Trained w: ", self.w
#w_list.append(self.w)
return self, w_list
count_check = [5, 20, 100, 500]
train_data = create_Data(N=100, dim=2, bounds=None)
test_data = create_Data(N=20, dim=2, bounds=None)
perceptron = perceptron(dim=2, max_ep=5)
_, w_list = perceptron.train(train_data.Xdata, train_data.Ydata, 0.1, 0.0, count_check)
print w_list
y_p = perceptron.predict(test_data.Xdata, perceptron.w)
#predict
idx_1 = np.where(train_data.Ydata >=0)[0]
idx_2 = np.where(train_data.Ydata <0)[0]
idx_1e = np.where(y_p>=0)[0]
idx_2e = np.where(y_p < 0)[0]
#co-ordinate data
count = 0
for w in w_list:
count += 1
x0= np.linspace(-1, 1, 1000)
x1 = (-w[0]*x0 - w[2])/w[1]
plt.plot(train_data.Xdata[idx_1, 0], train_data.Xdata[idx_1, 1], 'ko')
plt.plot(train_data.Xdata[idx_2, 0], train_data.Xdata[idx_2, 1], 'ro')
if count == len(w_list):
plt.plot(x0, x1, 'k-')
plt.plot(test_data.Xdata[idx_1e, 0], test_data.Xdata[idx_1e, 1], 'ks', markersize=12)
plt.plot(test_data.Xdata[idx_2e, 0], test_data.Xdata[idx_2e, 1], 'rs', markersize=12)
plt.xlabel('$x_1$', {'fontsize': 16})
plt.ylabel('$x_2$', {'fontsize': 16})
plt.ylim([-1, 1])
#plt.ylim([-1.1, 1.1])
filename = 'fig_perceptron' + str(count) + '.eps'
plt.savefig(filename)
plt.show()