如何从 tflite 模型中获取权重



我有一个简单的网络,我已经使用tensorflow完成了修剪和量化。我专门按照本教程在我的网络上应用:https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras#convert_to_tensorflow_lite

最后,我得到了 tflite 文件。我想从这个文件中提取权重。如何从这个量化模型中获取权重?我知道从"h5"文件而不是从"tflite"文件中获取权重的方法。或者有没有其他方法可以在模型上执行量化后保存"h5"文件?

创建一个 tflite 解释器并(可选(执行推理。 tflite_interpreter.get_tensor_details(( 将给出具有权重、偏差、其尺度zero_points的字典列表。等。

'''
Create interpreter, allocate tensors
'''
tflite_interpreter = tf.lite.Interpreter(model_path='model_file.tflite')
tflite_interpreter.allocate_tensors()
'''
Check input/output details
'''
input_details = tflite_interpreter.get_input_details()
output_details = tflite_interpreter.get_output_details()
print("== Input details ==")
print("name:", input_details[0]['name'])
print("shape:", input_details[0]['shape'])
print("type:", input_details[0]['dtype'])
print("n== Output details ==")
print("name:", output_details[0]['name'])
print("shape:", output_details[0]['shape'])
print("type:", output_details[0]['dtype'])
'''
Run prediction (optional), input_array has input's shape and dtype
'''
tflite_interpreter.set_tensor(input_details[0]['index'], input_array)
tflite_interpreter.invoke()
output_array = tflite_interpreter.get_tensor(output_details[0]['index'])
'''
This gives a list of dictionaries. 
'''
tensor_details = tflite_interpreter.get_tensor_details()
for dict in tensor_details:
    i = dict['index']
    tensor_name = dict['name']
    scales = dict['quantization_parameters']['scales']
    zero_points = dict['quantization_parameters']['zero_points']
    tensor = tflite_interpreter.tensor(i)()
    print(i, type, name, scales.shape, zero_points.shape, tensor.shape)
    '''
    See note below
    '''
  • Conv2D 层将有三个与之关联的字典:内核、偏差conv_output,每个字典都有其尺度、zero_points和张量。
  • 张量 - 是具有核权重或偏差的 NP 数组。对于conv_output或激活,这并不意味着什么(不是中间输出(
  • 对于卷核字典,张量是形状的(cout,k,k,cin(

我已经通过使用Netron解决了这个问题。在 Netron 中,权重可以保存为 numpy 数组。https://github.com/lutzroeder/netron

最新更新