How can I know if weights were loaded in Keras Model?

Viewed 5662

I am using keras for tensorflow 1.4. For some unknown reason, I continue failing when I try to download the weights (vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5') using:

base_model = VGG16(weights='imagenet', include_top=False)

so I manually downloaded the weights from the link cited in the script. https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5

Since the VGG16's weight cannot be set to the path of the weights (it has to be imagenet or None), I used the code lines:

 base_model = VGG16(weights=None, include_top=False)
 path = os.path.join('weights','vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5')
 base_model.load_weights(path)

It is the same than base_model = VGG16(weights='imagenet', include_top=False) ? How can I check that the weights and outputs are correct?

1 Answers

You can access the weights in an .h5 file as:

w1 = h5py.File('someFile.h5')
allKeys = w1.keys()
first_layer_wts = w1[allKeys[0]][:]  # assuming first layer has weights

After you load the weights in a Keras model, then you can access them as:

w2 = model.get_weights()

Now check if first_layer_wts and the corresponding weights in w2 are equal. This may need some tweaking. For example, if the layer is convolutional, then you have two weight arrays (one for kernel and another for bias). You can access them both as:

first_layer_wts_kernel = w1[allKeys[0]]['kernel'][:]
first_layer_wts_bias = w1[allKeys[0]]['bias'][:]

You can figure this out by always checking the available keys.

Related