user1241241
user1241241

Reputation: 674

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?

Upvotes: 0

Views: 569

Answers (2)

Mughees
Mughees

Reputation: 953

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)

Upvotes: 1

Dishin H Goyani
Dishin H Goyani

Reputation: 7723

It seems you have a list of tensors you can not convert directly like that.

You need to convert internal tensors into NumPy array first (Use torch.Tensor.numpy to convert tensor into the array) and then list of NumPy array to the final array.

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

Upvotes: 1

Related Questions