Monday, June 08, 2026

[SOLVED] Tuple index out of range in TensorFlow model fit function

When training a Keras or TensorFlow model you may hit an IndexError: tuple index out of range the moment you call model.fit(), even though your data looks fine. The cause is almost always the type of the data you passed in, not the model. This post explains why it happens and the one-line fix.

The problem code

Here training data is built up as plain Python lists and passed straight to fit:

x_train = []
y_train = []
# ... append samples to the lists ...

history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)

This raises:

IndexError: tuple index out of range

Why it happens

Keras needs to know the shape of your input to wire up the first layer and to split data into batches. It reads that shape from the .shape attribute of the array you pass in, which is a tuple like (num_samples, features). A NumPy array has this attribute; a plain Python list does not. When TensorFlow tries to index into the shape tuple of a list-like object that reports an empty or zero-dimensional shape, the index it expects is not there, and you get tuple index out of range. In short, the framework expected an array with real dimensions and received a bare list.

The solution

Convert the lists to NumPy arrays before calling fit:

import numpy as np

history = model.fit(np.array(x_train), np.array(y_train),
                    batch_size=batch_size, epochs=epochs)

Now x_train.shape and y_train.shape return proper tuples, Keras can read the input dimensions, and training proceeds normally.

Good practice

Build your data as lists if that is convenient, but convert once to arrays right before training, and check the shapes to catch problems early:

x_train = np.array(x_train)
y_train = np.array(y_train)
print(x_train.shape, y_train.shape)

history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)

If the printed shapes are not what you expect (for example a ragged list that NumPy turns into a 1-D object array), fix the data first; that same mismatch is a common second cause of this error.

Reference

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.