Why do I get the error "TypeError: object of type 'NoneType' has no len()"?

hello,

I am getting the error “TypeError: object of type ‘NoneType’ has no len()” and I do not know why it is happening.

This error is triggered by the training loop which is:

def training_loop(
        n_epochs,
        optimizer,
        model,
        loss_fn,
        train_loader):
    for epoch in range(1, n_epochs + 1):
        loss_train = 0.0
        for i, (imgs, labels) in enumerate(train_loader):

            outputs = model(imgs)

            loss = loss_fn(outputs, labels)

            optimizer.zero_grad()

            loss.backward()

            optimizer.step()

            loss_train += loss.item()

        if epoch == 1 or epoch % 10 == 0:
            print('{} Epoch {}, Training loss {}'.format(
                datetime.datetime.now(),
                epoch,
                loss_train / len(train_loader)))

here is the rest of the relevant code:


def instantiate_data(data_path, isTraining):
    """A higher-order procedure that instantiates training or val datasets.

      It transforms each PIL image to a Pytorch Tensor.

      Moreover, it normalizes the data.

      DATA_PATH -> DATASET"""
    return datasets.MNIST(data_path,
                          train=isTraining,
                          download=True,
                          transform=transforms.Compose([
                              transforms.ToTensor(),
                              transforms.Normalize((0.0839, 0.2039, 0.1042),
                                                   (0.2537, 0.3659, 0.2798))]))

def instantiate_training_data(data_path):
    """This function instantiates the training dataset."""
    instantiate_data(data_path, True)
model = Net()

data_path = "../Mnist/"

print("instatiate data")
mnist = instantiate_training_data(data_path)
print("training loader")
train_loader = torch.utils.data.DataLoader(mnist, batch_size=64)
print("optimizer")
optimizer = optim.SGD(model.parameters(), lr=1e-2)
print("loss")
loss_fn = nn.CrossEntropyLoss()
print("training loop")

training_loop(
    n_epochs = 100,
    optimizer = optimizer,
    model = model,
    loss_fn = loss_fn,
    train_loader = train_loader,
    )

here is the error message:
File "/home/sphere3/classify_mnist/src/train.py", line 11, in training_loop for i, (imgs, labels) in enumerate(train_loader):

thanks!

You must add return term beginning of the instantiate_data(data_path, True) in the ‘instantiate_training_data’ function.