end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

パーセプトロン + python による単純な論理回路実装

GitHub - oreilly-japan/deep-learning-from-scratch: 『ゼロから作る Deep Learning』(O'Reilly Japan, 2016)

「ゼロから作るDeep Learning ① (Pythonで学ぶディープラーニングの理論と実装)」p.23 ~33の写経です。

# coding: utf-8
import numpy as np
import sys

def main():
    inputs = [(0, 0), (1, 0), (0, 1), (1, 1)]

    for gate in [[and_gate,    "AND"    ],
                 [not_and_gate,"NOT AND"],
                 [or_gate,     "OR"     ],
                 [xor_gate,    "XOR"    ]]:
        print( gate[1] )
        for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
            y = gate[0](xs[0], xs[1])
            print( str(xs) + " -> " + str(y) )

# ANDゲート
# x1 x2│y
#───┼─
# 0  0 │0
# 1  0 │0
# 0  1 │0
# 1  1 │1
# 上記を満たす (x1,x2,w)は(0.5,0.5,0.8)や(1.0,1.0,1.0)等も
# ありますが、今回以下を使用
def and_gate(x1, x2):
    x = np.array([x1, x2])      # input
    w = np.array([0.5,0.5])     # weigth
    b = -0.7                    # bias
    tmp = np.sum(w*x) + b
    if tmp <= 0:
        return 0
    else:
        return 1

# NOT ANDゲート
# x1 x2│y
#───┼─
# 0  0 │1
# 1  0 │1
# 0  1 │1
# 1  1 │0
# 上記を満たす (x1,x2,w)は様々ありますが、今回以下を使用

# def not_and_gate(x1, x2):
#     return and_gate(x1, x2) * -1

def not_and_gate(x1, x2):
    x = np.array([x1,   x2])    # input
    w = np.array([-0.5, -0.5])  # weight
    b = 0.7                     # bias
    tmp = np.sum(w*x) + b
    if tmp <= 0:
        return 0
    else:
        return 1
    
# ORゲート
# x1 x2│y
#───┼─
# 0  0 │0
# 1  0 │1
# 0  1 │1
# 1  1 │1
# 上記を満たす (x1,x2,w)は様々ありますが、今回以下を使用

def or_gate(x1, x2):
    x = np.array([x1,  x2])     # input
    w = np.array([0.5, 0.5])    # weight
    b = -0.2                    # bias
    tmp = np.sum(w*x) + b
    if tmp <= 0:
        return 0
    else:
        return 1
    
# XORゲート
# x1 x2│y
#───┼─
# 0  0 │0
# 1  0 │1
# 0  1 │1
# 1  1 │0

# ★XORは、ANDやNAND、ORと異なり、
#    一つのパーセプトロンでは実現できない為、以下
def xor_gate(x1, x2):
    s1 = not_and_gate(x1, x2)
    s2 = or_gate(x1, x2)
    y  = and_gate(s1, s2)
    return y

if __name__ == '__main__':
    main()

↑こう書くと、↓こう表示されます

AND
(0, 0) -> 0
(1, 0) -> 0
(0, 1) -> 0
(1, 1) -> 1
NOT AND
(0, 0) -> 1
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 0
OR
(0, 0) -> 0
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 1
XOR
(0, 0) -> 0
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 0