
[英]How to extract samples from a Tensorflow Dataset which have the same label?
[英]How to extract data without label from tensorflow dataset
我有一个名为 train_ds 的 tf 数据集:
directory = 'Data/dataset_train'
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
directory,
validation_split=0.2,
subset="training",
color_mode='grayscale',
seed=123,
image_size=(28, 28),
batch_size=32)
这个数据集由 20000 张“假”图像和 20000 张“真实”图像组成,我想从这个 tf 数据集中提取 numpy 形式的 X_train 和 y_train ,但我只设法用
y_train = np.concatenate([y for x, y in train_ds], axis=0)
我也试过这个,但它似乎并没有遍历 20000 张图像:
for images, labels in train_ds.take(-1):
X_train = images.numpy()
y_train = labels.numpy()
我真的很想将图像提取到 X_train 并将标签提取到 y_train 但我无法弄清楚:对于我所犯的任何错误,我提前道歉并感谢我能得到的所有帮助:)
如果您没有对数据集应用进一步的转换,它将是BatchDataset
。 您可以创建两个列表来迭代数据集。 这里总共有2936张图像。
x_train, y_train = [], []
for images, labels in train_ds:
x_train.append(images.numpy())
y_train.append(labels.numpy())
np.array(x_train).shape >> (92,)
它正在生成批次。 您可以使用np.concatenate
连接它们。
x_train = np.concatenate(x_train, axis = 0)
x_train.shape >> (2936,28,28,3)
或者您可以取消批处理数据集并对其进行迭代:
for images, labels in train_ds.unbatch():
x_train.append(images.numpy())
y_train.append(labels.numpy())
x_train = np.array(x_train)
x_train.shape >> (2936,28,28,3)
您可以使用 TF Dataset 方法unbatch () 取消批处理数据集,然后您可以轻松地从中检索数据和标签:
data=[]
for images, labels in ds.unbatch():
data.append(images)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.