首页 > 解决方案 > 用于解决 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>)

为什么结果是这样的?

标签: pythonmachine-learningneural-networkpytorch

解决方案


推荐阅读