Search code examples
pytorchtorch

TypeError: can't assign a str to a torch.LongTensor pytoch


I'm trying to convert a list of strings into tensors but I get this error

lengths = [len(cap) for cap in captions]
    targets = torch.zeros(len(captions), max(lengths)).long()
    for i, cap in enumerate(captions):
        end = lengths[i]
        targets[i, :end] = cap[:end]

Solution

  • You can use python's ord to convert characters to their unicode:

    targets[i, :end] = torch.from_numpy(np.array(list(map(ord, cap[:end])))).to(torch.long)