【问题标题】:How add scalar to tensor in Keras or create tensor from scalar?如何在 Keras 中将标量添加到张量或从标量创建张量?
【发布时间】:2019-01-03 08:15:02
【问题描述】:

我需要以某种方式运行类似的东西:

x = Input(shape=(img_height, img_width, img_channels))
x1 = Add()([x, 127.5])
x2 = Multiply()(x1, -127.5])

但是,出现错误:
ValueError: Layer add_1 was called with an input that isn't a symbolic tensor. Received type: <class 'float'>. Full input: [<tf.Tensor 'input_1:0' shape=(?, 400, 300, 3) dtype=float32>, 0.00784313725490196]. All inputs to the layer should be tensors.

我无法使用Lambda() 层,因为我需要将最终模型转换为 CoreML,并且无法快速重写它们。

有没有办法从浮点数创建 Keras 张量?
也许这个问题有不同的解决方案?

UPD:后端是 TensorFlow

【问题讨论】:

  • 如果你不能使用 Lambda 层(我不明白为什么),恐怕你需要为常量使用第二个输入(或者创建一个自定义层只是为了加法)
  • 同意...使用 Keras 时,您无法逃避以下其中一项: 1 - 使用 lambda; 2 - 创建自定义图层; 3 - 使用 tf 张量作为额外的 Input
  • 请注意,您可以将这些规范化操作传递给 coremltools,因此您实际上不必将它们放入 Keras 模型中。另见machinethink.net/blog/help-core-ml-gives-wrong-output

标签: keras keras-layer coreml coremltools


【解决方案1】:

嗯,基于上面的 cmets,我测试了 2 种方法。自定义层不是一个选项,因为我需要用 swift 编写它才能转换为 CoreML 模型(而且我不知道 swift)。

其他输入
没有办法预先定义输入值,据我所知,所以我需要在输入上传递额外的参数,这不是很方便。
考虑下面的示例代码:

input1 = keras.layers.Input(shape=(1,), tensor=t_b, name='11')
input2 = keras.layers.Input(shape=(1,))
input3 = keras.layers.Input(shape=(1,), tensor=t_a, name='22')

# x1 = keras.layers.Dense(4, activation='relu')(input1)
# x2 = keras.layers.Dense(4, activation='relu')(input2)

added = keras.layers.Add()([input1, input3])  # equivalent to added = keras.layers.add([x1, x2])
added2 = keras.layers.Add()([input2, added])  # equivalent to added = keras.layers.add([x1, x2])

# out = keras.layers.Dense(4)(added2)

model = keras.models.Model(inputs=[input1, input2, input3], outputs=added2)

如果您将在干净的环境中加载该模型,那么您实际上需要将 3 个值传递给它:my_model.predict([np.array([1]), np.array([1]), np.array([1])]) 否则会出现错误。

CoreML 工具
通过在导入器函数中使用*_biasimage_scale 参数,我能够达到理想的效果。下面的例子。

coreml_model = coremltools.converters.keras.convert(
    model_path,
    input_names='image',
    image_input_names='image',
    output_names=['cla','bo'],
    image_scale=1/127.5,  # divide matrix by value
    # substract 1 from every value in matrix
    red_bias=-1.0,  # substract value from channel
    blue_bias=-1.0,
    green_bias=-1.0
)

如果有人知道如何在 Keras 中预定义不应该通过输入层加载的常量,请写下如何 (tf.constant() solution is not working)。

【讨论】:

  • 你的意思是常数张量还是标量张量?我想要可训练的标量。
  • @mathtick 我不记得了,太久以前了)
猜你喜欢
  • 2018-08-02
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多