3.3. パーセプトロンの実装

3.3.1. 簡単な実装

AND関数を実装しよう

[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
[2]:
AND(0, 0)
[2]:
0
[3]:
AND(1, 0)
[3]:
0
[4]:
AND(0, 1)
[4]:
0
[5]:
AND(1, 1)
[5]:
1

3.3.2. 重みとバイアスの導入

パーセプトロンの条件式を見てみよう

\[\begin{split}y = \begin{cases} 0 \quad (w_1 x_1 + w_2 x_2 \leqq \theta) \\ 1 \quad (w_1 x_1 + w_2 x_2 > \theta) \\ \end{cases}\end{split}\]

ここで、\(\theta\) = \(-b\) とすると

\[\begin{split}y = \begin{cases} 0 \quad (w_1 x_1 + w_2 x_2 \leqq - b) \\ 1 \quad (w_1 x_1 + w_2 x_2 > - b) \\ \end{cases}\end{split}\]

式変形して

\[\begin{split}y = \begin{cases} 0 \quad (b + w_1 x_1 + w_2 x_2 \leqq 0) \\ 1 \quad (b + w_1 x_1 + w_2 x_2 > 0) \\ \end{cases}\end{split}\]

ここで、\(b\)バイアス と呼び、\(w_1\) \(w_2\)重み と呼びます

[6]:
import numpy as np
x = np.array([0, 1])      # 入力
w = np.array([0.5, 0.5])  # 重み
b = -0.7                  # バイアス
w * x
[6]:
array([0. , 0.5])
[7]:
np.sum(w * x)
[7]:
0.5
[8]:
np.sum(w * x) + b
[8]:
-0.19999999999999996

3.3.3. 重みとバイアスによる実装

[9]:
def AND(x1, x2):
    """
    AND関数

    Parameters
    ----------
    x1 : float
        入力1
    x2 : float
        入力2
    """
    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
  • \(w_1\)\(w_2\) の重みは、入力信号の重要度をコントロールするパラメータ

  • \(b\) のバイアスは、発火のしやすさのパラメータ

[10]:
def NAND(x1, x2):
    """
    NAND関数

    Parameters
    ----------
    x1 : float
        入力1
    x2 : float
        入力2
    """
    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
[11]:
NAND(0, 0)
[11]:
1
[12]:
NAND(1, 0)
[12]:
1
[13]:
NAND(0, 1)
[13]:
1
[14]:
NAND(1, 1)
[14]:
0
[15]:
def OR(x1, x2):
    """
    OR関数

    Parameters
    ----------
    x1 : float
        入力1
    x2 : float
        入力2
    """
    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
[16]:
OR(0, 0)
[16]:
0
[17]:
OR(1, 0)
[17]:
1
[18]:
OR(0, 1)
[18]:
1
[19]:
OR(1, 1)
[19]:
1