Skip to content

Instantly share code, notes, and snippets.

@naoyashiga
Last active May 2, 2016 10:19
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 naoyashiga/92d51d11bfb2da82ddf6738cc2aa144d to your computer and use it in GitHub Desktop.
Save naoyashiga/92d51d11bfb2da82ddf6738cc2aa144d to your computer and use it in GitHub Desktop.
単純パーセプトロンの実装
# -*- coding: utf-8 -*-
import numpy
import matplotlib.pyplot as plt
def predict(w, x):
output = numpy.dot(w, x)
if output >= 0:
result = 1
else:
result = -1
return [result, output]
def train(w, x, label):
[result, output] = predict(w, x)
learningRate = 0.5
if output * label < 0:
# 更新
return w + learningRate * label * numpy.array(x)
else:
return w
if __name__=='__main__':
area = 100
loop = 1000
num = 50
bias = 1
# 学習用データ 第一象限、第3象限に大まかにわける
train_X1 = numpy.random.rand(num) * area
train_Y1 = numpy.random.rand(num) * area * 0.1
train_X2 = numpy.random.rand(num) * area - area
train_Y2 = numpy.random.rand(num) * area - area
# ラベルづけ
label1 = numpy.ones(num)
label2 = -1 * numpy.ones(num)
dataSet1 = numpy.c_[train_X1, train_Y1, label1]
dataSet2 = numpy.c_[train_X2, train_Y2, label2]
allDataSet = numpy.r_[dataSet1, dataSet2]
# 初期の重みは適当
weight = [[numpy.random.rand(), -numpy.random.rand(), 1]]
for j in range(loop):
for (x, y, label) in allDataSet:
w_new = train(weight[-1], [x, y, bias], label)
weight.append(w_new)
print(j)
print(w_new)
w = weight[-1]
# 図に描画
x_fig = range(-area,area)
y_fig = [-(w[1]/w[0])*xi-(w[2]/w[1]) for xi in x_fig]
plt.scatter(train_X1, train_Y1, marker='o', color='g', s=100)
plt.scatter(train_X2, train_Y2, marker='s', color='b', s=100)
plt.plot(x_fig,y_fig)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment