x1 | x2 | y |
---|---|---|
0 | 0 | 0 |
1 | 0 | 0 |
0 | 1 | 0 |
1 | 1 | 1 |
NAND ゲート
x1 | x2 | y |
---|---|---|
0 | 0 | 1 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 0 |
OR ゲート
x1 | x2 | y |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 1 |
def AND(x1, x2):
w1, w2, theta = 0.5, 0.5, 0.7
tmp = x1*w1 + x2*w2
if tmp <= theta:
return 0
elif tmp > theta:
return 1
AND(0, 0)
0
AND(1, 0)
0
AND(0, 1)
0
AND(1, 1)
1
import numpy as np
x = np.array([0, 1]) # 入力
w = np.array([0.5, 0.5]) # 重み
b = -0.7 # バイアス
w * x
array([ 0. , 0.5])
np.sum(w*x)
0.5
np.sum(w*x) + b
-0.19999999999999996
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
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
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
※ for 文をネストすることでまとめて実行・確認
for x2 in (0, 1):
for x1 in (0, 1):
print(x1, x2, AND(x1, x2))
0 0 0 1 0 0 0 1 0 1 1 1
for x2 in (0, 1):
for x1 in (0, 1):
print(x1, x2, NAND(x1, x2))
0 0 1 1 0 1 0 1 1 1 1 0
for x2 in (0, 1):
for x1 in (0, 1):
print(x1, x2, OR(x1, x2))
0 0 0 1 0 1 0 1 1 1 1 1
x1 | x2 | y |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 0 |
w = np.array([1.0, 1.0])
b = -0.5
%matplotlib inline
import matplotlib.pyplot as plt
f = lambda x: x*-w[0]/w[1]-b
x = np.arange(-1, 2, 0.5)
plt.hlines([0], -1, 2, colors="grey", linestyles="dashed")
plt.vlines([0], -1, 2, colors="grey", linestyles="dashed")
plt.plot(x, f(x))
plt.xlim(-1, 2)
plt.ylim(-1, 2)
plt.plot([0, 1], [0, 1], "x")
plt.plot([0, 1], [1, 0], "o")
[<matplotlib.lines.Line2D at 0x7f948b4d7f28>]
def XOR(x1, x2):
s1 = NAND(x1, x2)
s2 = OR(x1, x2)
y = AND(s1, s2)
return y
for x2 in (0, 1):
for x1 in (0, 1):
print(x1, x2, XOR(x1, x2))
0 0 0 1 0 1 0 1 1 1 1 0
※おまけ:NAND と OR を行列演算で書いてみた。
def XOR2(x1, x2):
W = np.array([[-0.5, -0.5], [0.5, 0.5]])
B = np.array([0.7, -0.2])
X = np.array([x1, x2])
a = W.dot(X) + B
Y = (a > 0).astype("float")
return AND(*Y)
for x2 in (0, 1):
for x1 in (0, 1):
print(x1, x2, XOR2(x1, x2))
0 0 0 1 0 1 0 1 1 1 1 0