如何从tensorflow数据集中提取没有标签的数据
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 数据集方法 unbatch() 取消对数据集的批处理,然后您可以轻松地从中检索数据和标签:
data=[]
for images, labels in ds.unbatch():
data.append(images)
我有一个名为 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 数据集方法 unbatch() 取消对数据集的批处理,然后您可以轻松地从中检索数据和标签:
data=[]
for images, labels in ds.unbatch():
data.append(images)