激活层从张量隐藏2个属性

时间:2019-05-27 16:00:20

标签: python tensorflow keras

  

TensorFlow版本:tf 1.13.1
  Keras版本:2.2.4
  Python版本:3.7

调试之后,我看到在模型的各个部分添加了激活层之后,该层删除了两个属性_keras_history和_keras_shape。

当前,该模型尚未编译,因为我的体系结构在计算logit之后最后应用了激活层。

代码:

x = keras.activations.relu(x)
ff_layer2 = keras.layers.DepthwiseConv2D(128, strides=(1, 1), depth_multiplier=1, padding='same')(x)
classifier = keras.activations.softmax(ff_layer2)

x = keras.activations.relu(x)
ff_layer2 = keras.layers.DepthwiseConv2D(128, strides=(1, 1), depth_multiplier=1, padding='same')(x)
classifier = keras.activations.softmax(ff_layer2)

错误:

File "/home/perennial_qube/.conda/envs/fast-scnn/lib/python3.7/site-packages/keras/engine/network.py", line 188, in _init_graph_network
    'Found: ' + str(x))
ValueError: Output tensors to a Model must be the output of a Keras `Layer` (thus holding past layer metadata). Found: Tensor("truediv:0", shape=(?, 2048, 1024, 128), dtype=float32)

1 个答案:

答案 0 :(得分:0)

keras.activations.*中的功能是激活功能,而不是Keras层。 Keras中的模型架构仅应分层构建。因此,您需要使用他们的equivalent activation layers

from keras.layers import Softmax, ReLU

x = ReLU()(x)
# ...
classifier = Softmax()(ff_layer2)

或者,您可以使用图层的activation参数并直接传递名称或激活函数。例如:

... = DepthwiseConv2D(..., activation='softmax')
# or:
... = DepthwiseConv2D(..., activation=keras.activations.softmax)

作为另一种选择,您可以使用Activation层并传递激活函数的名称:

from keras.layers import Activation

# ...
classifier = Activation('softmax')(ff_layer2)

与其他两个解决方案相比,第一个解决方案具有以下优点:您可以通过提供自定义参数轻松地修改激活函数的行为。例如,默认情况下,softmax激活是在最后一个轴上计算的,但是如果需要,您可以如下进行更改:

from keras.layers import Softmax

classifier = Softmax(axis=my_desired_axis)(ff_layer2)