如何在pytorch中将字符串列表转换为张量?

2024-04-28 23:09:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究分类问题,在这个问题中,我有一个字符串列表作为类标签,我想把它们转换成张量。到目前为止,我已经尝试使用numpy模块提供的np.array函数将字符串列表转换为numpy array

truth = torch.from_numpy(np.array(truths))

但我有以下错误。

RuntimeError: can't convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8.

有人能提出另一种方法吗?谢谢


Tags: 模块函数字符串fromnumpy列表错误np
2条回答
truth = [float(truths) for x in truths]
truth = np.asarray(truth)
truth = torch.from_numpy(truth)

不幸的是,你现在不能。我不认为这是一个好主意,因为它会使火把笨拙。一种流行的解决方法可以使用sklearn将其转换为数值类型。

下面是一个简短的例子:

from sklearn import preprocessing
import torch

labels = ['cat', 'dog', 'mouse', 'elephant', 'pandas']
le = preprocessing.LabelEncoder()
targets = le.fit_transform(labels)
# targets: array([0, 1, 2, 3])

targets = torch.as_tensor(targets)
# targets: tensor([0, 1, 2, 3])

由于可能需要在真标签和转换标签之间进行转换,因此最好存储变量le

相关问题 更多 >