Skip to content

Instantly share code, notes, and snippets.

@masaponto
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masaponto/5c583881d423a9c90e1f to your computer and use it in GitHub Desktop.
Save masaponto/5c583881d423a9c90e1f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import os.path
class SimplePerceptron:
def __init__(self, r = 0.5, v = 0):
self.r = r
self.v = v
def step(self, x):
return int(x >= self.v)
def add_bius(self, vec):
return np.append(vec, 1)
def fit(self, x_vs, y_s):
self.w_v = np.random.uniform(-1.0, 1.0, (1, len(list(x_vs[0])) + 1))[0]
while y_s != list(map(self.predict, x_vs)):
for y, x_v in zip(y_s, x_vs):
self.w_v = self.w_v + self.r * \
(y - self.predict(x_v)) * self.add_bius(x_v)
def g(self, x_v):
return np.dot(self.w_v, x_v)
def predict(self, x_v):
x_v = self.add_bius(x_v)
return self.step(self.g(x_v))
def plot(sp, x_vs, y_vs, fname):
"""plot function
"""
plt.cla()
plt.clf()
plt.close()
plt.ylim((-1,2))
plt.xlim((-1,2))
# plot points
for i in range(len(x_vs)):
x_v = x_vs[i]
x = x_v[0]
y = x_v[1]
if y_vs[i] == 1:
plt.plot(x, y, "r.", label= "["+ str(x) + ", "+ str(y) + "] class 1")
else:
plt.plot(x, y, "k.", label= "["+ str(x) + ", "+ str(y) + "] class 2")
xs = range(-5, 5)
ys = [-(sp.w_v[0] / sp.w_v[1]) * x - (sp.w_v[2] / sp.w_v[1])
for x in xs]
path = os.path.join("graphs", fname)
plt.plot(xs, ys)
plt.legend(loc="best")
plt.savefig(path)
def main():
# 教師データ
X_train = [[1, 1], [1, 0], [0, 1], [0, 0]]
y_train = [1, 0, 0, 0] # AND
sp1 = SimplePerceptron()
sp1.fit(X_train, y_train)
plot(sp1, X_train, y_train, "graph_and.png")
y_train = [1, 1, 1, 0] # OR
sp2 = SimplePerceptron()
sp2.fit(X_train, y_train)
plot(sp2, X_train, y_train, "graph_or.png")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment