神经网络中的异或门问题
神经网络停摆了接近30年,除了数据量少,运算速度慢等问题,还有一个关键性的问题就是精度问题,
1、 与门,或门和非与门
针对神经网络中的分类问题,有这样几类数据,
与门
| x0 | x1 | x2 | y_and |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 1 | 1 | 0 | 0 |
| 1 | 0 | 1 | 0 |
| 1 | 1 | 1 | 1 |
import torch
import matplotlib.pyplot as plt
import seaborn as sns
X = torch.tensor([[1,0,0],[1,1,0],[1,0,1],[1,1,1]],dtype = torch.float32)
andgate = torch.tensor([0,0,0,1],dtype = torch.float32)
plt.style.use('seaborn-whitegrid') #设置图像的风格
sns.set_style("white")
plt.figure(figsize=(5,3)) #设置画布大小
plt.title("AND GATE",fontsize=16) #设置图像标题
plt.scatter(X[:,1],X[:,2],c=andgate,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);

或门
| x0 | x1 | x2 | y_or |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 1 | 1 | 0 | 1 |
| 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 |

非与门
| x0 | x1 | x2 | y_nand |
|---|---|---|---|
| 1 | 0 | 0 | 1 |
| 1 | 1 | 0 | 1 |
| 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 0 |

上述的类型数据神经网络都能很好的处理,接下去看一个特例
异或门
| x0 | x1 | x2 | y_xor |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 1 | 1 | 0 | 1 |
| 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 0 |

这样的数据单层神经网络是无法处理的,深层神经网络就来了。。。。。。
2、深层神经网络

#定义三个单层网络,
def AND (X):
w = torch.tensor([-0.2,0.15,0.15],dtype = torch.float32)#因为权重不一样,所以得局部设置w
zhat = torch.mv(X,w)
yhat = torch.tensor([int(x) for x in zhat>=0],dtype = torch.float32)
return yhat
def OR (X):
w = torch.tensor([-0.08,0.15,0.15],dtype = torch.float32)
zhat = torch.mv(X,w)
yhat = torch.tensor([int(x) for x in zhat>=0],dtype = torch.float32)
return yhat
def NAND(X):
w = torch.tensor([0.23,-0.15,-0.15],dtype = torch.float32)
zhat = torch.mv(X,w)
yhat = torch.tensor([int(x) for x in zhat>=0],dtype = torch.float32)
return yhat
def XOR(X):
s_nand = NAND(X)#中间层
s_or = OR(X)#中间层
bias = X[:,0]#中间层
input_ = torch.cat([bias.view(4,1),s_nand.view(4,1),s_or.view(4,1)],dim = 1)#输出层
yhat = AND(input_)#输出层
return yhat
X = torch.tensor([[1,0,0],[1,1,0],[1,0,1],[1,1,1]],dtype = torch.float32)
xorgate = torch.tensor([0,1,1,0],dtype = torch.float32)
XOR(X)

权重经过特殊设置,完美预测分类结果。
本文探讨了神经网络在处理异或门问题上的挑战,展示了单层网络的局限,并通过实例展示了如何使用深层神经网络,如AND、OR、NAND网络,配合特殊权重设置来实现XOR逻辑。重点介绍了定义和实现深度神经网络函数的过程。
519

被折叠的 条评论
为什么被折叠?



