异或门(完整)

异或门(完整)_第1张图片

import torch
X = torch.tensor([[1,0,0],[1,1,0],[1,0,1,],[1,1,1]] ,dtype = torch.float32)
orgate = torch.tensor([0,1,1,1],dtype = torch.float32)


def OR(X):
    w = torch.tensor([-0.5,1,1] ,dtype = torch.float32) # b,w1,w2
    zhat = torch.mv(X,w)
    yhat = torch.tensor([int(x) for x in zhat>=0],dtype = torch.float32)  #int(True)=1,int(False)=0
    return yhat
sigma_or = OR(X)


import torch
X = torch.tensor([[1,0,0],[1,1,0],[1,0,1,],[1,1,1]] ,dtype = torch.float32)
nandgate = torch.tensor([1,1,1,0],dtype = torch.float32)


def NAND(X):
    w = torch.tensor([0.7,-0.5,-0.5] ,dtype = torch.float32) # b,w1,w2
    zhat = torch.mv(X,w)
    yhat = torch.tensor([int(x) for x in zhat>=0],dtype = torch.float32)  #int(True)=1,int(False)=0
    return yhat
sigma_nand = NAND(X)


x0 = torch.tensor([1,1,1,1],dtype = torch.float32)
input_2 = torch.cat((x0.view(4,1),sigma_nand.view(4,1),sigma_or.view(4,1)),dim=1)
def AND(X):
    w = torch.tensor([-0.7,0.5,0.5] ,dtype = torch.float32) # b,w1,w2
    zhat = torch.mv(X,w)
    yhat = torch.tensor([int(x) for x in zhat>=0],dtype = torch.float32)  #int(True)=1,int(False)=0
    return yhat
sigma_and = AND(input_2)

def XOR(X):
    #输入层
    input_1 = X
    #中间层
    sigma_nand = NAND(input_1)
    sigma_or = OR(input_1)
    x0 = torch.tensor([1,1,1,1],dtype = torch.float32)
    input_2 = torch.cat((x0.view(4,1),sigma_nand.view(4,1),sigma_or.view(4,1)),dim=1)
    #输出层
    y_and = AND(input_2)
    return y_and

Y = XOR(X)
print(Y)

import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-whitegrid') #设置图像的风格
sns.set_style("white")
plt.figure(figsize=(5,3)) #设置画布大小
plt.title("NOR GATE",fontsize=16) #设置图像标题
plt.scatter(input_2[:,1],input_2[:,2],c=Y,cmap="rainbow") #绘制散点图
plt.xlim(-1,3) #设置横纵坐标尺寸
plt.ylim(-1,3)
plt.grid(alpha=.4,axis="y") #显示背景中的网格
plt.gca().spines["top"].set_alpha(.0) #让上方和右侧的坐标轴被隐藏
plt.gca().spines["right"].set_alpha(.0);

异或门(完整)_第2张图片

你可能感兴趣的:(深度学习)