pytorch - 属性错误: 'builtin_function_or_method' object has no attribute 'requires_grad'

标签 pytorch mnist

我在训练 MNIST 数据时收到此错误,csv 文件来自 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()

Traceback (most recent call last):

File "C:/Users/Bryan Zoe/PycharmProjects/MNIST_TEST/PyTorch/test1.py", line 118, in loss = loss_f(output, b_y)

File "C:\Users\Bryan Zoe\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 491, in __ call __ result = self.forward(*input, **kwargs)

File "C:\Users\Bryan Zoe\Anaconda3\lib\site-packages\torch\nn\modules\loss.py", line 757, in forward _assert_no_grad(target)

File "C:\Users\Bryan Zoe\Anaconda3\lib\site-packages\torch\nn\modules\loss.py", line 11, in _assert_no_grad assert not tensor.requires_grad, \

AttributeError: 'builtin_function_or_method' object has no attribute 'requires_grad'

最佳答案

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

关于pytorch - 属性错误: 'builtin_function_or_method' object has no attribute 'requires_grad' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50939730/

相关文章:

python - 通过索引列表选择pytorch张量元素

python - 属性错误 : 'CrossEntropyLoss' object has no attribute 'backward'

python - 如何设置和获取自定义 YOLOv5 模型的置信度阈值?

Pytorch-为什么 “accumulating”是.gradient的默认模式?

python - 对 MNIST 数据集进行标准化和缩放的正确方法

python-3.x - 拥抱脸: tokenizer for masked lm question

caffe - mnist 数据集 Lenet 训练

machine-learning - 有类似 MNIST 的数据集吗?

tensorflow - 如何更改用于在 tensorflow2.0 中进行训练和评估的图像数量?

machine-learning - 使用keras识别手写数字