将张量转换为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)