如何在TensorFlow中重塑张量而不造成计算图断开?
解决TensorFlow前向传播中张量重塑导致计算图断开的问题
问题原因
直接使用tf.reshape属于原生TensorFlow操作,并非Keras层组件,会打破Keras层之间的连接关系,进而引发计算图断开错误。
可行的重塑方法
方法一:使用Keras内置的Reshape层
这是最规范的方式,Reshape是Keras的原生层,能完美融入计算图:
... image = tf.keras.layers.Input(INPUT_SHAPE, name='image', dtype=tf.uint8) # 替换为Keras Reshape层 image = tf.keras.layers.Reshape((1344, 768, 1))(image) image_norm = normalize(image) ...
方法二:用Lambda层包装tf.reshape
如果需要保留tf.reshape的灵活写法,可以把它封装到Lambda层中,使其成为Keras计算图的一部分:
... image = tf.keras.layers.Input(INPUT_SHAPE, name='image', dtype=tf.uint8) # 用Lambda层包装tf.reshape image = tf.keras.layers.Lambda(lambda x: tf.reshape(x, shape=(-1, 1344, 768, 1)))(image) image_norm = normalize(image) ...
内容的提问来源于stack exchange,提问作者alryosha
相关产品推荐
相关产品推荐

