tensorflow2.0在使用keras的Average等数学计算类报错解决方法

今天在构建模型时候,为了方便直接使用了tf2的内置函数

tf.keras.layers.Average
tf.keras.layers.Add

结果就是我在用@tf.function进行包裹的时候报错:

/Volumes/data_save/code_space/nlp/baidu/model/decoder.py:72 call  *
        object_feature = self.add([encoder_hidden_state,tf.expand_dims(vv_sub,1),tf.expand_dims(vv_rel,1)])
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py:748 __call__
        self._maybe_build(inputs)
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py:2116 _maybe_build
        self.build(input_shapes)
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/utils/tf_utils.py:305 wrapper
        input_shape = convert_shapes(input_shape, to_tuples=True)
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/utils/tf_utils.py:231 convert_shapes
        input_shape)
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/utils/tf_utils.py:179 map_structure_with_atomic
        map_structure_with_atomic(is_atomic_fn, map_fn, ele) for ele in values
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/utils/tf_utils.py:179 
        map_structure_with_atomic(is_atomic_fn, map_fn, ele) for ele in values
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/utils/tf_utils.py:168 map_structure_with_atomic
        return map_fn(nested)
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/utils/tf_utils.py:227 _convert_shape
        input_shape = tuple(input_shape.as_list())
    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_shape.py:1166 as_list
        raise ValueError("as_list() is not defined on an unknown TensorShape.")
    ValueError: as_list() is not defined on an unknown TensorShape.

本来想图方便,直接这样就少去了增加Lambda操作,少写点代码。后来发现还是不行滴啊。
针对报错信息。我们发现None的tensor是无法计算as_list()的。但是这个内置函数要计算。所以还是通过以下方式进行相加和平均:

 self.average = Lambda(lambda x: tf.math.add_n(x)/2.0)
 self.add = Lambda(lambda x: tf.math.add(x[0],x[1]))

这样修改后包裹上@tf.function就不会再报错

你可能感兴趣的:(Python机器学习,python,tensorflow,lambda,神经网络)