Converting list to numpy array

PythonNumpyScikit Learn

Python Problem Overview


I have managed to load images in a folder using the command line sklearn: load_sample_images()

I would now like to convert it to a numpy.ndarray format with float32 datatype

I was able to convert it to np.ndarray using : np.array(X), however np.array(X, dtype=np.float32) and np.asarray(X).astype('float32') give me the error:

> ValueError: setting an array element with a sequence.

Is there a way to work around this?

from sklearn_theano.datasets import load_sample_images
import numpy as np  

kinect_images = load_sample_images()
X = kinect_images.images

X_new = np.array(X)  # works
X_new = np.array(X[1], dtype=np.float32)  # works

X_new = np.array(X, dtype=np.float32)  # does not work

Python Solutions


Solution 1 - Python

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPriya NarayananView Question on Stackoverflow
Solution 1 - PythonThom IvesView Answer on Stackoverflow