gpt4 book ai didi

deep-learning - PyTorch 中的双层神经网络不收敛

转载 作者:行者123 更新时间:2023-12-04 03:44:31 25 4
gpt4 key购买 nike

问题

我正在尝试使用不同的方法(TensorFlow、PyTorch 和从头开始)实现 2 层神经网络,然后根据 MNIST 数据集比较它们的性能。

我不确定我犯了什么错误,但 PyTorch 中的准确率只有 10% 左右,基本上是随机猜测。我认为可能权重根本没有更新。

请注意,我特意使用了 TensorFlow 提供的数据集,以使我通过 3 种不同方法使用的数据保持一致,以便准确比较。

from tensorflow.examples.tutorials.mnist import input_data
import torch

class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = torch.nn.Linear(784, 100)
self.fc2 = torch.nn.Linear(100, 10)

def forward(self, x):
# x -> (batch_size, 784)
x = torch.relu(x)
# x -> (batch_size, 10)
x = torch.softmax(x, dim=1)
return x

net = Net()
net.zero_grad()
Loss = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)

for epoch in range(1000): # loop over the dataset multiple times

batch_xs, batch_ys = mnist_m.train.next_batch(100)
# convert to appropriate settins
# note the input to the linear layer should be (n_sample, n_features)
batch_xs = torch.tensor(batch_xs, requires_grad=True)
# batch_ys -> (batch_size,)
batch_ys = torch.tensor(batch_ys, dtype=torch.int64)

# forward
# output -> (batch_size, 10)
output = net(batch_xs)
# result -> (batch_size,)
result = torch.argmax(output, dim=1)
loss = Loss(output, batch_ys)

# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()

最佳答案

这里的问题是您没有应用完全连接的层 fc1fc2

您的 forward() 目前看起来像:

def forward(self, x):
# x -> (batch_size, 784)
x = torch.relu(x)
# x -> (batch_size, 10)
x = torch.softmax(x, dim=1)
return x

所以如果你把它改成:

def forward(self, x):
# x -> (batch_size, 784)
x = self.fc1(x) # added layer fc1
x = torch.relu(x)

# x -> (batch_size, 10)
x = self.fc2(x) # added layer fc2
x = torch.softmax(x, dim=1)
return x

它应该可以工作。

关于 Umang Guptas 的回答:在我看来,像 Mr.Robot 那样,在调用 backward() 之前先调用 zero_grad() 就可以了。这应该不是问题。


编辑:

所以我做了一个简短的测试 - 我将迭代设置为从 100010000 以查看它是否真的在减少。 (当然,我也将数据加载到 mnist_m,因为您发布的代码中未包含此数据)

我在代码中添加了一个打印条件:

if epoch % 1000 == 0:
print('Epoch', epoch, '- Loss:', round(loss.item(), 3))

1000 次迭代打印出损失:

Epoch 0 - Loss: 2.305
Epoch 1000 - Loss: 2.263
Epoch 2000 - Loss: 2.187
Epoch 3000 - Loss: 2.024
Epoch 4000 - Loss: 1.819
Epoch 5000 - Loss: 1.699
Epoch 6000 - Loss: 1.699
Epoch 7000 - Loss: 1.656
Epoch 8000 - Loss: 1.675
Epoch 9000 - Loss: 1.659

使用 PyTorch 版本 0.4.1 测试

所以你可以看到,随着 forward() 的改变,网络现在正在学习,其余的代码我没有动过。

祝你好运!

关于deep-learning - PyTorch 中的双层神经网络不收敛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com