Search code examples
pytorchobject-detectiondataloader

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


This is my code, I am using pycharm!

Imports

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

create Fully Connected Network

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
  

#Set Device

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

Hyperparameters

input_size = 784
num_classes = 10
learning_rate = 0.001
batch_size = 2
num_epochs = 1
  

Load Data

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)
  

Initialize network

model = NN(input_size=input_size, num_classes=num_classes).to(device)
  

Loss and optimizer

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
  

Train network

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)

I am getting the error on this line

train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)

Error is

in <module> train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) TypeError: 'module' object is not callable


Solution

  • You need to edit your import

    from torch.utils.data import DataLoader, Dataset