【问题标题】:TFLiteConverter representative_dataset from keras.preprocessing.image_dataset_from_directory datasetTFLiteConverter 来自 keras.preprocessing.image_dataset_from_directory 数据集的代表数据集
【发布时间】:2021-04-30 06:52:31
【问题描述】:

我有一个数据集通过

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=validation_split,
  subset="training",
  seed=seed,
  image_size=(img_height, img_width),
  batch_size=batch_size)

(基于来自 https://www.tensorflow.org/tutorials/load_data/images 的代码,对配置进行了非常小的更改)

我正在将最终模型转换为 TFLite 模型,该模型正在运行,但我认为该模型对于终端设备来说太大了,所以我试图通过提供 representative_dataset (如 @987654322)来运行训练后量化@)

但是我不知道如何将 image_dataset_from_directory 生成的数据集转换为 representative_dataset 期望的格式

提供的例子有

def representative_dataset():
  for data in tf.data.Dataset.from_tensor_slices((images)).batch(1).take(100):
    yield [data.astype(tf.float32)]

我尝试过类似的东西

def representative_dataset():
  for data in train_ds.batch(1).take(100):
    yield [data.astype(tf.float32)]

但事实并非如此

【问题讨论】:

  • 运行代码时是否打印了一些错误信息?
  • 很多像'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'astype' 这样的东西表明我没有以正确的方式做representative_dataset

标签: tensorflow keras tensorflow-datasets tensorflow-lite


【解决方案1】:

看起来像

def representative_dataset():
  for image_batch, labels_batch in train_ds:
    yield [image_batch]

正是我要找的,image_batch 已经是tf.float32

【讨论】:

    【解决方案2】:

    我无法让tf.keras.preprocessing.image_dataset_from_directory 工作,但我对tf.keras.preprocessing.ImageDataGenerator 有一些运气。

    就我而言,图像位于“images/all”目录中。我必须确保从该目录中删除所有非图像文件(例如 XML 注释)。

    from tensorflow.keras.preprocessing.image import ImageDataGenerator
    from tensorflow.keras.applications.mobilenet import preprocess_input
    
    def representative_dataset():
      test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
      test_generator = test_datagen.flow_from_directory(
          './images', 
          target_size=(300, 300), 
          batch_size=1,
          classes=['all'],
          class_mode='categorical')
      for ind in range(len(test_generator.filenames)):
        img_with_label = test_generator.next()
        yield [np.array(img_with_label[0], dtype=np.float32, ndmin=2)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      相关资源
      最近更新 更多