GAN生成對抗網絡-GAN原理與基本實現-去噪與卷積自編碼器01


在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

基本去噪自編碼器

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
# 顯存自適應分配
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu,True)
gpu_ok = tf.test.is_gpu_available()
print("tf version:", tf.__version__)
print("use GPU", gpu_ok) # 判斷是否使用gpu進行訓練
# 自編碼器的數據相似性,使用手寫數字集
(x_train,y_train),(x_test,y_test) = tf.keras.datasets.mnist.load_data()

在這里插入圖片描述

x_train = x_train.reshape(x_train.shape[0],-1)
x_test = x_test.reshape(x_test.shape[0],-1) #3維reshape成2維 -1的意思就是28*28

在這里插入圖片描述

# 歸一化
x_train = tf.cast(x_train,tf.float32)/255
x_test = tf.cast(x_test,tf.float32)/255
# 增加噪聲
factor = 0.5 # 噪聲系數
# 在x_train的基礎上增加噪聲數據 點與點相加 保證 形狀不變
x_train_noise = x_train + factor*np.random.normal(size = x_train.shape)
x_test_noise = x_test + factor*np.random.normal(size = x_test.shape)
# 控制到0-1范圍之間
x_train_noise = np.clip(x_train_noise,0.,1.)
x_test_noise = np.clip(x_test_noise,0.,1.)
n = 10
# 繪制增加噪聲后的數據
plt.figure(figsize=(10,2)) 
for i in range(1,n): 
    ax = plt.subplot(1,n,i)
    plt.imshow(x_train_noise[i].reshape(28,28))

在這里插入圖片描述

# 輸入784 壓縮到長度32的向量 在還原輸出784
input_size = 784
hidden_size = 32
output_size = 784
# 創建輸入
input = tf.keras.layers.Input(shape=(input_size,)) # 輸入的形狀
# encode 編碼
en = tf.keras.layers.Dense(hidden_size,activation="relu")(input) # 對輸入形狀進行編碼為32長度向量
# decode 解碼
de = tf.keras.layers.Dense(output_size,activation="sigmoid")(en) # 還原
# 創建模型
model = tf.keras.Model(inputs=input,outputs=de) 
model.summary()

在這里插入圖片描述

# 編譯
model.compile(
    optimizer="adam",
    loss="mse"
)
# 訓練
model.fit(x_train_noise,x_train, # 輸入的是帶噪聲的圖片 目標數據是原圖
          epochs=50, # 訓練步數
          batch_size = 256, # 每次訓練256個數據
          shuffle=True, # 亂序
          validation_data=(x_test_noise,x_test)
         )

在這里插入圖片描述
在這里插入圖片描述

# 使用
encode = tf.keras.Model(inputs=input,outputs=en) # 獲取編碼器
input_de = tf.keras.layers.Input(shape=(hidden_size,))
output_de = model.layers[-1](input_de)#從模型最后一層 0x262423e1940 調用input_de

decode = tf.keras.Model(inputs=input_de,outputs=output_de)
# 使用test進行測試
encode_test = encode(x_test_noise) # 使用encode去調用x_test_noise 得到編碼后的test數據

在這里插入圖片描述

decode_test = decode.predict(encode_test) # 使用decode去調用test 得到解碼后的test數據

在這里插入圖片描述

x_test_noise = x_test.numpy() # 轉換成numpy格式
# 繪圖 10張圖片
n = 10
plt.figure(figsize=(20,4)) # 畫布長20寬4
for i in range(1,n): # 循環從1畫到n
    ax = plt.subplot(2,n,i) # 繪制此圖,2行 n列 的第i張圖片
    plt.imshow(x_test_noise[i].reshape(28,28)) # 繪制第i張圖片 reshape 成28*28的圖片格式
    ax = plt.subplot(2,n,i + n) # 繪制對應的圖片 2行 n列 n+1個
    plt.imshow(decode_test[i].reshape(28,28))

在這里插入圖片描述

卷積去噪自編碼器

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
# 顯存自適應分配
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu,True)
gpu_ok = tf.test.is_gpu_available()
print("tf version:", tf.__version__)
print("use GPU", gpu_ok) # 判斷是否使用gpu進行訓練
# 自編碼器的數據相似性,使用手寫數字集
(x_train,y_train),(x_test,y_test) = tf.keras.datasets.mnist.load_data()

在這里插入圖片描述

x_train = np.expand_dims(x_train,-1)
x_test = np.expand_dims(x_test,-1) #3維變四維

在這里插入圖片描述

# 歸一化
x_train = tf.cast(x_train,tf.float32)/255
x_test = tf.cast(x_test,tf.float32)/255
# 增加噪聲
factor = 0.5 # 噪聲系數
# 在x_train的基礎上增加噪聲數據 點與點相加 保證 形狀不變
x_train_noise = x_train + factor*np.random.normal(size = x_train.shape)
x_test_noise = x_test + factor*np.random.normal(size = x_test.shape)
# 控制到0-1范圍之間
x_train_noise = np.clip(x_train_noise,0.,1.)
x_test_noise = np.clip(x_test_noise,0.,1.)
n = 10
# 繪制增加噪聲后的數據
plt.figure(figsize=(10,2)) 
for i in range(1,n): 
    ax = plt.subplot(1,n,i)
    plt.imshow(x_train_noise[i].reshape(28,28))

在這里插入圖片描述

# 輸入784 壓縮到長度32的向量 在還原輸出784
input_size = 784
hidden_size = 32
output_size = 784
# 創建輸入
input = tf.keras.layers.Input(shape=x_train.shape[1:]) # 輸入的形狀
# encode 編碼
x = tf.keras.layers.Conv2D(16,3,activation="relu",padding="same")(input)# 28*28*16
x = tf.keras.layers.MaxPooling2D(padding="same")(x) # 14*14*16
x = tf.keras.layers.Conv2D(32,3,activation="relu",padding="same")(x) # 14*14*32
x = tf.keras.layers.MaxPooling2D(padding="same")(x) # 7*7*32
# decode 解碼
x = tf.keras.layers.Conv2DTranspose(16,3,strides=2,
                                    activation="relu",
                                    padding="same")(x)  # 反卷積 14*14*16

x = tf.keras.layers.Conv2DTranspose(1,3,strides=2,
                                    activation="sigmoid",
                                    padding="same")(x) # 28*28*1
# 創建模型
model = tf.keras.Model(inputs=input,outputs=x) 

在這里插入圖片描述

# 編譯
model.compile(
    optimizer="adam",
    loss="mse"
)
# 訓練
model.fit(x_train_noise,x_train, # 輸入的是帶噪聲的圖片 目標數據是原圖
          epochs=50, # 訓練步數
          batch_size = 256, # 每次訓練256個數據
          shuffle=True, # 亂序
          validation_data=(x_test_noise,x_test)
         )

在這里插入圖片描述
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM