Reputation: 45
I'm creating a CNN using Keras 2.0.8, with tensorflow backend. I'm trying to get the weight matrix of the first convolution layer as shown below:
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=(3,3),
input_shape=
(9,9,1),activation='relu',kernel_regularizer =l2(regularization_coef)))
model.add(Conv2D(filters=64, kernel_size=
(3,3),activation='relu',kernel_regularizer = l2(regularization_coef)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(128,activation='relu',kernel_regularizer =
l2(regularization_coef)))
model.add(Dropout(0.5))
model.add(Dense(2,activation='softmax',kernel_regularizer =
l2(regularization_coef)))
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',metrics=['accuracy'])
model.summary()
model.fit(X_train, Y_train, batch_size=batch_size, epochs=nb_epoch,
verbose=0, validation_split=0.1)
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
filters= model.layers[0].get_weights()[0]
print(filters.shape)
The first layer, as you can see is a 2d convolution layer with 16 filters, of kernel size (3,3) and 1 input channel. So the last line should give me a shape of (16,1,3,3), but instead I get a shape of (3,3,1,16). I want to visualise the weights as 16 3x3 matrices, but I'm not able to do that because of this shape problem. Can someone please help me out? Thanks in advance!
Upvotes: 0
Views: 1236
Reputation: 6365
You can transpose the array to move the 16 to the beginning, and then reshape it to (16, 3, 3).
filters= model.layers[0].get_weights()[0]
print(filters.shape)
# (3,3,1,16)
filters = filters.transpose(3,0,1,2)
print(filters.shape)
# (16, 3, 3, 1)
filters = filters.reshape((16,3,3))
print(filters.shape)
# (16, 3, 3)
Upvotes: 1