close

[Solved] Tensorflow : logits and labels must have the same first dimension

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Tensorflow : logits and labels must have the same first dimension in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Tensorflow : logits and labels must have the same first dimension Error Occurs?

Today I get the following error Tensorflow : logits and labels must have the same first dimension in python.

How To Solve Tensorflow : logits and labels must have the same first dimension Error ?

  1. How To Solve Tensorflow : logits and labels must have the same first dimension Error ?

    To Solve Tensorflow : logits and labels must have the same first dimension Error I resolved it changing from sparse_categorical_crossentropy to categorical_crossentropy and is now running fine.

  2. Tensorflow : logits and labels must have the same first dimension

    To Solve Tensorflow : logits and labels must have the same first dimension Error I resolved it changing from sparse_categorical_crossentropy to categorical_crossentropy and is now running fine.

Solution 1

The problem is in your target shape and is related to the correct choice of an appropriate loss function. you have 2 possibilities:

1. possibility: if you have 1D integer encoded target, you can use sparse_categorical_crossentropy as loss function

n_class = 3
n_features = 100
n_sample = 1000

X = np.random.randint(0,10, (n_sample,n_features))
y = np.random.randint(0,n_class, n_sample)

inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)

model = Model(inp, out)
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)

2. possibility: if you have one-hot encoded your target in order to have 2D shape (n_samples, n_class), you can use categorical_crossentropy

n_class = 3
n_features = 100
n_sample = 1000

X = np.random.randint(0,10, (n_sample,n_features))
y = pd.get_dummies(np.random.randint(0,n_class, n_sample)).values

inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)

model = Model(inp, out)
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)

Solution 2

I resolved it changing from sparse_categorical_crossentropy to categorical_crossentropy and is now running fine.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read