1

I am doing a Computer Vision project in which I am getting an error 'setting an array element with a sequence' when I am trying to change the data type of input image matrix. I realized this is happening because the input image matrix I am having does not have the same number of elements in all of its array. Is there any way I can convert that input image into the 2D array with the same number of elements in each of its array?

I am getting an error when I am trying to execute the following line: X_train = X_train.astype('float32')

Any help would be appreciated. Cheers.

1 Answer 1

0

You need to pad the rows with less elements with zeros to make their lengths equal to the length of the longest array (or list) in the list of lists (matrix). Below's a code snippet to pad a list of lists of unequal lengths to a matrix of same row-lengths:

import numpy as np
unpadded_matrix = np.array([[1, 2], [3, 4, 5], [6, 7, 8, 9]])
max_len = max([len(row) for row in unpadded_matrix])
np.array([row + [0]*(max_len-len(row)) for row in unpadded_matrix])

o/p:

array([[1, 2, 0, 0],
       [3, 4, 5, 0],
       [6, 7, 8, 9]])
3
  • Thanks for your help. But now I am getting another error saying, operands could not be broadcast together with shapes (50,50,3) (0,). My X_train.shape is (416286,). Commented Jan 7, 2020 at 14:14
  • Could you post the full code? I guess the code is breaking due to a reason different from the padding issue discussed above. Commented Jan 7, 2020 at 14:50
  • The data I have is about detecting cancer. So I first loaded the unlabeled data and manually created labels using notations. I used one hot encoding for y_train and y_test y_train = to_categorical(y_train_labels) y_test = to_categorical(y_test_labels) but when execute following line of code which you gave, it gives me error max_len = max([len(row) for row in X_train]) np.array([row + [0]*(max_len-len(row)) for row in X_train]) Note: In X_train, I have both class images i.e. with cancer and without cancer which I manually amalgamated. Commented Jan 8, 2020 at 4:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.