如何更改 tf.data.Dataset 中数据的 dtype?

Yaf*_*faa 1 image-processing python-3.x deep-learning keras tensorflow

我使用此 API 从目录加载了一个数据集

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.3,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)
Run Code Online (Sandbox Code Playgroud)

我想更改数据类型并使训练更快

我尝试过,但没有成功

for image_batch, labels_batch in train_ds:
  image_batch = tf.cast(image_batch,tf.int16)
Run Code Online (Sandbox Code Playgroud)

Per*_*Pon 5

只需对您的数据集应用映射方法:

val_ds.map(lambda x, y: (tf.cast(x, tf.int16), y))
Run Code Online (Sandbox Code Playgroud)