2
votes

I have a python list than includes 90900 nparrays shaped (299, 299, 3). I tried to convert this list to numpy array

X_trains = np.asarray(X_train).reshape((len(X_train),299,299,3))

However, this gave me the error:

ValueError: could not broadcast input array from shape (299,299,3) into shape (299,299)

I suppose that the part of the code that cause the error is np.asarray, is there any way to fix that?

Full error code:

ValueErrorTraceback (most recent call last)
<ipython-input-34-2ba5db77f6b1> in <module>()
  1 
  2 
----> 3 X_trains = np.asarray(X_train)

/usr/local/lib/python3.4/dist-packages/numpy/core/numeric.py in asarray(a,          dtype, order)
529 
530     """
--> 531     return array(a, dtype, copy=False, order=order)
532 
533 

ValueError: could not broadcast input array from shape (299,299,3) into shape (299,299)
2
I want to shape my data as a 4 dimensional array (It's image files) (number of images, height, length, color channels) - Lau
@kmario23 You were right! The problem was that I didn't realize that there were some grayscale images, which messed things up. - Lau
Ok. Good that you figured out the issue! - kmario23

2 Answers

1
votes

No, the problem is because of the reshape(). The asarray() function will convert your list to a proper Numpy array, you don't need to reshape it.

Here is an example:

In [1]: a = [[1, 2], [4, 5]]

In [2]: import numpy as np

In [3]: np.asarray(a)
Out[3]: 
array([[1, 2],
       [4, 5]])

If you want to reshape the array still after converting to a Numpy array, the new shape should be proper enough for broadcasting the older array to the new one.

You can get the shape and see if it's convertible to your expected one:

X_trains = np.asarray(X_train)
old_shape = X_trains.shape
0
votes

I understand your problem. There is no need to reshape it. Just np.asarray would do the job

X_trains = np.asarray(X_train)

Example:

In [18]: arr_3d
Out[18]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])


In [19]: list_of_arr = [arr_3d, arr_3d]

In [20]: arr_4d = np.asarray(list_of_arr)

In [21]: arr_4d.shape
Out[21]: (2, 2, 3, 3)