What is error in this code pytorch

import torch
import torch.nn as nn
import torch.optim as optim

train_loader = torch.utils.data.DataLoader(cifar2, batch_size=64,
shuffle=True)

model = nn.Sequential(
nn.Linear(3072, 128),
nn.Tanh(),
nn.Linear(128, 2),
nn.LogSoftmax(dim=1))

learning_rate = 1e-2

optimizer = optim.SGD(model.parameters(), lr=learning_rate)

loss_fn = nn.NLLLoss()

n_epochs = 100

for epoch in range(n_epochs):
for imgs, labels in train_loader:
outputs = model(imgs.view(imgs.shape[0], -1))
loss = loss_fn(outputs, labels)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

print("Epoch: %d, Loss: %f" % (epoch, float(loss)))

i have this error
TypeError: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found <class ‘PIL.Image.Image’>
i can not fixed it?

Transform the PIL.Images to tensors. I don’t know how cifar2 is defined, but assume you can pass transform=transforms.ToTensor() to its init.

it correct ?
imgs,labels=cifar2[0]
to_tensor=transforms.ToTensor()
imge=to_tensor(imgs)
imge.shape

I think @ptrblck had asked you to pass this transforms to the dataset set class when you are initializing it, there should be a parameter taking transforms if not that then what you have done will also work.

1 Like

Yes, @shalom_p is right and if you are using torchvision.datasets.CIFAR10, just it to the transform argument. If you are using another class definition, check its docs.

1 Like