AttributeError:“ builtin_function_or_method”对象没有属性“ requires_grad”

时间:2018-06-20 03:25:00

标签: pytorch mnist

训练MNIST数据时出现此错误,csvfiles来自Kaggle。有人可以告诉我我哪里出问题了吗?这是我的代码。 PyTorch的版本是0.4.0。

import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as data
import torchvision
import matplotlib.pyplot as plt

torch.manual_seed(1)

# Training Parameters
EPOCH = 20
BATCH_size = 15
LR = 0.001
img_row, img_col = 28, 28


# Networks structure
class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(
                in_channels=1, out_channels=32,
                kernel_size=5, stride=1, padding=2
            ),
            nn.ReLU(),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2),
            nn.Dropout(0.25)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(32, 64, 3, 1, 1),
            nn.ReLU(),
            nn.Conv2d(64, 64, 3, 1, 1),
            nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Dropout(0.25)
        )
        self.out = nn.Sequential(
            nn.Linear(64*7*7, 512),
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(512, 10)
        )

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = x.view(x.size(0), -1)
        output = self.out(x)
        return output


# Torch Dataset
class Torch_Dataset(data.Dataset):
    def __init__(self, root_dir, csvfile, img_rows, img_cols, train=True, transform=None):
        self.root_dir = root_dir
        self.transform = transform
        self.train = train
        if self.train:
            y_data0 = pd.read_csv(csvfile, header=0, usecols=['label'])
            y_data1 = np.array(y_data0)
            self.y_data = torch.from_numpy(y_data1)
            x_data0 = pd.read_csv(csvfile, header=0, usecols=[i for i in range(1, 785)])
            x_data1 = np.array(x_data0)
            x_data1 = x_data1.reshape(x_data1.shape[0], 1, img_rows, img_cols)
            x_data1 = x_data1.astype('float32')
            x_data1 /= 255
            self.x_data = torch.from_numpy(x_data1)
        else:
            x_data0 = pd.read_csv(csvfile, header=0)
            x_data1 = np.array(x_data0)
            x_data1 = x_data1.reshape(x_data1.shape[0], 1, img_rows, img_cols)
            x_data1 = x_data1.astype('float32')
            x_data1 /= 255
            self.x_data = torch.from_numpy(x_data1)

    def __len__(self):
        return len(self.x_data)

    def __getitem__(self, idx):
        if self.train:
            img, target = self.x_data[idx], self.y_data[idx]
        else:
            img = self.x_data[idx]
            target = None
        # sample = {'img': img, 'target': target}
        return img, target


train = Torch_Dataset(
    root_dir='./',                # root
    csvfile='train.csv',          # filename
    img_rows=img_row,             # image rows
    img_cols=img_col,             # image cols
    train=True                    # train or test
)
# DataLoader
loader = data.DataLoader(
    dataset=train,                # torch dataset format
    batch_size=BATCH_size,        # mini batch size
    shuffle=True,                 # shuffle the data
)
# train the data
cnn = CNN()
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)
loss_f = nn.CrossEntropyLoss()
for epoch in range(EPOCH):
    for step, (x, y) in enumerate(loader):
        b_x = Variable(x)
        b_y = Variable(y)
        b_y = b_y.squeeze

        output = cnn(b_x)
        loss = loss_f(output, b_y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
  

回溯(最近通话最近一次):

     

文件“ C:/ Users / Bryan Zoe / PycharmProjects / MNIST_TEST / PyTorch / test1.py”,第118行,在       损失= loss_f(输出,b_y)

     

文件“ C:\ Users \ Bryan Zoe \ Anaconda3 \ lib \ site-packages \ torch \ nn \ modules \ module.py”,第491行,位于__ 调用 __       结果= self.forward(* input,** kwargs)

     

文件“ C:\ Users \ Bryan Zoe \ Anaconda3 \ lib \ site-packages \ torch \ nn \ modules \ loss.py”,行757,向前       _assert_no_grad(目标)

     

_assert_no_grad中的文件“ C:\ Users \ Bryan Zoe \ Anaconda3 \ lib \ site-packages \ torch \ nn \ modules \ loss.py”,第11行       断言不是tensor.requires_grad,\

     

AttributeError:“ builtin_function_or_method”对象没有属性“ requires_grad”

1 个答案:

答案 0 :(得分:2)

您没有调用squeeze方法,这应该可以工作 b_y = b_y.squeeze()