Pytorch 1.7.0 | DataLoader 错误 - TypeError:“模块”对象不可调用
Posted
技术标签:
【中文标题】Pytorch 1.7.0 | DataLoader 错误 - TypeError:“模块”对象不可调用【英文标题】:Pytorch 1.7.0 | DataLoader Error - TypeError: 'module' object is not callable 【发布时间】:2021-03-22 02:16:51 【问题描述】:这是我的代码,我正在使用 pycharm!
进口
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.utils.data as DataLoader
import torchvision.datasets as Datasets
import torchvision.transforms as transforms
创建全连接网络
class NN(nn.Module):
def __init__(self, input_size, num_classes): #(28x28 = 784)
super(NN, self).__init__()
self.fc1 = nn.Linear(input_size, 50)
self.fc2 = nn.Linear(50, input_size) #hidden layer
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
#设置设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
超参数
input_size = 784
num_classes = 10
learning_rate = 0.001
batch_size = 2
num_epochs = 1
加载数据
train_dataset = Datasets.MNIST(root='dataset/', train=True, transform=transforms.ToTensor(), download=True)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = Datasets.MNIST(root='dataset/', train=False, transform=transforms.ToTensor(), download=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True)
初始化网络
model = NN(input_size=input_size, num_classes=num_classes).to(device)
损失和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
火车网络
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
data = data.to(device=device)
targets = targets.to(device=device)
print(data.shape)
我在这一行得到错误
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
错误是
in <module>
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
TypeError: 'module' object is not callable
【问题讨论】:
【参考方案1】:您需要编辑您的导入
from torch.utils.data import DataLoader, Dataset
【讨论】:
以上是关于Pytorch 1.7.0 | DataLoader 错误 - TypeError:“模块”对象不可调用的主要内容,如果未能解决你的问题,请参考以下文章
Pytorch 1.7.0 | DataLoader 错误 - TypeError:“模块”对象不可调用
01 Pytorch和CUDA对应的版本及Pytorch和Python对应的版本及Python与Anaconda的对应关系