How to convert strings to tensors

Hi,
I am trying to create a dataset class for a problem, In that all the targets are in the form of a string like “Airplane”, “tree” etc. When I am trying to convert it into a tensor is says that TypeError: must be real number, not string, also when I am trying to convert image to tensor it says TypeError: must be real number, not JpegImageFile.
Here is my code:

class HolidayDataset(Dataset):
    def __init__(self, df, transform=None):
        self.df = df
        self.transforms = transform
        
    def __len__(self):
        return len(self.df)
    
    def __getitem__(self, idx):
        img_name = 'Input/dataset/train/' + self.df.Image[idx]
        target = self.df.Class[idx]
        img = Image.open(img_name)
        if self.transforms:
            img = self.transforms(img)
        return {
            "img": torch.tensor(img, dtype=torch.float),
            "target": torch.tensor(target, dtype=torch.float)
        }

You would have to map the words to indices as e.g. described in this tutorial first and could then create the tensors containing the numerical values.

The second error is raised, if the JPEG file descriptor instead of an already loaded image array is passed to the tensor creation. Make sure img is transformed to a tensor in the self.transforms or create it from a numpy array via torch.from_numpy.

2 Likes

Hi guys,
Please how I can convert Sequential to tensor.

The nn.Sequential module is used to execute multiple layers in a sequential manner, while tensors are used as the input, output, weights (wrapped into nn.Parameter) etc., so I’m unsure how these objects could be converted.
Could you explain your use case a bit more, please?

I have two Sequentials

 else:

           in_rgb = nn.Sequential(
           Conv(3, 32,1),
           Conv(3, 64,2),
           Bottleneck(64, 64)
         )
           print("in_rgb",in_rgb)


           in_ther = nn.Sequential(
           Conv(3, 32, 1),
           Conv(3, 64,2),
           Bottleneck(64, 64)
         )
           print("in_ther",in_ther)


           out = torch.nn.Sequential(in_rgb,in_ther)

           print("out1",out) 

          # b = torch.Tensor(s_cat)
           
         

           #out = torch.cat((in_rgb, in_ther), dim=1)
           #out = torch.cat((out,m), dim=1)
          # out = torch.nn.Sequential(*(list(b)),m)

           return self.forward_once(out, profile)  # single-scale inference, train

when i run my code i have error

Traceback (most recent call last):
  File "train.py", line 622, in <module>
    train(hyp, opt, device, tb_writer, wandb)
  File "train.py", line 79, in train
    model = Model(opt.cfg or ckpt['model'].yaml, ch=6, nc=nc).to(device)  # create
  File "/content/drive/My Drive/yolov3_v0/models/yolo.py", line 98, in __init__
    m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, 3, s, s),torch.zeros(1, 3, s, s))])  # forward
  File "/content/drive/My Drive/yolov3_v0/models/yolo.py", line 170, in forward
    return self.forward_once(out, profile)  # single-scale inference, train
  File "/content/drive/My Drive/yolov3_v0/models/yolo.py", line 186, in forward_once
    out = m(out)  # run
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/content/drive/My Drive/yolov3_v0/models/common.py", line 37, in forward
    return self.act(self.bn(self.conv(x)))
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py", line 399, in forward
    return self._conv_forward(input, self.weight, self.bias)
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py", line 396, in _conv_forward
    self.padding, self.dilation, self.groups)
TypeError: conv2d(): argument 'input' (position 1) must be Tensor, not Sequential

So i think i should cast Sequential to Tensor.

I assume that self.forward_once is expecting an input and executed the forward pass using this input tensor.
Currently you are passing the nn.Sequential container as the input to this method, which seems wrong.
Note that modules (layers) expect input tensors, not other modules, in their forward method.

1 Like