将 tf 模型转换为 TFlite 模型时出错

时间:2021-01-31 17:39:44

标签: python tensorflow keras arduino tensorflow-lite

我目前正在构建一个模型,将其用于我的 nano 33 BLE 感应板,通过测量湿度、压力、温度来预测天气,我有 5 个类。 我使用了一个 kaggle 数据集对其进行训练。

    df_labels = to_categorical(df.pop('Summary'))
    df_features = np.array(df)
    
    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(df_features, df_labels, test_size=0.15)
    
    normalize = preprocessing.Normalization()
    normalize.adapt(X_train)
    
    
    activ_func = 'gelu'
    model = tf.keras.Sequential([
                 normalize,
                 tf.keras.layers.Dense(units=6, input_shape=(3,)),
                 tf.keras.layers.Dense(units=100,activation=activ_func),
                 tf.keras.layers.Dense(units=100,activation=activ_func),
                 tf.keras.layers.Dense(units=100,activation=activ_func),
                 tf.keras.layers.Dense(units=100,activation=activ_func),
                 tf.keras.layers.Dense(units=5, activation='softmax')
    ])
    
    model.compile(optimizer='adam',#tf.keras.optimizers.Adagrad(lr=0.001),
                 loss='categorical_crossentropy',metrics=['acc'])
    model.summary()
    model.fit(x=X_train,y=y_train,verbose=1,epochs=15,batch_size=32, use_multiprocessing=True)

然后训练模型,我想在运行命令 convert 时将其转换为 tflite 模型我收到以下消息:

    # Convert the model to the TensorFlow Lite format without quantization
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    tflite_model = converter.convert()
    
    # Save the model to disk
    open("gesture_model.tflite", "wb").write(tflite_model)
      
    import os
    basic_model_size = os.path.getsize("gesture_model.tflite")
    print("Model is %d bytes" % basic_model_size)




    <unknown>:0: error: failed while converting: 'main': Ops that can be supported by the flex runtime (enabled via setting the -emit-select-tf-ops flag):
        tf.Erf {device = ""}

为了您的信息,我使用 google colab 来设计模型。

如果有人对此问题有任何想法或解决方案,我会很高兴听到它!

2 个答案:

答案 0 :(得分:0)

当您尚未设置转换器支持的操作时,通常会发生这种情况。

这是一个例子:

import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)

converter.target_spec.supported_ops = [
  tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.
  tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.
]

tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

这个支持的操作列表在不断变化,所以如果错误仍然出现,您也可以尝试设置实验转换器功能如下:

converter.experimental_new_converter = True

答案 1 :(得分:-1)

我解决了这个问题!这是 TFlite 尚不支持的激活函数 'gelu'。我将其更改为“relu”,没有更多问题。