0

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?

1
  • 1
    This is very suspect for something that's supposed to be a scalar: feature[0] / np.linalg.norm(feature[0]) Commented Aug 21, 2020 at 12:35

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.