python - 用于解决 XOR 问题的 MLP 的 Pytorch 实现给出了错误的预测
问题描述
我正在尝试使用 MLP 来解决 pytorch 的 XOR 问题。
from torch import nn
class XORLinear(nn.Module):
def __init__(self):
super(XORLinear, self).__init__()
self.fc1 = nn.Linear(2, 2)
self.activation = nn.ReLU()
self.fc2 = nn.Linear(2, 1)
self.init_weights()
def init_weights(self):
self.fc1.weight.data = torch.Tensor([[1, 1], [1, 1]])
self.fc1.bias.data = torch.Tensor([[0, -1]])
self.fc2.weight.data = torch.Tensor([[1, -2]])
self.fc2.bias.data.zero_()
def forward(self, data):
fc1 = self.fc1(data)
activated = self.activation(fc1)
fc2 = self.fc2(fc1)
return fc2
我认为使用初始权重,模型应该为所有 4 个可能的输入输出正确的预测。
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = XORLinear().to(device)
x = torch.Tensor([[1, 1], [0, 0], [1, 0], [0, 1]])
y_pred = model(x)
print(y_pred)
然而,预测是
tensor([[0.],
[2.],
[1.],
[1.]], grad_fn=<AddmmBackward>)
为什么结果是这样的?
解决方案
推荐阅读
- hashtable - CS50 Pset 5 哈希表问题
- javascript - 无法让 Bootstrap-vue 表单验证工作
- wordpress - 我的 wordpress 网站已损坏。不知道做什么。尝试了安全模式插件,但没有任何反应
- javascript - 是否可以在 JS 中使用没有 Await 的 Async?
- pine-script - Pine 脚本 - 使用 strategy.order() 或 strategy.entry() 的括号顺序
- python - AttributeError:模块'rest_framework.serializers'在django中没有属性'as_view'
- javascript - bootstrap.css className 不影响网站的样式
- python - 尝试使用 Python 从目录中获取所有文件(包括只读文件)
- python - 满足条件时如何使我的代码停止
- kubernetes - 使用 ip -a 命令在 kubernetes pod 中的 eth0@if1092 是什么意思