感知机实现与门(and), 与非门(Nand), 或门(or), 异或门(xor)
原理
python 实现
class perceptron:
@classmethod
def AND(cls,x1, x2):
w1, w2, b = 0.5, 0.5, -0.7
s = w1*x1+w2*x2+b
return 1 if s>0 else 0
@classmethod
def NAND(cls, x1, x2):
w1, w2, b = -0.5, -0.5, 0.7
s = w1*x1+w2*x2+b
return 1 if s>0 else 0
@classmethod
def OR(cls, x1, x2):
w1, w2, b = 0.5, 0.5, -0.3
s = w1*x1+w2*x2+b
return 1 if s>0 else 0
@classmethod
def XOR(cls, x1, x2):
return perceptron.AND(perceptron.NAND(x1,x2), perceptron.OR(x1, x2))
if __name__ == '__main__':
print("and")
print("0 0 {0}".format(perceptron.AND(0,0)))
print("0 1 {0}".format(perceptron.AND(0,1)))
print("1 0 {0}".format(perceptron.AND(1,0)))
print("1 1 {0}".format(perceptron.AND(1,1)))
print("nand")
print("0 0 {0}".format(perceptron.NAND(0,0)))
print("0 1 {0}".format(perceptron.NAND(0,1)))
print("1 0 {0}".format(perceptron.NAND(1,0)))
print("1 1 {0}".format(perceptron.NAND(1,1)))
print("or")
print("0 0 {0}".format(perceptron.OR(0,0)))
print("0 1 {0}".format(perceptron.OR(0,1)))
print("1 0 {0}".format(perceptron.OR(1,0)))
print("1 1 {0}".format(perceptron.OR(1,1)))
print("xor")
print("0 0 {0}".format(perceptron.XOR(0,0)))
print("0 1 {0}".format(perceptron.XOR(0,1)))
print("1 0 {0}".format(perceptron.XOR(1,0)))
print("1 1 {0}".format(perceptron.XOR(1,1)))
运行结果
and
0 0 0
0 1 0
1 0 0
1 1 1
nand
0 0 1
0 1 1
1 0 1
1 1 0
or
0 0 0
0 1 1
1 0 1
1 1 1
xor
0 0 0
0 1 1
1 0 1
1 1 0
参考
《深度学习入门:基于Python的理论与实现》