如何在pytorch中将字符串列表转换为张量? [英] How to convert a list of strings into a tensor in pytorch?

查看:2449
本文介绍了如何在pytorch中将字符串列表转换为张量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理分类问题,在该问题中,我有一个字符串列表作为类标签,并且希望将它们转换为张量.到目前为止,我已经尝试使用numpy模块提供的np.array函数将字符串列表转换为numpy array.

I am working on classification problem in which I have a list of strings as class labels and I want to convert them into a tensor. So far I have tried converting the list of strings into a numpy array using the np.array function provided by the numpy module.

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.

有人可以建议替代方法吗?谢谢

Can anybody suggest an alternative approach? Thanks

推荐答案

很遗憾,您现在不能.而且我认为这不是一个好主意,因为它会使PyTorch变得笨拙.一个流行的解决方法是使用 sklearn 将其转换为数字类型

Unfortunately, you can't right now. And I don't think it is a good idea since it will make PyTorch clumsy. A popular workaround could convert it into numeric types using 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.

Since you may need the conversion between true labels and transformed labels, it is good to store the variable le.

这篇关于如何在pytorch中将字符串列表转换为张量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆