'int'对象没有属性'size'“

时间:2020-01-11 02:50:05

标签: python deep-learning artificial-intelligence pytorch

F.nll_loss:我要

AttributeError:“ int”对象没有属性“ size”

当我尝试运行此代码时。我还获得了模块代码的片段。

提高ValueError('预期2个或更多尺寸(got {})'。format(dim)) 如果input.size(0)!= target.size(0):
引发ValueError('预期的输入batch_size({})以匹配目标batch_size({})。'
格式(input.size(0),target.size(0)))

import torch
from torchvision import transforms, datasets
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pylab as plt

train_dataset = datasets.MNIST(root = '', train =True, download = True,
                                transform =transforms.Compose([transforms.ToTensor()]))

test_dataset = datasets.MNIST(root ='', download =True, train =False,
                               transform =transforms.Compose([transforms.ToTensor()]))
batch_size = 10
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size, shuffle =True)

test_dataset = torch.utils.data.DataLoader(test_dataset, batch_size, shuffle =True)
class Net(nn.Module):

  def __init__(self):
    super().__init__()
    self.fc1 = nn.Linear(28*28, 64)
    self.fc2 = nn.Linear(64,64)
    self.fc3 = nn.Linear(64,64)
    self.fc4 = nn.Linear(64,10)

  def forward(self, x):
      x = F.relu(self.fc1(x))
      x = F.relu(self.fc2(x))
      x = F.relu(self.fc2(x))
      x = self.fc4(x)
      return F.log_softmax(x, dim=1)

x=torch.rand((28,28))
x=x.view(-1,28*28)
net =Net()
out=net(x)
out
import torch.optim as optim

optimizer =optim.Adam(net.parameters(), lr=0.001)

EPOCHS = 3
for epoch in range(EPOCHS):
  for data in train_dataset:
      x, y = data
      net.zero_grad()
      x=x.view(-1, 28*28)
      output = net(x)
      loss = F.nll_loss(output, y)
      loss.backward()
      optimizer.step()
  print(loss)

1 个答案:

答案 0 :(得分:2)

只需将for循环更改为:

for data in train_loader:

#!/bin/bash