Hi, I was working with sequential models using Keras 3, and I noticed that the output layer name of the current layer is different from the input layer name of the next layer. Let me explain in detail:

I have a sequential model which uses 2 Dense layer. When I printed the input and output name of each of those layers I noticed this:

Model definition:

import keras
import numpy as np

x_train = np.random.rand(32, 10)
y_train = np.random.rand(32, 10)

model = models.Sequential([
    layers.Input(shape=(10,)),
    layers.Dense(20, activation='relu'),
    layers.Dense(10, activation='tanh')
])

model.compile(
    optimizer='adam',
    loss='mean_squared_error',
    metrics=['mae']
)

model.fit(x_train, y_train, epochs=1)
model.save('Dense_model.h5')

Code to print input and output layer names

model = models.load_model('Dense_model.h5')
for layer in model.layers:
    print(layer.input.name)
    print(layer.output.name)
    print()

Output:

Image

Shouldn't the keras_tensor_47 and keras_tensor_48 have the same name?

If the names are not supposed to be the same, then how Keras handles the layer sequence internally? I also noticed that this particular scenario seems to be occurring only in when I load this model from my disk. Whenever I train it and then directly use it as it (basically from memory) this doesn't happen

Image

And this doesn't happen with Keras 2.x

Image

Package information Keras: 3.11.1 Tensorflow: 2.17.0 Numpy: 1.26.4

Comment From: sonali-kumari1

Hi @PrasannaKasar - Thanks for reporting this. When a model is saved and then loaded, Keras reconstructs the computational graph and regenerates internal tensor or model variable names, which may result in different numerical suffixes for the same logical connections between layers(e.g keras_tensor_47 ,keras_tensor_48). However, this does not affect the functional connection between layers.

For accessing specific variables, it is recommended to use layer attributes (e.g. model.get_layer("dense_1").kernel). Please refer to this documentation for more details on model loading.

Comment From: github-actions[bot]

This issue is stale because it has been open for 14 days with no activity. It will be closed if no further activity occurs. Thank you.

Comment From: google-ml-butler[bot]

Are you satisfied with the resolution of your issue? Yes No