tensorflow - 如何在 Keras / Tensorflow 中将(无,)批量维度重新引入张量?
问题描述
我正在尝试使用与 Google 机器学习引擎兼容的 Keras 创建一个张量流模型。我有一个现有的训练有素的 Keras 模型,它采用向量浮点输入。我在现有模型的前面引入了一个字符串向量输入层。这将传递要预处理的字符串。我正在尝试使用 Lambda 层预处理图像数据。在预处理时,为了解码字符串 jpeg 数据,我需要从张量中删除批量维度。预处理后,我需要重新引入“无”批次维度。这就是我面临的问题。似乎没有办法重新引入“无”作为批次维度。Google ML Engine 要求批次维度在整个模型中一直是未知的。
Tensorflow 版本:1.12 Keras 版本:2.2.4 操作系统:Debian Linux(VM 实例) Python 版本:2.7
我尝试过: 1. Reshape() 同时使用 [None,299,299,3] 和 [-1,299,299,3]。两者都不能按要求工作
- tf.reshape 如上所述。不工作。
img_height=299
img_width=299
inputs = Input(shape=[1],dtype=tf.string)
inputs_inter1 = Lambda(preprocess_input, output_shape=(img_height,img_width,3))(inputs)
print(inputs_inter1.shape)
print("Combining with string vector input")
combine_out = trainedmodel(inputs_inter1)
Combinedmodel = Model(inputs,combine_out)
input_tensor = Combinedmodel.inputs[0]
output_tensor = Combinedmodel.outputs[0]
print("Inputs: "+str(input_tensor))
print("Outputs: "+str(output_tensor))
def preprocess_input(x):
import tensorflow as tf
x=tf.reshape(x,())
x = tf.image.decode_jpeg(x,channels=3)
x = tf.image.resize_images(x,(299,299))
x = tf.cast(x, tf.float32)
x = tf.math.divide(x, 255.0)
x = tf.math.subtract(x, 0.5)
x = tf.math.multiply(x, 2.0)
x = tf.expand_dims(x,0)
return x
预期结果:
输入:Tensor("input_1_1:0", shape=(?, 1), dtype=string)
输出:Tensor("model_2/model_1/dense_2/Softmax:0", shape=(?, 8), dtype=float32)
实际结果:
输入:Tensor("input_1_1:0", shape=(?, 1), dtype=string)
输出:Tensor("model_2/model_1/dense_2/Softmax:0", shape=(1, 8), dtype=float32)
解决方案
回答我自己的问题。
诀窍是创建一个具有所需尺寸的新占位符 [None,299,299,3],将预处理的张量复制到其中并从 Lambda 函数/层返回该占位符。
def preprocess_input(x):
import tensorflow as tf
x=tf.reshape(x,())
x = tf.image.decode_jpeg(x,channels=3)
x = tf.image.resize_images(x,(299,299))
x = tf.cast(x, tf.float32)
x = tf.math.divide(x, 255.0)
x = tf.math.subtract(x, 0.5)
x = tf.math.multiply(x, 2.0)
x = tf.placeholder_with_default(x,[None,299,299,3])
return x
tf.placeholder_with_default的用法可以在这里找到:https ://www.tensorflow.org/api_docs/python/tf/placeholder_with_default
ETA:最新的 Tensorflow 2.0 具有向后兼容的占位符,具有默认功能。可以短期使用。
推荐阅读
- tensorflow - Precision@K 作为 Keras 中的自定义指标
- javascript - 如何在网站上显示下拉列表的所有选项?
- python - 如何将我的数据框分成两行,其中两列具有特定值?
- paperjs - 如何停止和启动 view.onFrame
- azure - 使用 VSTS 将角色分配给 Web 应用程序时出现授权错误
- android - 如何在 android 中检测整个面部(不是侧面,甚至不是面部隐藏的任何部分),就像 ios 中的 CI 面部检测器一样
- reactjs - mount(Component).debug() 给出了 emtpy 值
- apache-camel - 这条骆驼路线会在异常情况下确认消息吗?
- javascript - 无法让动画与 AMP 和 React 一起使用
- html - Flexbox最后一个子边距在Firefox中折叠