keras-team / keras-io

Keras documentation, hosted live at keras.io
Apache License 2.0
2.78k stars 2.05k forks source link

Grad-CAM example does not work with sequential models #1903

Open jasperchess opened 3 months ago

jasperchess commented 3 months ago

Issue Type

Documentation Bug

Source

source

Keras Version

3.4.1

Custom Code

No

OS Platform and Distribution

MacOS 14.4.1

Python version

3.12.3

GPU model and memory

No response

Current Behavior?

When trying to use the example Grad-CAM algorithm from the documentation, it didn't seem to work with a Sequential model.

Perhaps I am wrong, but I believe that instead of using model.output on a Sequential model, one should use model.layers[-1].output. Please correct me if I'm mistaken.

Suggested fix If my assumption is correct, it may be worth adding a note to the documentation/a comment to the snippet where it is relevant.

Thanks!

Standalone code to reproduce the issue or tutorial link

model = keras.Sequential([
    keras.layers.InputLayer(shape=(256, 256, 3)),
    keras.layers.BatchNormalization(),
    keras.layers.Conv2D(64, (3, 3), activation='relu', strides=2),
    keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
    keras.layers.Conv2D(128, (3, 3), activation='relu', strides=2),
    keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
    keras.layers.Conv2D(256, (3, 3), activation='relu'),
    keras.layers.Conv2D(256, (3, 3), activation='relu'),
    keras.layers.Conv2D(128, (3, 3), activation='relu'),
    keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
    keras.layers.Conv2D(128, (3, 3), activation='relu'),
    keras.layers.Flatten(),
    keras.layers.Dense(4096, activation='relu'),
    keras.layers.Dense(4096, activation='relu'),
    keras.layers.Dropout(0.4),
    keras.layers.Dense(1, activation='sigmoid'),
])

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=0.0001),
    loss='binary_crossentropy',
    metrics=[
        keras.metrics.BinaryAccuracy(),
        keras.metrics.Precision(),
        keras.metrics.Recall(),
        keras.metrics.F1Score(),
        keras.metrics.AUC(num_thresholds=3)
    ]
)

history = model.fit(
    train_dataset,
    epochs=5,
    validation_data=validation_dataset,
)

... REST OF THE GRAD-CAM EXAMPLE ...

Relevant log output

ValueError: The layer sequential has never been called and thus has no defined output.