I am trying to create an autoencoder for:
- Train the model
- Split encoder and decoder
- Visualise compressed data (encoder)
- Use arbitrary compressed data to get the output (decoder)
JavaScript
x
40
40
1
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
2
from keras.models import Model
3
from keras import backend as K
4
from keras.datasets import mnist
5
import numpy as np
6
7
(x_train, _), (x_test, _) = mnist.load_data()
8
9
x_train = x_train.astype('float32') / 255.
10
x_train = x_train[:100,:,:,]
11
x_test = x_test.astype('float32') / 255.
12
x_test = x_train
13
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1)) # adapt this if using `channels_first` image data format
14
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1)) # adapt this if using `channels_first` image data format
15
input_img = Input(shape=(28, 28, 1)) # adapt this if using `channels_first` image data format
16
17
x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
18
x = MaxPooling2D((2, 2), padding='same')(x)
19
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
20
encoded = MaxPooling2D((2, 2), padding='same')(x)
21
22
# at this point the representation is (7, 7, 32)
23
24
decoder = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)
25
x = UpSampling2D((2, 2))(decoder)
26
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
27
x = UpSampling2D((2, 2))(x)
28
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
29
30
autoencoder = Model(input_img, decoded(encoded(input_img)))
31
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
32
33
autoencoder.fit(x_train, x_train,
34
epochs=10,
35
batch_size=128,
36
shuffle=True,
37
validation_data=(x_test, x_test),
38
#callbacks=[TensorBoard(log_dir='/tmp/tb', histogram_freq=0, write_graph=False)]
39
)
40
How to split train it and split with the trained weights?
Advertisement
Answer
Make encoder:
JavaScript
1
9
1
input_img = Input(shape=(28, 28, 1))
2
3
x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
4
x = MaxPooling2D((2, 2), padding='same')(x)
5
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
6
encoded = MaxPooling2D((2, 2), padding='same')(x)
7
8
encoder = Model(input_img, encoded)
9
Make decoder:
JavaScript
1
10
10
1
decoder_input= Input(shape_equal_to_encoder_output_shape)
2
3
decoder = Conv2D(32, (3, 3), activation='relu', padding='same')(decoder_input)
4
x = UpSampling2D((2, 2))(decoder)
5
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
6
x = UpSampling2D((2, 2))(x)
7
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
8
9
decoder = Model(decoder_input, decoded)
10
Make autoencoder:
JavaScript
1
6
1
auto_input = Input(shape=(28,28,1))
2
encoded = encoder(auto_input)
3
decoded = decoder(encoded)
4
5
auto_encoder = Model(auto_input, decoded)
6
Now you can use any of them any way you want to.
- train the autoencoder
- use the encoder and decoder