利用感知机实现逻辑电路(与门、与非门、或门、异或门)
#!/usr/bin/env python# -*- coding: utf-8 -*-import numpy as npdef AND(x1, x2): """ 与门实现(单层感知机) :param x1: 输入信号1 :param x2: 输入信号2 :return: 输出信号 """ # 输入信号数组 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 1def NAND(x1, x2): """ 与非门实现(单层感知机) :param x1: 输入信号1 :param x2: 输入信号2 :return: 输出信号 """ # 输入信号数组 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 1def OR(x1, x2): """ 或门实现(单层感知机) :param x1: 输入信号1 :param x2: 输入信号2 :return: 输出信号 """ # 输入信号数组 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 1def XOR(x1, x2): """ 异或门实现(多层感知机) :param x1: 输入信号1 :param x2: 输入信号2 :return: 输出信号 """ # 与非门运算 s1 = NAND(x1, x2) # 或门运算 s2 = OR(x1, x2) # 与门运算 y = AND(s1, s2) return ydef doit(): """ 测试函数 """ res = XOR(0, 0) print(res)doit()