带Tensorflow后端的Keras的K.function方法是否可以与网络层一起使用? [英] Does K.function method of Keras with Tensorflow backend work with network layers?
问题描述
我最近开始使用Keras构建神经网络.我建立了一个简单的CNN对MNIST数据集进行分类.在学习模型之前,我使用了K.set_image_dim_ordering('th')
来绘制卷积层权重.现在,我正在尝试使用K.function
方法可视化卷积层输出,但是我一直遇到错误.
I recently have started using Keras to build neural networks. I built a simple CNN to classify MNIST dataset. Before learning the model I used K.set_image_dim_ordering('th')
in order to plot a convolutional layer weights. Right now I am trying to visualize convolutional layer output with K.function
method, but I keep getting error.
这是我现在想要做的:
input_image = X_train[2:3,:,:,:]
output_layer = model.layers[1].output
input_layer = model.layers[0].input
output_fn = K.function(input_layer, output_layer)
output_image = output_fn.predict(input_image)
print(output_image.shape)
output_image = np.rollaxis(np.rollaxis(output_image, 3, 1), 3, 1)
print(output_image.shape)
fig = plt.figure()
for i in range(32):
ax = fig.add_subplot(4,8,i+1)
im = ax.imshow(output_image[0,:,:,i], cmap="Greys")
plt.xticks(np.array([]))
plt.yticks(np.array([]))
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([1, 0.1, 0.05 ,0.8])
fig.colorbar(im, cax = cbar_ax)
plt.tight_layout()
plt.show()
这就是我得到的:
File "/home/kinshiryuu/anaconda3/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 1621, in function
return Function(inputs, outputs, updates=updates)
File "/home/kinshiryuu/anaconda3/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 1569, in __init__
raise TypeError('`inputs` to a TensorFlow backend function '
TypeError: `inputs` to a TensorFlow backend function should be a list or tuple.
推荐答案
您应进行以下更改:
output_fn = K.function([input_layer], [output_layer])
output_image = output_fn([input_image])
K.function
将输入和输出张量作为列表,以便您可以创建从多个输入到多个输出的函数.在您的情况下,从一个输入到一个输出..但是您仍然需要将它们作为列表传递.
K.function
takes the input and output tensors as list so that you can create a function from many input to many output. In your case one input to one output.. but you need to pass them as a list none the less.
下一步K.function
返回张量函数,而不是可在其中使用predict()
的模型对象.正确的使用方法只是作为函数调用
Next K.function
returns a tensor function and not a model object where you can use predict()
. The correct way of using is just to call as a function
这篇关于带Tensorflow后端的Keras的K.function方法是否可以与网络层一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!