其他分享
首页 > 其他分享> > Keras(六)Autoencoder 自编码 原理及实例 Save&reload 模型的保存和提取

Keras(六)Autoencoder 自编码 原理及实例 Save&reload 模型的保存和提取

作者:互联网

Autoencoder 自编码

import numpy as np
np.random.seed(1)
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Dense, Input
import matplotlib.pyplot as plt

# 获取数据 非监督学习 不用y
(x_train, _), (x_test, y_test) = mnist.load_data()

# 预处理
x_train = x_train.astype('float32') / 255. - 0.5 # 标准化 -0.5~0.5
x_test = x_test.astype('float32') / 255. - 0.5
x_train = x_train.reshape((x_train.shape[0], -1))
x_test = x_test.reshape((x_test.shape[0], -1))
# print(x_train.shape)
# print(x_test.shape)

# 要压成的维度
encoding_dim = 2

# 原来的图片数据大小
input_img = Input(shape=(784,))

## 建立神经网路
# 编码层
encoded = Dense(128, activation='relu')(input_img)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(10, activation='relu')(encoded)
encoder_output = Dense(encoding_dim)(encoded)
# 解码层
decoded = Dense(10, activation='relu')(encoder_output)
decoded = Dense(64, activation='relu')(decoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(784, activation='tanh')(decoded)
# 构建自动编码模型
autoencoder = Model(input=input_img, output=decoded)

# 激活模型
autoencoder.compile(optimizer='adam', loss='mse')

# 训练 非监督学习 经历压缩和解压的自己跟原来的自己比较
autoencoder.fit(x_train, x_train,epochs=20,batch_size=256,shuffle=True)

# 可视化结果
encoded_imgs = autoencoder.predict(x_test)
plt.scatter(encoded_imgs[:, 0], encoded_imgs[:, 1], c=y_test)
plt.colorbar()
plt.show()

输出:

Epoch 1/20

  256/60000 [..............................] - ETA: 1:41 - loss: 0.2318
 1280/60000 [..............................] - ETA: 22s - loss: 0.2211 
。。。
59648/60000 [============================>.] - ETA: 0s - loss: 0.0393
60000/60000 [==============================] - 2s 41us/step - loss: 0.0393

Save&reload 保存提取

标签:编码,Dense,Keras,reload,train,encoded,test,Autoencoder,model
来源: https://www.cnblogs.com/peng8098/p/keras_6.html