【问题标题】:MobileBert from TensorFlow Lite in PythonPython 中来自 TensorFlow Lite 的 MobileBert
【发布时间】:2020-01-15 21:04:35
【问题描述】:

我从 TensorFlow 下载了 MobileBert 模型 - 基于 TensorFlow Lite 的移动设备问答模型:

https://www.tensorflow.org/lite/models/bert_qa/overview

仅针对 Android 提供的使用方法示例。任何人都可以建议如何在 Python 中使用这个模型(用于测试目的)。我遵循了有关如何使用 TensorFlow Lite API 的建议,但我需要弄清楚如何修改它以用于 MobileBert:

import numpy as np
import tensorflow as tf

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="mobilebert_float_20191023.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)

input_data = np.array(np.random.random_sample(input_shape), dtype=np.int32)

interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)

【问题讨论】:

    标签: python tensorflow tensorflow-lite


    【解决方案1】:

    请看看这个项目:https://github.com/samsgates/MobileBERT 它基本上是为运行你提到的谷歌模型而设计的。我设法使用 TF 1.14 以及安装的其他依赖项运行它(sentencepiecebert-for-tf2,两者都可以从 PiP 获得)。我唯一需要调整的是删除输入/输出张量上的 tf.dtypes.cast() 包装器。例如。对于我更改的输入

    input_ids = tf.dtypes.cast(self.get_ids(stokens),tf.int32)
    

    input_ids = self.get_ids(stokens).astype('int32')
    

    对于我改变的输出

    end = tf.argmax(end_logits,output_type=tf.dtypes.int32).numpy()[0]
    

    简单

    end = np.argmax(end_logits)
    

    这对我有用。希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多