-
-
一种异或门的实现方式
-
发表于: 2022-8-22 14:01 4877
-
说明
感觉有点意思,记录于此。
gate.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | class SwitchGate(object): def AND(self, x1, x2): if 1==x1 and 1==x2: return 1 else: return 0 def OR(self, x1, x2): if 1==x1 or 1==x2: return 1 else: return 0 def NAND(self, x1, x2): if 1==x1 and 1==x2: return 0 else: return 1 def XOR(self, x1, x2): s1=self.NAND(x1, x2) s2=self.OR( x1, x2) y =self.AND( s1, s2) return yclass PerceptronGate(object): def AND(self, x1, x2): # x2>-x1+1.5 -> x1+x2-1.5>0 ,可以有无数条线 w1, w2, b=[1, 1, -1.5] if w1*x1+w2*x2+b>0: return 1 else: return 0 def OR(self, x1, x2): # x2>-x1+0.5 -> x1+x2-0.5>0 w1, w2, b=[1, 1, -0.5] if w1*x1+w2*x2+b>0: return 1 else: return 0 def NAND(self, x1, x2): # x2<-x1+1.5 -> x1+x2-1.5<0 -> -x1-x2+1.5>0 w1, w2, b=[-1, -1, 1.5] # 除了参数不同,后面的代码结构完全一样,即仅依靠参数选取,可以决定门的类型(除了异或门) if w1*x1+w2*x2+b>0: return 1 else: return 0 def XOR(self, x1, x2): s1=self.NAND(x1, x2) s2=self.OR( x1, x2) y =self.AND( s1, s2) return ydef main(): print("SwitchGate") fn=SwitchGate() for x1,x2 in [(0,0), (0,1), (1,0), (1,1)]: y=fn.XOR(x1,x2) print("{x1},{x2}->{y}".format(x1=x1, x2=x2, y=y)) print("") print("PerceptronGate") fn=PerceptronGate() for x1,x2 in [(0,0), (0,1), (1,0), (1,1)]: y=fn.XOR(x1,x2) print("{x1},{x2}->{y}".format(x1=x1, x2=x2, y=y))if "__main__"==__name__: main() |
运行结果

对应的结构

参考
《深度学习入门:基于Python的理论与实现》
[培训]传播安全知识、拓宽行业人脉——看雪讲师团队等你加入!
最后于 2022-9-13 15:15
被Jtian编辑
,原因:
赞赏
他的文章
赞赏
雪币:
留言: