DSH
DSH

Reputation: 1139

How to convert list of str into Pytorch tensor

How do I convert a list of strings into a string/character tensor in Pytorch?

Related example with numpy:

import numpy as np

mylist = ["this","is","my","list"]

np.array([mylist])

Returns:

array([['this', 'is', 'my', 'list']], dtype='<U4')

However, in pytorch:

torch.tensor(mylist)

Returns:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-156-36722d81da09> in <module>
----> 1 torch.tensor(mylist)

ValueError: too many dimensions 'str'

A tensor is a multi-dimensional array, so I'm assuming this is possible pytorch.

Note: this post does not answer my question

Upvotes: 2

Views: 11353

Answers (1)

sujay
sujay

Reputation: 395

There is no string tensor so you cannot directly convert to pytorch tensor of strings.

Alternative, you can convert the string to ASCII char values and save that as a Tensor.

Upvotes: 6

Related Questions