Pytorch 1.7.0 | DataLoader Error - TypeError: 'module' object is not callable

Pytorch 1.7.0 | DataLoader Error - TypeError: 'module' object is not callable

这是我的代码,我正在使用 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

您需要编辑您的导入

from torch.utils.data import DataLoader, Dataset