在Keras中分割CNN层

时间:2019-04-26 01:13:28

标签: python-3.x tensorflow keras

我想摆脱CNN中的某些频道。它由两个模型组成,这两个模型结合在一起可以创建一个简单的模型。

它创建正确的输出,但在中间层,但稍后仍会给出错误。

def highAccuracyModelTillConv2(input_img): 
  conv1_1 = (Conv2D(32, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay), input_shape=x_train.shape[1:], activation='elu', name = 'HighAccuracyConv1'))(input_img)
  conv1_2 = BatchNormalization()(conv1_1)
  conv2_1 = (Conv2D(32, (3,3), padding='same', activation= 'elu', name = 'HighAccuracyConv2',kernel_regularizer=regularizers.l2(weight_decay)))(conv1_2)
  conv2_2 = BatchNormalization()(conv2_1)  
  return conv2_1
import tensorflow as tf
def cifar10ClassifierTransfer(input_img, conv2_high):

  # Add additional inputs to 

  conv1_1 = (Conv2D(32, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay), input_shape=x_train.shape[1:], activation='elu'))(input_img)
  conv1_2 = BatchNormalization()(conv1_1)
  conv2_1 = (Conv2D(32, (3,3), padding='same', activation= 'elu',kernel_regularizer=regularizers.l2(weight_decay)))(conv1_2)
  channels = [1,2,4]
  branch_outputs = []
  orig_channel = conv2_1
  branch_outputs.append(orig_channel)
  for i in channels:
      # Slicing the ith channel:
      out = Lambda(lambda x: x[:,:,:, i])(conv2_high)
      # Setting up your per-channel layers (replace with actual sub-models):
      layer_out =  keras.backend.expand_dims(out, axis = 3)
      branch_outputs.append(layer_out)
  out = Concatenate()(branch_outputs)
  print(out.shape)

  out = Dense(num_classes, activation='softmax')(out)

  return out  

high_acc_output = highAccuracyModelTillConv2(input_img)
modelFilt = Model(input_img, 
              cifar10ClassifierTransfer(input_img,
              high_acc_output))

这是我创建模型时得到的错误,尽管中间输出的正确值正确。任何帮助将不胜感激。

(?, 32, 32, 35)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-257-685f377c5c1a> in <module>()
      3 modelFilt = Model(input_img, 
      4               cifar10ClassifierTransfer(input_img,
----> 5               high_acc_output))
      6 # #data augmentation
      7 # datagen = ImageDataGenerator(

6 frames
/usr/local/lib/python3.6/dist-packages/keras/engine/network.py in build_map(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1323             ValueError: if a cycle is detected.
   1324         """
-> 1325         node = layer._inbound_nodes[node_index]
   1326 
   1327         # Prevent cycles.

AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

1 个答案:

答案 0 :(得分:1)

该错误通常意味着我们传入了Keras层以外的某种对象。您的大多数代码看上去都不错,但是这一行代码需要包装在Lambda层中:

layer_out =  keras.backend.expand_dims(out, axis = 3)

将其更改为:

layer_out = Lambda(lambda x: keras.backend.expand_dims(x, axis = 3))(out)

通常,任何时候我们下降到Tensorflow后端时,我们都必须使用lambda层,因为后端在张量而不是Keras层上运行。