Unable to load chexnet pre-trained weight file to Densenet121

1.1k views Asked by At

Im trying to load Keras chexNet weight file to Densenet121, https://www.kaggle.com/theewok/chexnet-keras-weights

I'm getting ValueError: You are trying to load a weight file containing 242 layers into a model with 241 layers. if I Call densenet121

densenet = tf.keras.applications.DenseNet121(
include_top=False,
weights="CheXNet_Keras_0.3.0_weights.h5",
input_shape=(224,224,3)
)

If I try:-

densenet = tf.keras.applications.DenseNet121(
include_top=True,
weights="CheXNet_Keras_0.3.0_weights.h5",
input_shape=(224,224,3)
)

I'll get ValueError: Shapes (1024, 1000) and (1024, 14) are incompatible

2

There are 2 answers

0
thisisme On

The answer with popping the last layer does now work anymore, pop only returns the last layer but the model remains unchanged.

I recommend something like this:

densenet = DenseNet121(weights=None, include_top=False, 
                       input_shape=(224, 224, 3), pooling="avg")
output = tf.keras.layers.Dense(14, activation='sigmoid', name='output')(densenet.layers[-1].output)
model = tf.keras.Model(inputs=[densenet.input], outputs=[output])
model.load_weights("./CheXNet_weights.h5")
0
GrimSqueaker On

They saved the model without the correct output layer, here's the fix:

base_model = densenet.DenseNet121(weights=None,
                            include_top=False,
                            input_shape=(224,224,3), pooling="avg")

predictions = tf.keras.layers.Dense(14, activation='sigmoid', name='predictions')(base_model.output)
base_model = tf.keras.Model(inputs=base_model.input, outputs=predictions)
base_model.load_weights("./temp/CheXNet_Keras_0.3.0_weights.h5")
base_model.layers.pop()

print("CheXNet loaded")