繁体   English   中英

TFLite 转换器:为 keras 模型实现的 RandomStandardNormal,但不适用于纯 TensorFlow 模型

[英]TFLite Converter: RandomStandardNormal implemented for keras model, but not for pure TensorFlow model

任务

我有两个模型应该是等效的。 第一个是用 keras 构建的,第二个是用 tensorflow 构建的。 两个变分自tf.random.normal在其模型中使用tf.random.normal方法。 此外,它们会产生类似的结果。 一切都使用每晚构建(1.15)进行测试。

当我尝试将它们转换为具有训练后量化的 tensorflow lite 模型时,混乱就出现了。 我对两种模型使用相同的命令:

converter = tf.compat.v1.lite.TFLiteConverter... # from respective save file
converter.representative_dataset = representative_dataset_gen
converter.optimizations = [tf.lite.Optimize.DEFAULT]

tflite_model = converter.convert()
open('vae.tflite', 'wb').write(tflite_model)

错误

对于 keras 模型,一切顺利,我最终得到了一个有效的 tflite 模型。 但是,如果我尝试使用 tensorflow 版本执行此操作,则会遇到一个错误,指出未实现RandomStandardNormal

标准 TensorFlow Lite 运行时不支持模型中的某些运算符。 如果这些是本机 TensorFlow 运算符,您可以通过传递 --enable_select_tf_ops 或在调用 tf.lite.TFLiteConverter() 时设置 target_ops=TFLITE_BUILTINS,SELECT_TF_OPS 来使用扩展运行时。 否则,如果您有自定义实现,您可以使用 --allow_custom_ops 或通过在调用 tf.lite.TFLiteConverter() 时设置 allow_custom_ops=True 来禁用此错误。 以下是您正在使用的内置运算符列表:ADD、EXP、FULLY_CONNECTED、LEAKY_RELU、LOG、MUL。 以下是您需要自定义实现的运算符列表:RandomStandardNormal。

这对我来说没有意义,因为显然这已经在使用 keras。 keras 知道我必须明确告诉我的 tensorflow 模型吗?

楷模

张量流

fc_layer = tf.compat.v1.layers.dense

# inputs have shape (90,)
x = tf.identity(inputs, name='x')

# encoder
outputs = fc_layer(x, 40, activation=leaky_relu)

self.z_mu = fc_layer(outputs, 10, activation=None)
self.z_sigma = fc_layer(outputs, 10, activation=softplus)

# latent space
eps = tf.random.normal(shape=tf.shape((10,)), mean=0, stddev=1, dtype=tf.float32)
outputs = self.z_mu + eps * self.z_sigma

# decoder
outputs = fc_layer(outputs, 40, activation=leaky_relu)

# prediction
x_decoded = fc_layer(outputs, 90, activation=None)

凯拉斯

x = keras.layers.Input(shape=(90,))

h = keras.layers.Dense(40, activation=leakyrelu)(x)

z_mu = keras.layers.Dense(10)(h)
z_sigma = keras.layers.Dense(10, activation=softplus)(h)

eps = tf.random.normal(shape=tf.shape((10,)), mean=0, stddev=1, dtype=tf.float32)
z = z_mu + eps * z_sigma

h_decoded = keras.layers.Dense(40, activation=leakyrelu)(z)
x_decoded = keras.layers.Dense(90)(h_decoded)

train_model = keras.models.Model(x, x_decoded)

!pip 安装张量流==1.15

import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_keras_model_file('model.h5') 
converter.allow_custom_ops = True
tfmodel = converter.convert() 
open ("model.tflite" , "wb") .write(tfmodel)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM