パーセプトロン
意味
パーセプトロンは、2クラス分類の線形分類モデルです。その入力はインスタンスの特徴ベクトルであり、出力は+1と-1のバイナリ値をとるインスタンスのカテゴリです。
f(x)= sign(w * x + b)
ANDゲート
ANDゲートは、両方の入力が1の場合にのみ1を出力し、それ以外の場合は0を出力します。
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
def AND(x1, x2):
x = np.array([x1, x2])
w = np.array([0.5, 0.5])
b = -0.7
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
if __name__ == '__main__':
for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
y = AND(xs[0], xs[1])
print(str(xs) + " -> " + str(y))
输入结果:
(0, 0) -> 0
(1, 0) -> 0
(0, 1) -> 0
(1, 1) -> 1
ORゲート
1の場合、出力は1です。それ以外の場合、出力は0です。
# coding: utf-8
import numpy as np
def NAND(x1, x2):
x = np.array([x1, x2])
w = np.array([-0.5, -0.5])
b = 0.7
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
if __name__ == '__main__':
for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
y = NAND(xs[0], xs[1])
print(str(xs) + " -> " + str(y))
输出结果:
(0, 0) -> 0
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 1
ゲートではありません
x1とx2が同時に1の場合は0を出力し、それ以外の場合は1を出力します。
# coding: utf-8
import numpy as np
def OR(x1, x2):
x = np.array([x1, x2])
w = np.array([0.5, 0.5])
b = -0.2
tmp = np.sum(w*x) + b
if tmp <= 0:
return 0
else:
return 1
if __name__ == '__main__':
for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
y = OR(xs[0], xs[1])
print(str(xs) + " -> " + str(y))
输出结果:
(0, 0) -> 1
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 0
XORゲート
同じことが0、違いが1です。XORゲートは、上記で紹介したパーセプトロンモデルでは実現できず、多層パーセプトロンは次のように実装されます。
def XOR(x1, x2):
s1 = NAND(x1, x2)
s2 = OR(x1, x2)
y = AND(s1, s2)
return y
if __name__ == '__main__':
for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
y = XOR(xs[0], xs[1])
print(str(xs) + " -> " + str(y))
输出结果
(0, 0) -> 0
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 0