Index error in keras after reshaping array

Viewed 75

I am using a .csv file for the image data, which I reshape into a 2d numpy array to represent images.

I am not sure what I am missing, and I keep getting an "IndexError: list index out of range" when fitting the model.

train_data = pd.read_csv('sign_mnist_train.csv')
test_data = pd.read_csv('sign_mnist_test.csv')

train_labels = train_data.pop('label').to_numpy().reshape(-1, 1)
test_labels = test_data.pop('label').to_numpy().reshape(-1, 1)

train_images = train_data.to_numpy().reshape(-1, 28, 28, 1) / 255.0
test_images = test_data.to_numpy().reshape(-1, 28, 28, 1) / 255.0

def make_model():
    model = models.Sequential()
    
    model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)))
    model.add(layers.MaxPool2D((2,2)))
    model.add(layers.Conv2D(64, (3,3), activation='relu'))
    model.add(layers.MaxPool2D(2,2))
    model.add(layers.Conv2D(64, (3,3), activation='relu'))

    model.add(layers.Flatten())
    model.add(layers.Dense(64))
    model.add(layers.Dense(25))

    model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy,
                  metrics=['accuracy'])
    
    return model

model = make_model()
model.fit(train_images, train_labels, epochs=5, validation_data(test_images, test_labels))

The full traceback: 1 2 3

1 Answers

I suppose the issue is from this train.data, as per the test images you named them test_data. Also you're reshaping them into a 4D Tensor and not a 2D Tensor based on the code.

train_images = train_data.to_numpy().reshape(-1, 28, 28, 1) 
test_images = test_data.to_numpy().reshape(-1, 28, 28, 1) 

train_images = train_images / 255.0
test_images = test_images / 255.0

Edit: Check if applying one-hot encoding to the target variables helps

train_labels = tf.keras.utils.to_categorical(train_labels)
Related