Search code examples
pythontensorflowmachine-learningkerastransfer-learning

Transfer learning with Keras and CNN: Received a label value of 46 which is outside the valid range of [0, 5)


I have trained a Sequential model with a dataset having 43 classes; each class name is 0 - 43 and they're derived from the directories' names. Now I want to use transfer learning to create a new model on top of the previously trained model, with the new data having classes of 43 - 47. Now the problem is when I add 5 (the count of my labels 43-47) as number of classes in the Dense layer it shows this error:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Received a label value of 46 which is outside the valid range of [0, 5).

So how do I add the number of classes in the Dense layer starting from 44, not zero (0)?

Here is my transfer model code:

model_old = load_model('model.h5')

model_new = tf.keras.models.Sequential()

for layer in model_old.layers[:-1]:
    layer.trainable = False
    model_new.add(layer)

model_new.add(tf.keras.layers.Dense(5, activation="softmax"))
model_new.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) 

Solution

  • Please check if your call the tf.keras.utils.to_categorical(y, num_classes=None, dtype='float32') function that converts your Y vector contating labels (43-47) into a matrix of integers from 0 to num_classes = 5 in your case (0,1,2,3,4). Hope this will be helpful.