首页 > 解决方案 > AttributeError:“builtin_function_or_method”对象没有属性“requires_grad”

问题描述

训练 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 = loss_f(output, b_y)

文件“C:\Users\Bryan Zoe\Anaconda3\lib\site-packages\torch\nn\modules\module.py”,第 491 行,在 __ call __ result = self.forward(*input, **kwargs)

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

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

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

标签: pytorchmnist

解决方案


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


推荐阅读