Introduction to Deep Learning: Theory and Implementation Based on Python Chapter 2 Perceptron

import numpy as np

Implement AND function (AND gate):

# 最简单版本
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
print(AND(0, 0)) # 输出0
print(AND(1, 0)) # 输出0
print(AND(0, 1)) # 输出0
print(AND(1, 1)) # 输出1
0
0
0
1
# 使用权重和偏置的版本:
def AND1(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
print(AND1(0, 0)) # 输出0
print(AND1(1, 0)) # 输出0
print(AND1(0, 1)) # 输出0
print(AND1(1, 1)) # 输出1
0
0
0
1

Implement NAND function (NAND gate):

def NAND(x1, x2):
    x = np.array([x1, x2])
    w = np.array([-0.5, -0.5]) # 仅权重和偏置与AND不同!
    b = 0.7
    tmp = np.sum(w*x) + b
    if tmp <= 0:
        return 0
    else:
        return 1
print(NAND(0, 0)) # 输出1
print(NAND(1, 0)) # 输出1
print(NAND(0, 1)) # 输出1
print(NAND(1, 1)) # 输出0
1
1
1
0

Realize the OR function (or gate):

def OR(x1, x2):
    x = np.array([x1, x2])
    w = np.array([0.5, 0.5]) # 仅权重和偏置与AND不同!
    b = -0.2
    tmp = np.sum(w*x) + b
    if tmp <= 0:
        return 0
    else:
        return 1
print(OR(0, 0)) # 输出0
print(OR(1, 0)) # 输出1
print(OR(0, 1)) # 输出1
print(OR(1, 1)) # 输出1
0
1
1
1

Realize XOR gate:

def XOR(x1, x2):
    s1 = NAND(x1, x2)
    s2 = OR(x1, x2)
    y = AND(s1, s2)
    return y
print(XOR(0, 0)) # 输出0
print(XOR(1, 0)) # 输出1
print(XOR(0, 1)) # 输出1
print(XOR(1, 1)) # 输出0
0
1
1
0

Guess you like

Origin blog.csdn.net/u011703187/article/details/89075123