我使用Keras 2.0.8创建CNN,并使用tensorflow后端。我试图得到第一个卷积层的权重矩阵,如下所示:
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)
第一层,如您所见,是一个带有16个滤波器的2d卷积层,内核大小(3,3)和1个输入通道。所以最后一行应该给我一个(16,1,3,3)的形状,但我得到一个(3,3,1,16)的形状。我想将权重可视化为16个3x3矩阵,但由于这种形状问题,我无法做到这一点。 有人可以帮帮我吗? 提前谢谢!
答案 0 :(得分:1)
您可以转置数组以将16移动到开头,然后将其重新整形为(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)