Search code examples
pythonnumpypytorchtorchresnet

Value error while converting tensor to numpy array


I'm using the following code to extract the features from image.

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

However, the above code throws the following error,

 features = np.array(features, dtype=np.float32)
ValueError: only one element tensors can be converted to Python scalars

How can I be able to fix it?


Solution

  • The error says that your features variable is a list which contains multi dimensional values which cant be converted to tensor, because .append is converting the tensors to list, So some workaround is to use concatenation function of torch as torch.cat() (read here) instead of append method. I tried to replicate the solution with toy example.

    I am assuming that features contain 2D tensor

    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)