将张量转换为 numpy 数组时出现值错误

Value error while converting tensor to numpy array

我正在使用以下代码从图像中提取特征。

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 数组列表转换为最终数组。

features = np.array([item.numpy() for item in features], dtype=np.float32)

错误说你的 features 变量是一个列表,其中包含无法转换为张量的多维值,因为 .append 正在将张量转换为列表,所以一些解决方法是使用torch 的连接函数为 torch.cat()(阅读 here)而不是 append 方法。我试图用玩具示例复制解决方案。

我假设特征包含二维张量

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)