dos*_*rog 3 python deep-learning keras tensorflow tensorflow-datasets
这里有一个类似的问题,询问如何使用image_dataset_from_directory()自动编码器。问题实际上没有答案,因为答案建议使用其他东西。
我的问题是,是否可以用作image_dataset_from_directory()Keras 中卷积自动编码器的输入?
这绝对是可能的,您只需事先调整模型的输入:
import tensorflow as tf
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
batch_size = 32
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(28, 28),
batch_size=batch_size)
normalization_layer = tf.keras.layers.Rescaling(1./255)
def change_inputs(images, labels):
x = tf.image.resize(normalization_layer(images),[28, 28], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
return x, x
normalized_ds = train_ds.map(change_inputs)
input_img = tf.keras.Input(shape=(28, 28, 3))
x = tf.keras.layers.Flatten()(input_img)
x = tf.keras.layers.Dense(28 * 28 * 3, activation='relu')(x)
output = tf.keras.layers.Reshape(target_shape=(28, 28 ,3))(x)
autoencoder = tf.keras.Model(input_img, output)
autoencoder.compile(optimizer='adam', loss='mse')
history = autoencoder.fit(normalized_ds, epochs=2)
Run Code Online (Sandbox Code Playgroud)
Found 3670 files belonging to 5 classes.
Using 2936 files for training.
Epoch 1/2
92/92 [==============================] - 4s 41ms/step - loss: 0.1538
Epoch 2/2
92/92 [==============================] - 4s 40ms/step - loss: 0.1300
Run Code Online (Sandbox Code Playgroud)
请注意,我使用单个完全级联的神经层作为编码器和解码器,但它们可以轻松地被 CNN 网络替换。我还将图像缩小到更小的尺寸以便快速演示。
| 归档时间: |
|
| 查看次数: |
2131 次 |
| 最近记录: |