python-3.x - 如何将 tensorflow.python.data.ops.dataset_ops.BatchDataset 转换为 numpy 数组?
问题描述
我有一个图像数据集
|-Train
| |-Defective
| |-images
| |-Not_Defective
| |-images
我使用以下函数对这些图像进行了预处理
dir='../input/railwaytrackv4/Dataset _ Railway Track Fault Detection-20210713T183411Z-001/Dataset _ Railway Track Fault Detection/Train'
train_data=tf.keras.utils.image_dataset_from_directory(directory=dir,
labels='inferred',
batch_size=32,
image_size=(256, 256))
它给出的输出为Found 1469 files belonging to 2 classes.
和
type(train_data)
=tensorflow.python.data.ops.dataset_ops.BatchDataset
如何将其转换train_data
为 numpy 数组?
更新:
我试过了
for x, y in train_data:
x = x.numpy()
y = y.numpy()
但它给出了以下输出
2021-11-01 08:48:15.079479: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2)
2021-11-01 08:48:25.085070: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:175] Filling up shuffle buffer (this may take a while): 250 of 11760
2021-11-01 08:48:35.132351: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:175] Filling up shuffle buffer (this may take a while): 558 of 11760
2021-11-01 08:48:45.122079: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:175] Filling up shuffle buffer (this may take a while): 843 of 11760
2021-11-01 08:48:55.135867: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:175] Filling up shuffle buffer (this may take a while): 1160 of 11760
2021-11-01 08:49:05.080678: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:175] Filling up shuffle buffer (this may take a while): 1455 of 11760
2021-11-01 08:49:05.657894: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:228] Shuffle buffer filled.
2021-11-01 08:49:05.665031: W tensorflow/core/framework/cpu_allocator_impl.cc:80] Allocation of 1155268608 exceeds 10% of free system memory.
注意:找到属于 2 个类的 1469 个文件。
解决方案
tf.keras.utils.image_dataset_from_directory
返回 atf.data.Dataset
这是一个花哨的生成器,它产生的值正如你在 python 中所期望的那样,唯一的区别是它产生 tensorflowTensor
对象,所以你只需要numpy
使用numpy()
方法将它们转换为对象
x, y = next(train_data)
x = x.numpy()
y = y.numpy()
for x, y in train_data:
x = x.numpy()
y = y.numpy()
编辑:
数据集是批处理的,这意味着您将始终分批读取文件。当您定义tf.keras.utils.image_dataset_from_directory
数据集时,您可能指定了参数batch_size=29
。如果您想一次读取整个数据集,您可以使用batch_size=735
,但请注意 tensorflowDataset
旨在用作驱动器中的生成器。如果您可以将数据集放入内存中,则最好自己阅读文件,例如使用tf.keras.utils.load_img
.
推荐阅读
- r - 过滤/子集R中数据框中的所有因素
- powerapps - SortByColumns / Filter / Search 和 Yes/No
- java - 在 Android-Studio 中访问 XML 文件
- azure - 如何将多个键值对作为 ENV 变量从 Azure 密钥库机密加载到 k8s POD
- jakarta-ee - 在 Quarkus 中使用 @RolesAllowed 和自定义 JWT 验证,没有 smallrye-jwt
- jquery - 在 jQuery 中,如果元素包含属性,无论其值如何,我如何找到它们?
- python - 在括号内使用python for循环
- r - 对称共生矩阵的最小重叠
- ios - iOS 使用外部键盘显示/隐藏屏幕键盘
- c# - Unity配色游戏