如何访问张量到keras图层的单个特征图

时间:2018-12-25 14:12:14

标签: python keras neural-network conv-neural-network

我正在实现两个不同的keras层之间的自定义连接。神经网络开始如下:

from tensorflow.keras.layers import Dense, Conv2D, Flatten, AveragePooling2D
import tensorflow as tf
from keras.models import Model
from tensorflow.keras.layers import Conv2D, Input, Concatenate, Lambda, Add

inputTensor = Input(shape=( 32, 32,1))
stride = 1
c1 = Conv2D(6, kernel_size=[5,5], strides=(stride,stride), padding="valid", input_shape=(32,32,1), 
                  activation = 'tanh')(inputTensor)
s2 = AveragePooling2D(pool_size=(2, 2), strides=(2, 2))(c1)

在这里,我想将自定义连接应用于输出大小为10 * 10 * 16的卷积层c3(也就是说,需要在大小为14 * 14 * 6的s2上应用16个过滤器10 * 10 * 16)。为此,我需要使用kernal_size = 5*5filers=16stride = 1padding=valid

对于我的自定义连接,我不想一次使用s2的全部6个特征图,而是要单独使用它们。我正在使用lambda函数,如下所示:

例如,如果我想使用s2的第零个特征图并对其应用1个过滤器,我将执行以下操作:

group0_a = Lambda(lambda x: x[:,:,:,0], output_shape=lambda x: (x[0], x[1], x[2], 1))(s2)

conv_group0_a = Conv2D(1, kernel_size=[5,5], strides=(stride,stride), padding="valid", activation = 'tanh')(group0_a)

现在,我收到错误消息:

Input 0 of layer conv2d_10 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 14, 14]用于group0_a

1 个答案:

答案 0 :(得分:0)

好的,因此您可以访问s2的第零个特征图并对其应用1个过滤器,您可以按如下所示访问它:

group0_a = Lambda(lambda x: x[:,:,:,0:1], output_shape=lambda x: (x[0], x[1], x[2], 1))(s2)

conv_group0_a = Conv2D(1, kernel_size=[5,5], strides=(stride,stride), padding="valid", activation = 'tanh')(group0_a)

我唯一要做的是代替x的{​​{1}}函数作为lambda,我将其传递为x[:,:,:,0]