【问题标题】:Value error while converting tensor to numpy array将张量转换为 numpy 数组时出现值错误
【发布时间】:2020-12-10 19:02:45
【问题描述】:

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

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

我怎样才能解决它?

【问题讨论】:

  • 这对于应该是标量的东西非常可疑:feature[0] / np.linalg.norm(feature[0])

标签: python numpy pytorch torch resnet


【解决方案1】:

您似乎有一个tensors 列表,您不能这样直接转换。

您需要先将内部张量转换为 NumPy 数组(使用torch.Tensor.numpy 将张量转换为数组),然后将 NumPy 数组列表转换为最终数组。

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

【讨论】:

    【解决方案2】:

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

    我假设特征包含二维张量

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2021-10-17
      • 2018-11-28
      • 2020-12-31
      • 1970-01-01
      • 2021-01-08
      相关资源
      最近更新 更多