Created
July 20, 2017 15:20
-
-
Save adash333/569d6df7dd8b4743698ca725afcadf29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%matplotlib inline | |
import numpy as np | |
import matplotlib.pyplot as plt | |
''' | |
データの生成 | |
''' | |
rng = np.random.RandomState(123) | |
d = 2 | |
N = 10 | |
mean = 5 | |
x1 = rng.randn(N, d) + np.array([0, 0]) | |
x2 = rng.randn(N, d) + np.array([mean, mean]) | |
x = np.concatenate((x1, x2), axis=0) | |
''' | |
単純パーセプトロン | |
''' | |
w = np.zeros(d) | |
b = 0 | |
def y(x): | |
return step(np.dot(w, x) + b) | |
def step(x): | |
return 1 * (x > 0) | |
def t(i): | |
if i < N: | |
return 0 | |
else: | |
return 1 | |
while True: | |
classified = True | |
for i in range(N * 2): | |
delta_w = (t(i) - y(x[i])) * x[i] | |
delta_b = (t(i) - y(x[i])) | |
w += delta_w | |
b += delta_b | |
classified *= all(delta_w == 0) * (delta_b == 0) | |
if classified: | |
break | |
print('w:', w) | |
print('b:', b) | |
print('\nTest:') | |
print(y([0, 0])) # => 0 | |
print(y([5, 5])) # => 1 | |
# matplotlibで描画 | |
x1_x, x1_y, x2_x, x2_y = [], [], [], [] | |
for i in range(N): | |
x1_x.append(x1[i][0]) | |
x1_y.append(x1[i][1]) | |
x2_x.append(x2[i][0]) | |
x2_y.append(x2[i][1]) | |
plt.plot(x1_x, x1_y,"o") | |
plt.plot(x2_x, x2_y,"^") | |
plt.plot([-2, 7], [10.375, -4.67], color='k', linestyle='-', linewidth=1) | |
plt.xlim([-4,8]) | |
plt.ylim([-6,12]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment