【问题标题】:Normalizing BatchDataset in Tensorflow 2.3在 TensorFlow 2.3 中规范化 BatchDataset
【发布时间】:2020-12-13 18:25:08
【问题描述】:

我正在使用 TF 2.3 中的 tf.keras.preprocessing.image_dataset_from_directory 从目录加载图像(训练/测试拆分)。我得到的是一个带有形状的 tf.data.Dataset (tensorflow.python.data.ops.dataset_ops.BatchDatasetactually) 对象:

train_ds.take(1)
# <TakeDataset shapes: ((None, 256, 256, 3), (None, 6)), types: (tf.float32, tf.float32)>
for images, labels in train_ds.take(1):
    print(images.shape)
    print(images[0])
# (32, 256, 256, 3)
# tf.Tensor(
# [[[225.75  225.75  225.75 ]
#   [225.75  225.75  225.75 ]
#   [225.75  225.75  225.75 ]
#   ...
#   [215.    214.    209.   ]
#   [215.    214.    209.   ]
#   [215.    214.    209.   ]]
#
#  ...], shape=(256, 256, 3), dtype=float32)

我无法弄清楚如何使用该 Dataset 对象规范化图像 (/= 255)。我尝试使用/= 运算符本身、mapapply 方法,甚至将该对象转换为here 中提到的列表。似乎没有任何效果,我真的很想在数据集级别解决这个问题,而不是在我的网络中添加规范化层。

有什么想法吗?

【问题讨论】:

  • 你能展示一下你是如何使用map 对来自 tf 数据集的图像进行归一化的吗

标签: python tensorflow keras deep-learning tensorflow-datasets


【解决方案1】:

试试这个方法:

def process(image,label):
    image = tf.cast(image/255. ,tf.float32)
    return image,label

ds = tf.keras.preprocessing.image_dataset_from_directory(IMAGE_DIR)
ds = ds.map(process)

【讨论】:

  • 我真的相信我做了类似的事情(在另一个问题中发现)但没有奏效。这段代码似乎可以工作。非常感谢,原来那是我的愚蠢错误
  • 这段代码似乎将数据集类型更改为MapDataset,这稍后会引发错误(即 MapDataset 没有我使用的属性 class_names),但规范化本身正在工作
  • 当然,它在这里:github.com/mtszkw/garbage/blob/master/garbage2.ipynb 我已经解决了 class_names 的问题(通过明确提供名称列表)。
猜你喜欢
  • 2021-05-15
  • 2018-04-29
  • 2021-01-12
  • 2012-05-22
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
相关资源
最近更新 更多