自编码器图像去噪
??? 自編碼器(AutoEncoder)是深度學習中的一類無監督學習模型,由 encoder 和 decoder 兩部分組成。
??? ? encoder 將原始表示編碼成隱層表示;
??? ? decoder 將隱層表示解碼成原始表示;
??? ? 訓練目標為最小化重構誤差;
??? ? 隱層特征維度一般低于原始特征維度,降維的同時學習更稠密更有意 義的表示。
??? 自編碼器主要是一種思想,encoder 和 decoder 可以由全連接層、CNN 或 RNN 等模型實現。
??? 以下使用 Keras,用 CNN 實現自編碼器,通過學習從加噪圖片到原始 圖片的映射,完成圖像去噪任務。
用到的數據是 MNIST,手寫數字識別數據集,Keras 中自帶。 訓練集 5W 條,測試集 1W 條,都是 28 × 28 的灰度圖。實現如下:
??? # -*- coding:utf-8 -*-
??? import numpy as np
??? import matplotlib.pyplot as plt
??? from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
??? from keras.models import Model, load_model
??? ?
??? def get_data():
??????? data = np.load('mnist.npz')
??????? x_train, y_train = data['x_train'], data['y_train']
??????? x_test, y_test = data['x_test'], data['y_test']
??????? # 處理成0-1之間的值
??????? x_train = x_train.astype('float32') / 255.
??????? x_test = x_test.astype('float32') / 255.
??????? # 重新構造一個N × 1 × 28 × 28 的四維tensor
??????? x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
??????? x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
??????? return x_train,x_test
??? ?
??? def add_noise(x_train,x_test):
??????? """隨機添加噪音"""
??????? 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)
??????? # 值仍在0-1之間
??????? x_train_noisy = np.clip(x_train_noisy, 0., 1.)
??????? x_test_noisy = np.clip(x_test_noisy, 0., 1.)
??????? return x_train_noisy,x_test_noisy
??? ?
??? def remove_noisy_model(x_train_noisy,x_test_noisy):
??????? """去燥"""
??????? input_img = Input(shape=(28, 28, 1,)) # N * 28 * 28 * 1
??????? # 實現 encoder 部分,由兩個 3 × 3 × 32 的卷積和兩個 2 × 2 的最大池化組 成。
??????? x = Conv2D(32, (3, 3), padding='same', activation='relu')(input_img) # 28 * 28 * 32
??????? x = MaxPooling2D((2, 2), padding='same')(x) # 14 * 14 * 32
??????? x = Conv2D(32, (3, 3), padding='same', activation='relu')(x) # 14 * 14 * 32
??????? encoded = MaxPooling2D((2, 2), padding='same')(x) # 7 * 7 * 32
??????? # 實現 decoder 部分,由兩個 3 × 3 × 32 的卷積和兩個 2 × 2 的上采樣組成。
??????? # 7 * 7 * 32
??????? x = Conv2D(32, (3, 3), padding='same', activation='relu')(encoded) # 7 * 7 * 32
??????? x = UpSampling2D((2, 2))(x) # 14 * 14 * 32
??????? x = Conv2D(32, (3, 3), padding='same', activation='relu')(x) # 14 * 14 * 32
??????? x = UpSampling2D((2, 2))(x) # 28 * 28 * 32
??????? decoded = Conv2D(1, (3, 3), padding='same', activation='sigmoid')(x) # 28 * 28 *
??? ?
??????? autoencoder = Model(input_img, decoded)
??????? autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
??? ?
??????? autoencoder.fit(x_train_noisy, x_train,
??????????????????????? epochs=100,
??????????????????????? batch_size=128,
??????????????????????? shuffle=True,
??????????????????????? validation_data=(x_test_noisy, x_test))
??? ?
??????? autoencoder.save('autoencoder.h5')
??? ?
??? def remove_noisy(x_test_noisy):
??????? autoencoder = load_model('autoencoder.h5')
??????? decoded_imgs = autoencoder.predict(x_test_noisy)
??????? return decoded_imgs
??? ?
??? ?
??? def plot1(x_data):
??????? """畫圖"""
??????? n = 10
??????? plt.figure(figsize=(20, 2))
??????? for i in range(n):
??????????? ax = plt.subplot(1, n, i + 1)
??????????? plt.imshow(x_data[i].reshape(28, 28))
??????????? plt.gray()
??????????? ax.get_xaxis().set_visible(False)
??????????? ax.get_yaxis().set_visible(False)
??????? plt.show()
??? ?
??? def plot2(x_test_noisy,decoded_imgs):
??????? """畫圖"""
??????? n = 10
??????? plt.figure(figsize=(20, 4))
??????? for i in range(n):
??????????? # display original
??????????? ax = plt.subplot(2, n, i + 1)
??????????? plt.imshow(x_test_noisy[i].reshape(28, 28))
??????????? plt.gray()
??????????? ax.get_xaxis().set_visible(False)
??????????? ax.get_yaxis().set_visible(False)
??? ?
??????????? # display reconstruction
??????????? ax = plt.subplot(2, n, i + 1 + n)
??????????? plt.imshow(decoded_imgs[i].reshape(28, 28))
??????????? plt.gray()
??????????? ax.get_xaxis().set_visible(False)
??????????? ax.get_yaxis().set_visible(False)
??????? plt.show()
??? ?
??? x_train,x_test =get_data()
??? x_train_noisy, x_test_noisy = add_noise(x_train,x_test)
??? decoded_imgs = remove_noisy(x_test_noisy)
??? plot2(x_test_noisy,decoded_imgs)
??? 最后結果展示:
https://github.com/littlemesie/AI-project/tree/master/image_denoise
?
————————————————
版權聲明:本文為CSDN博主「mesie美?!沟脑瓌撐恼?#xff0c;遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/baidu_28610773/article/details/84666918
總結
- 上一篇: 深度学习论文翻译--Deep Resid
- 下一篇: 基于深度学习的CT图像肺结节自动检测(系