2

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)
3
  • I want to shape my data as a 4 dimensional array (It's image files) (number of images, height, length, color channels) Commented Apr 8, 2017 at 13:18
  • @kmario23 You were right! The problem was that I didn't realize that there were some grayscale images, which messed things up. Commented Apr 8, 2017 at 13:28
  • Ok. Good that you figured out the issue! Commented Apr 8, 2017 at 13:28

2 Answers 2

1

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

2 Comments

nope the problem is clearly in np.asarray, I included the full error code, hope it would make more sense
@Wideem This answer is because of the fact that your list contain similar shaped lists. But if the error is because of the asarray this means that you have a mismatch in your sub lists.
0

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)

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.