gpt4 book ai didi

python - TFLIte 无法设置张量 : Dimension mismatch on model conversion

转载 作者:行者123 更新时间:2023-12-05 02:58:36 24 4
gpt4 key购买 nike

我有一个构造如下的keras模型

module_url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
backbone = hub.KerasLayer(module_url)
backbone.build([None, 224, 224, 3])
model = tf.keras.Sequential([backbone, tf.keras.layers.Dense(len(classes), activation='softmax')])
model.build([None, 224, 224, 3])
model.compile('adam', loss='sparse_categorical_crossentropy')

然后我按如下方式从 TF hub 加载 Caltech101 数据集

samples, info = tfds.load("caltech101", with_info=True)
train_samples, test_samples = samples['train'], samples['test']
def normalize(row):
image, label = row['image'], row['label']
image = tf.dtypes.cast(image, tf.float32)
image = tf.image.resize(image, (224, 224))
image = image / 255.0
return image, label
train_data = train_samples.repeat().shuffle(1024).map(normalize).batch(32).prefetch(1)
test_data = test_samples.map(normalize).batch(1)

现在我已准备好按如下方式训练和保存我的模型:

model.fit_generator(train_data, epochs=1, steps_per_epoch=100)
saved_model_dir = './output'
tf.saved_model.save(model, saved_model_dir)

此时模型可用,我可以评估形状输入 (224, 224, 3)。我尝试按如下方式转换此模型:

def generator2():
data = train_samples
for _ in range(num_calibration_steps):
images = []
for image, _ in data.map(normalize).take(1):
images.append(image)
yield images

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.optimizations = [tf.lite.Optimize.DEFAULT]

converter.representative_dataset = tf.lite.RepresentativeDataset(generator2)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
tflite_default_quant_model = converter.convert()

转换触发如下错误

/usr/local/lib/python3.6/dist-packages/tensorflow_core/lite/python/optimize/tensorflow_lite_wrap_calibration_wrapper.py in FeedTensor(self, input_value)
110
111 def FeedTensor(self, input_value):
--> 112 return _tensorflow_lite_wrap_calibration_wrapper.CalibrationWrapper_FeedTensor(self, input_value)
113
114 def QuantizeModel(self, input_py_type, output_py_type, allow_float):

ValueError: Cannot set tensor: Dimension mismatch

现在有一个类似的question但在这种情况下,他们正在加载一个已经转换的模型,这与我尝试转换模型时出现问题的情况不同。

转换器对象是使用 SWIG 从 C++ 代码自动生成的类这使得检查变得困难。如何找到转换器对象期望的确切维度?

最佳答案

使用时遇到同样的问题

def representative_dataset_gen():
for _ in range(num_calibration_steps):
# Get sample input data as a numpy array in a method of your choosing.
yield [input]

来自 https://www.tensorflow.org/lite/performance/post_training_quantization .似乎 converter.representative_dataset 需要一个列表,其中包含一个形状为 (1, input_shape) 的示例。也就是说,沿线使用一些东西

def representative_dataset_gen():
for i in range(num_calibration_steps):
# Get sample input data as a numpy array in a method of your choosing.
yield [input[i:i+1]]

如果输入的形状为 (num_samples, input_shape),问题就解决了。在您的情况下,当使用 tf 数据集时,一个工作示例是

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

samples, info = tfds.load("caltech101", with_info=True)
train_samples, test_samples = samples['train'], samples['test']

def normalize(row):
image, label = row['image'], row['label']
image = tf.dtypes.cast(image, tf.float32)
image = tf.image.resize(image, (224, 224))
image = image / 255.0
return image, label

train_data = train_samples.repeat().shuffle(1024).map(normalize).batch(32).prefetch(1)
test_data = test_samples.map(normalize).batch(1)

module_url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
backbone = hub.KerasLayer(module_url)
backbone.build([None, 224, 224, 3])
model = tf.keras.Sequential([backbone, tf.keras.layers.Dense(102, activation='softmax')])
model.build([None, 224, 224, 3])
model.compile('adam', loss='sparse_categorical_crossentropy')

model.fit_generator(train_data, epochs=1, steps_per_epoch=100)
saved_model_dir = 'output/'
tf.saved_model.save(model, saved_model_dir)

num_calibration_steps = 50

def generator():
single_batches = train_samples.repeat(count=1).map(normalize).batch(1)
i=0
while(i<num_calibration_steps):
for batch in single_batches:
i+=1
yield [batch[0]]

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.optimizations = [tf.lite.Optimize.DEFAULT]

converter.representative_dataset = tf.lite.RepresentativeDataset(generator)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
tflite_default_quant_model = converter.convert()

关于python - TFLIte 无法设置张量 : Dimension mismatch on model conversion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58775848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com