还是上面的网络,我们输出各个层的权值看看
len(model.layers[0].weights)=2,
weights[0],
<tf.Variable 'conv2d/kernel:0' shape=(3, 3, 1, 32) dtype=float32
weights[1]
<tf.Variable 'conv2d/bias:0' shape=(32,) dtype=float32,
要输出第一个卷积的值:
model.layers[0].weights[0][:,:,:,0]
model.layers[0].weights[0][:,:,:,0].shape=TensorShape([3, 3, 1])
输出第一个层的32个卷积图
我们来计算一下这个网络的参数
参数个数和输入图像的大小直接关系。和卷积数,channel数有关。
input shape=28*28*1
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 26, 26, 32) 320 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 13, 13, 32) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 11, 11, 64) 18496 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 5, 5, 64) 0 _________________________________________________________________ flatten (Flatten) (None, 1600) 0 _________________________________________________________________ dropout (Dropout) (None, 1600) 0 _________________________________________________________________ dense (Dense) (None, 10) 16010 ================================================================= Total params: 34,826 Trainable params: 34,826 Non-trainable params: 0
320=32*(3*3+1)
18496=64*【32*(3*3)+1】,32个核对应的是32个通道,就像rgb图像的3个通道一样。
从参数计算可以更清楚的看到网络结构。28*28*1的图像经过第一次卷积后,图像变成了32幅,26*26*32,对应的是经过32个卷积过滤后的图像。然后对这32个图像的每个图像用一个3*3的卷积核过滤,relu后输出,共用一个b。
有没有可能还是在原始图上做卷积?构建一个扁平化的网络结构?生产更加自定义结构的网络能做吗?留待后面再看吧。
经过一次卷积后的32个图像,可以画出来看看
feature_extractor = keras.Model(
inputs=model.inputs,
outputs=[layer.output for layer in model.layers],
)
d=x_test[0:1]#这样才能获取到(none,28, 28, 1)的结构
l=y_test[0] #7
plt.imshow(d[0],plt.cm.gray)
feature_extractor.input_shape #(none,28, 28, 1)
d.shape #(1,28, 28, 1)
features = feature_extractor(d)
plt.figure(figsize=(10,10))
for i in range(32):
x=features[0][0,:,:,0] #features[0]是第0层的输出,详见上面关于feature_extractor的定义,
plt.subplot(6,6,i+1)
plt.imshow(x,cmap=plt.cm.gray)
plt.show()
7经过第一层卷积后得到的图
经过第二层卷积的图,features[1]
到这里,卷积的特征提取就比较明显了。