Tensorflow 图像分类得到 train_images/train_X 和 train_labels/train_y

Tensorflow Image classification get train_images/train_X and train_labels/train_y

我正在研究用于识别不同蝴蝶的张量流模型。我正在为此使用神经网络,我正在从文件夹中读取图像,所有数据都在训练数据集和验证数据集中被拆分,但我想像这样拆分它们:

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

而不是:

train_ds = utils.image_dataset_from_directory(data_dir, validation_split=0.2, subset="training", seed=123, image_size=(img_height, img_width), batch_size=BATCH_SIZE)
val_ds = utils.image_dataset_from_directory(data_dir, validation_split=0.2, subset="validation", seed=123, image_size=(img_height, img_width), batch_size=BATCH_SIZE)

我试过这样做,但它使我的模型的准确性变得很糟糕,所以我认为它不正确:

train_images = np.concatenate([x for x, y in train_ds], axis=0)
train_labels = np.concatenate([y for x, y in train_ds], axis=0)
test_images = np.concatenate([x for x, y in val_ds], axis=0)
test_labels = np.concatenate([y for x, y in val_ds], axis=0)

我试了很多Whosebug的方法,但都不管用。

我的模特:

model = tf.keras.Sequential([
   # Please reread this link for a better understanding of the data being entered:
   #https://www.codespeedy.com/determine-input-shape-in-keras-tensorflow/
   layers.Conv2D(32, (3, 3), activation='relu', input_shape=(180, 180, 3)),
   layers.MaxPooling2D((2, 2)),
   layers.Conv2D(64, (3, 3), activation='relu'),
   layers.MaxPooling2D((2, 2), strides=2),
   layers.Flatten(),
   layers.Dropout(0.2, input_shape=(180, 180, 3)),
   layers.Dense(64, activation='relu'), 
   layers.Dense(5, activation='softmax') # there are 5 classes_names/folders or 5 kinds of butterflies
])

解决了问题:

train_images = np.array([]).reshape((0,180,180,3))
train_labels = np.array([]).reshape(0,)
for x, y in train_ds:
  train_images = np.concatenate((train_images, x), axis=0)
  train_labels = np.concatenate((train_labels, y), axis=0)

reshape 为图像的输入形状,大小为 0,否则不能添加 x 或 y。