Pythonを使って,ANDゲートと同様に,単純な論理ゲートであるNANDゲートを考える.
def NAND_gate(input1, input2):
if input1 == 1 and input2 == 1:
return 0
else:
return 1
# テスト
print(NAND_gate(0, 0)) # 1
print(NAND_gate(0, 1)) # 1
print(NAND_gate(1, 0)) # 1
print(NAND_gate(1, 1)) # 0
実行すると,
1
1
1
0
次に,同じくNANDゲートをパーセプトロンとして考えてみる.
import numpy as np
class Perceptron:
def __init__(self, input_size, lr=1, epochs=10):
self.W = np.zeros(input_size)
self.b = 0
self.lr = lr
self.epochs = epochs
def activation_fn(self, x):
return 1 if x >= 0 else 0
def predict(self, x):
z = np.dot(self.W, x) + self.b
a = self.activation_fn(z)
return a
def train(self, X, d):
for _ in range(self.epochs):
for i in range(d.shape[0]):
y = self.predict(X[i])
e = d[i] - y
self.W += self.lr * e * X[i]
self.b += self.lr * e
print("Final weights:", self.W)
print("Final bias:", self.b)
# データの準備 (NANDゲートの入力と出力)
X = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
d = np.array([1, 1, 1, 0]) # NANDゲートの出力
# パーセプトロンの定義と訓練
perceptron = Perceptron(input_size=2)
perceptron.train(X, d)
# テスト
print("0 AND 0 =", perceptron.predict(np.array([0, 0])))
print("0 AND 1 =", perceptron.predict(np.array([0, 1])))
print("1 AND 0 =", perceptron.predict(np.array([1, 0])))
print("1 AND 1 =", perceptron.predict(np.array([1, 1])))
出力は次のようになる.
Final weights: [-2. -1.]
Final bias: 2
0 AND 0 = 1
0 AND 1 = 1
1 AND 0 = 1
1 AND 1 = 0
Mathematics is the language with which God has written the universe.