keras瞎搞系列-卷积自编码去噪

keras瞎搞系列-卷积自编码去噪


我们把训练样本用噪声污染,然后使解码器解码出干净的照片,以获得去噪自动编码器。首先我们把原图片加入高斯噪声,然后把像素值clip到0~1。

头文件

from keras.layers import Input,Convolution2D
from keras.models import Model 
from keras.datasets import mnist
from keras.callbacks import EarlyStopping
import numpy as np 
import matplotlib.pyplot as plt 

导入数据

(X_train,_),(X_test,_) = mnist.load_data()

X_train = X_train.astype('float32')/255.
X_test = X_test.astype('float32')/255.
将值归一化到0-1

调整大小

这里所需要的是[28,28,1]维的,所以得调整大小。
X_train = np.reshape(X_train,(len(X_train),28,28,1))
X_test = np.reshape(X_test,(len(X_test),28,28,1))

添加噪声

noise_factor = 0.5
X_train_noisy = X_train+noise_factor*np.random.normal(loc=0.0,scale=1.0,size=X_train.shape)
X_test_noisy = X_test+noise_factor*np.random.normal(loc=0.0,scale=1.0,size=X_test.shape)
X_test_noisy = np.clip(X_test_noisy,0.,1.)
X_train_noisy = np.clip(X_train_noisy,0.,1.)

构建模型

input_img = Input(shape=(28,28,1))
x = Convolution2D(32,(3,3),activation='relu',padding='same')(input_img)
x = MaxPooling2D((2,2),padding='same')(x)
x = Convolution2D(32,(3,3),activation='relu',padding='same')(x)
encoded = MaxPooling2D((2,2),padding='same')(x)

x = Convolution2D(32,(3,3),activation='relu',padding='same')(encoded)
x = UpSampling2D((2,2))(x)
x = Convolution2D(32,(3,3),activation='relu',padding='same')(x)
x = UpSampling2D((2,2))(x)
decoded = Convolution2D(1,(3,3),activation='sigmoid',padding='same')(x)

autoencoder = Model(inputs=input_img,outputs = decoded)

模型编译和训练

autoencoder.compile(optimizer='adadelta',loss='binary_crossentropy')

autoencoder.fit(X_train_noisy,X_train,epochs=50,batch_size=256,shuffle=True,validation_data=(X_test_noisy,X_test))m

模型预测

decoded_imgs = autoencoder.predict(X_test_noisy)








你可能感兴趣的:(keras瞎搞系列-卷积自编码去噪)