将TensorFlow决策树的RandomForest模型转TFlite时遇错求助
尝试将tensor_flow_decision_tree库中的RandomForest模型转换为TFlite模型时,出现如下ConverterError错误:
ConverterError: :0: error:
loc(fused["SimpleMLCreateModelResource:",
"SimpleMLCreateModelResource"]): 'tf.SimpleMLCreateModelResource' op
is neither a custom op nor a flex op :0: note:
loc(fused["SimpleMLCreateModelResource:",
"SimpleMLCreateModelResource"]): Error code: ERROR_NEEDS_CUSTOM_OPS
/usr/local/lib/python3.8/dist-packages/tensorflow/python/framework/func_graph.py:749:0:
error: 'tf.SimpleMLInferenceOpWithHandle' op is neither a custom op
nor a flex op :0: note: loc(fused["StatefulPartitionedCall:",
"StatefulPartitionedCall"]): called from
/usr/local/lib/python3.8/dist-packages/tensorflow/python/framework/func_graph.py:749:0:
note: Error code: ERROR_NEEDS_CUSTOM_OPS :0: error: failed
while converting: 'main': Some ops in the model are custom ops, See
instructions to implement custom ops:
Custom ops:
SimpleMLCreateModelResource, SimpleMLInferenceOpWithHandle Details:
tf.SimpleMLCreateModelResource() -> (tensor<!tf_type.resource>) :
{container = "", device = "", shared_name =
"simple_ml_model_243450c3-97d3-43ae-bd29-ea9628cd031d"}
tf.SimpleMLInferenceOpWithHandle(tensor<?x12xf32>, tensor<0x0xf32>,
tensor<0x0xi32>, tensor<0xi32>, tensor<1xi64>, tensor<1xi64>,
tensor<!tf_type.resource>) -> (tensor<?x2xf32>,
tensor<2x!tf_type.string>) : {dense_output_dim = 2 : i64, device = ""}
已查阅官方自定义算子指南但未找到有效解决方法,求处理方案。
使用TensorFlow Decision Forests(TF-DF)官方提供的专用TFLite转换API,不要用标准的
tf.lite.TFLiteConverter。TF-DF的模型依赖专属状态算子,标准转换器无法处理,专用API会自动处理这些算子的序列化:import tensorflow_decision_forests as tfdf import tensorflow as tf # 加载训练好的TF-DF随机森林模型 model = tfdf.keras.load_model("your_model_path") # 获取TF-DF专属转换器 converter = tfdf.lite.convert.get_converter(model) # 执行转换 tflite_model = converter.convert() # 保存转换后的模型 with open("converted_model.tflite", "wb") as f: f.write(tflite_model)确保TF-DF与TensorFlow版本严格兼容。TF-DF对TensorFlow版本有明确依赖,版本不匹配会导致算子识别失败。可以通过以下命令查看当前版本:
pip show tensorflow_decision_forests pip show tensorflow根据TF-DF官方说明调整到兼容版本。
尝试导出无状态TFLite模型。TF-DF模型默认是有状态的,依赖资源算子,可通过转换参数强制转为无状态模式,避开资源算子问题:
converter = tfdf.lite.convert.get_converter(model, use_training_model=False) tflite_model = converter.convert()注意:无状态模式会失去模型在线更新能力,仅适合推理场景。
固定模型输入形状。如果模型输入是动态维度,可能导致转换失败,可在转换前固定输入形状:
# 假设输入特征维度为12 model.build(input_shape=[None, 12])
内容的提问来源于stack exchange,提问作者WinterSolstice

