model-optimization icon indicating copy to clipboard operation
model-optimization copied to clipboard

ValueError: `to_annotate` can only be a `keras.layers.Layer` instance. You passed an instance of type: Dense.

Open ningjingzhiwei opened this issue 6 months ago • 1 comments

import tensorflow as tf from tensorflow.keras import layers, models import tensorflow_model_optimization as tfmot

input_shape = (20,) annotated_model = tf.keras.Sequential([ tfmot.quantization.keras.quantize_annotate_layer(tf.keras.layers.Dense(20, input_shape=input_shape)), tf.keras.layers.Flatten() ])

quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model) quant_aware_model.summary()

when I run the above code, it appears error like: "ValueError: to_annotate can only be a keras.layers.Layer instance. You passed an instance of type: Dense."

Does anyone know the way to handle it? Thanks a lot.

ningjingzhiwei avatar Jun 12 '25 08:06 ningjingzhiwei

it looks like you are using one of the latest versions of tensorflow/keras 3+, based on the error. Try installing tf-keras. Then:

import tf_keras as keras
import os

os.environ["TF_USE_LEGACY_KERAS"]="1"

import tensorflow_model_optimization as tfmot

input_shape = (20,)
annotated_model = keras.Sequential([
tfmot.quantization.keras.quantize_annotate_layer(keras.layers.Dense(20, input_shape=input_shape)),
keras.layers.Flatten()
])

quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
quant_aware_model.summary()

anasvaf avatar Jun 19 '25 09:06 anasvaf