【问题标题】:LSTM with two inputs conversion to TFlite具有两个输入的 LSTM 转换为 TFlite
【发布时间】:2022-07-25 21:31:29
【问题描述】:

按照example,我正在尝试将我的 TF LSTM 模型转换为 TFlite 模型。问题:我有两个输入而不是一个。

import tensorflow as tf

tf.keras.backend.clear_session()
inputs = tf.keras.Input(shape=(5, 3))
inputs_2 = tf.keras.Input(shape=(4))
x = tf.keras.layers.Conv1D(filters=6, kernel_size=5, activation='elu', padding="same", kernel_regularizer=tf.keras.regularizers.l2(0.01), bias_regularizer=tf.keras.regularizers.l2(0.01))(inputs)
x = tf.keras.layers.LSTM(6)(x)
x = tf.keras.layers.Flatten()(x)
con = tf.keras.layers.Concatenate()([x, inputs_2])
con = tf.keras.layers.Dense(1, activation='sigmoid')(con)
model = tf.keras.Model([inputs, inputs_2], con)
model.compile(loss="binary_crossentropy", optimizer=tf.keras.optimizers.Adam(), metrics=[tf.keras.metrics.PrecisionAtRecall(0.8), tf.keras.metrics.AUC()])

run_model = tf.function(lambda x, y: model([x, y]))

concrete_func = run_model.get_concrete_function(
    [tf.TensorSpec([1, 5, 3], model.inputs[0].dtype), 
     tf.TensorSpec([1, 4], model.inputs[0].dtype)]
)

converter = tf.lite.TFLiteConverter.from_saved_model(MODEL_DIR)
tflite_model = converter.convert()

显然,我必须提到一个事实,即我有两个输入并且我做错了。正确的面对方式是什么?

【问题讨论】:

    标签: tensorflow lstm tensorflow-lite converters


    【解决方案1】:

    曾几何时,存在一个有两个输入的函数:

    lambda x, y: model([x, y])
    

    有一天,它被转换为一个 tf 函数

    tf.function(lambda x, y: model([x, y]))
    

    但是有人仍然想将它与 python 实现一起使用,使用get_concrete_function...但是get_concrete_function 的函数是初始 lambda 函数,它需要 2 个输入...

    但是,您使用单个输入(向量)调用 lambda 函数:

    run_model.get_concrete_function(
        [tf.TensorSpec([1, 5, 3], model.inputs[0].dtype), tf.TensorSpec([1, 4], model.inputs[0].dtype)]
    )
    

    您可能打算执行以下操作?

    run_model.get_concrete_function(
        tf.TensorSpec([1, 5, 3], model.inputs[0].dtype), 
        tf.TensorSpec([1, 4], model.inputs[0].dtype)
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2022-11-01
      相关资源
      最近更新 更多