Error while appending tensors to a list

I want to append 2 tensors of different size in a list and later I want to put all of it into dataloader.
x_train is a numpy array of 277 numpy arrays
and y_train is a numpy array of 277 scalars

image_transforms = {
    "train": transforms.Compose([transforms.ToPILImage(),
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        transforms.Normalize([0.5, 0.5, 0.5],
                             [0.5, 0.5, 0.5])
    ]),
    "test": transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        transforms.Normalize([0.5, 0.5, 0.5],
                             [0.5, 0.5, 0.5])
    ])
}
print(x_train[1].shape)
trainset=[]
testset=[]
train=image_transforms['train']
for i in range(x_train.shape[0]):
    trainset.append([torch.tensor(train(x_train[i]),torch.tensor(y_train))])
trainset

Error

TypeError                                Traceback (most recent call last)
<ipython-input-26-66fc15feb658> in <module>
      4 train=image_transforms['train']
      5 for i in range(x_train.shape[0]):
----> 6     trainset.append([torch.tensor(train(x_train[i]),torch.tensor(y_train))])
      7 trainset

TypeError: tensor() takes 1 positional argument but 2 were given

Probably your dataset returns 2 values. But to create a tensor you need to pass only 1 value.

1 Like

x_train is an array of arrays which are nothing but pixel values of images.
Total arrays in x_train are 277 and y_train is an array of 277 scalars
It returns one value each.

The error is raise, as you are trying to pass multiple numpy arrays/scalars to torch.tensor as seen here:

torch.tensor(np.random.randn(1), np.random.randn(2))
> TypeError: tensor() takes 1 positional argument but 2 were given

Transform the numpy arrays to tensors first via torch.from_numpy and use torch.cat or torch.stack to create the single tensor.