gpt4 book ai didi

keras - 如何在 Keras 中将标量添加到张量或从标量创建张量?

转载 作者:行者123 更新时间:2023-12-05 07:31:57 26 4
gpt4 key购买 nike

我需要以某种方式运行这样的东西:

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,我将无法快速重写它们。

有什么方法可以从 float 创建 Keras 张量吗?
也许这个问题有不同的解决方案?

更新:后端是 TensorFlow

最佳答案

嗯,根据上面的评论,我测试了 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)。

关于keras - 如何在 Keras 中将标量添加到张量或从标量创建张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com