如何解决将张量转换为numpy数组时出现值错误
我正在使用以下代码从图像中提取特征。
def ext():
imgPathList = glob.glob("images/"+"*.JPG")
features = []
for i,path in enumerate(tqdm(imgPathList)):
feature = get_vector(path)
feature = feature[0] / np.linalg.norm(feature[0])
features.append(feature)
paths.append(path)
features = np.array(features,dtype=np.float32)
return features,paths
但是,上面的代码引发了以下错误,
features = np.array(features,dtype=np.float32)
ValueError: only one element tensors can be converted to Python scalars
我该如何解决?
解决方法
似乎您有tensors
的列表,您无法像这样直接转换。
首先需要将内部张量转换为NumPy数组(使用torch.Tensor.numpy
将张量转换为NumPy数组),然后将NumPy数组列表转换为最终数组。
features = np.array([item.numpy() for item in features],dtype=np.float32)
,
错误表明您的features
变量是一个包含无法转换为张量的多维值的列表,因为.append
正在将张量转换为列表,因此一些解决方法是使用串联函数以torch.cat()
(读取here)代替附加方法。我试图用玩具示例来复制解决方案。
我假设要素包含2D张量
import torch
for i in range(1,11):
alpha = torch.rand(2,2)
if i<2:
beta = alpha #will concatenate second sample
else:
beta = torch.cat((beta,alpha),0)
import numpy as np
features = np.array(beta,dtype=np.float32)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。