Repository navigation
Expand file tree
/
Copy pathdenoise_autoencoder.py
More file actions
158 lines (133 loc) · 6.48 KB
/
Copy pathdenoise_autoencoder.py
File metadata and controls
158 lines (133 loc) · 6.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers
import tensorflow_datasets as tfds
# Paths to save/load data and model
DATA_DIR = 'data'
MODEL_DIR = 'weights'
RESULTS_DIR = 'results'
DATA_PATH = f'{DATA_DIR}/stl10_denoising_data.npz'
MODEL_PATH = f'{MODEL_DIR}/stl10denoising_autoencoder.weights.h5'
DENOISED_IMAGE_PATH = f'{RESULTS_DIR}/denoised_stl10_images.png'
def initialize_directories():
# Create directories if they do not exist
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(MODEL_DIR, exist_ok=True)
os.makedirs(RESULTS_DIR, exist_ok=True)
def load_data():
if os.path.exists(DATA_PATH):
print("Loading saved data...")
data = np.load(DATA_PATH)
return data['x_train_noisy'], data['x_train']
print("Downloading and preparing STL-10...")
# Load STL-10 dataset from TensorFlow Datasets
ds = tfds.load('stl10', split='unlabelled', as_supervised=False)
# Preprocess the dataset, loading the images as numpy arrays
# and normalizing them.
# This is needed to ensure the autoencoder works correctly.
# As the images are in RGB format, we will normalize them to [0, 1].
images = [example['image'].astype(np.float32) / 255.0 for example in tfds.as_numpy(ds)]
# Load only the first 10,000 images for training
# This is to keep from loading the whole dataset into memory.
x_train = np.stack(images[:10000])
# Add noise to the images
# We will add Gaussian noise to the images.
# The noise factor can be adjusted to control the amount of noise.
noise_factor = 0.2
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_train_noisy = np.clip(x_train_noisy, 0., 1.)
# Save the noisy and original images to a .npz file, that can be loaded later.
np.savez(DATA_PATH, x_train_noisy=x_train_noisy, x_train=x_train)
return x_train_noisy, x_train
def build_autoencoder():
# Defines the input shape of the autoencoder
# The input shape is (96, 96, 3) for STL-10
# This is because STL-10 images are 96x96 pixels and have 3 color channels (RGB).
# The autoencoder will learn to denoise these images.
input_img = tf.keras.Input(shape=(96, 96, 3))
# Encoder
# The encoder consists of several convolutional layers followed by max pooling.
# Each convolutional layer reduces the spatial dimensions of the input,
# while increasing the number of feature maps.
# The max pooling layers downsample the feature maps, reducing their size.
# The final encoded representation is a compressed version of the input image.
e1 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
p1 = layers.MaxPooling2D((2, 2), padding='same')(e1)
e2 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(p1)
p2 = layers.MaxPooling2D((2, 2), padding='same')(e2)
e3 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(p2)
p3 = layers.MaxPooling2D((2, 2), padding='same')(e3)
e4 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(p3)
encoded = layers.MaxPooling2D((2, 2), padding='same')(e4)
# Decoder
# The decoder consists of several convolutional layers followed by upsampling.
# Each upsampling layer increases the spatial dimensions of the feature maps,
# while the convolutional layers refine the features.
# The final output is a denoised version of the input image.
#
# The decoder mirrors the encoder, gradually reconstructing the image.
# The concatenation layers combine the features from the encoder with the upsampled features,
# allowing the decoder to use the high-level features learned by the encoder.
# The skip connections help preserve spatial information
# and improve the quality of the reconstructed image.
d1 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(encoded)
u1 = layers.UpSampling2D((2, 2))(d1)
u1 = layers.Concatenate()([u1, e4])
d2 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(u1)
u2 = layers.UpSampling2D((2, 2))(d2)
u2 = layers.Concatenate()([u2, e3])
d3 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(u2)
u3 = layers.UpSampling2D((2, 2))(d3)
u3 = layers.Concatenate()([u3, e2])
d4 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(u3)
u4 = layers.UpSampling2D((2, 2))(d4)
u4 = layers.Concatenate()([u4, e1])
decoded = layers.Conv2D(3, (3, 3), activation='sigmoid', padding='same')(u4)
autoencoder = tf.keras.Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='mse')
return autoencoder
def train_autoencoder(autoencoder, x_train_noisy, x_train):
if os.path.exists(MODEL_PATH):
print("Loading saved model...")
autoencoder.load_weights(MODEL_PATH)
else:
# Train the autoencoder
# The autoencoder is trained for 50 epochs with a batch size of 128.
# The training data is shuffled to ensure that the model learns from different images in each epoch
# We give the noisy images as input and the original images as target, to check with the loss function of MSE.
print("Training model...")
autoencoder.fit(x_train_noisy, x_train,
epochs=50,
batch_size=128,
shuffle=True)
autoencoder.save_weights(MODEL_PATH)
return autoencoder
def visualize(autoencoder, x_train_noisy, x_train):
n = 10
decoded_imgs = autoencoder.predict(x_train_noisy[:n])
plt.figure(figsize=(20, 6))
for i in range(n):
ax = plt.subplot(3, n, i + 1)
plt.imshow(x_train[i])
plt.title("Original")
plt.axis("off")
# Noisy
ax = plt.subplot(3, n, i + 1 + n)
plt.imshow(x_train_noisy[i])
plt.title("Noisy")
plt.axis("off")
# Denoised
ax = plt.subplot(3, n, i + 1 + 2 * n)
plt.imshow(decoded_imgs[i])
plt.title("Denoised")
plt.axis("off")
plt.tight_layout()
plt.savefig(DENOISED_IMAGE_PATH)
if __name__ == "__main__":
initialize_directories()
x_train_noisy, x_train = load_data()
autoencoder = build_autoencoder()
autoencoder = train_autoencoder(autoencoder, x_train_noisy, x_train)
visualize(autoencoder, x_train_noisy, x_train)