python实现自编码器
时间: 2023-12-04 15:30:26 浏览: 39
自编码器是一种无监督学习算法,可以用于数据压缩、特征提取等任务。下面是一个使用Python实现自编码器的示例代码:
```
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
# 定义自编码器模型
class Autoencoder(tf.keras.Model):
def __init__(self, encoding_dim):
super(Autoencoder, self).__init__()
self.encoding_dim = encoding_dim
self.encoder = tf.keras.Sequential([
layers.Dense(128, activation='relu'),
layers.Dense(encoding_dim, activation='relu')
])
self.decoder = tf.keras.Sequential([
layers.Dense(128, activation='relu'),
layers.Dense(784, activation='sigmoid')
])
def call(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
# 加载MNIST数据集
(x_train, _), (x_test, _) = tf.keras.datasets.mnist.load_data()
# 数据预处理
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
# 将数据展平成一维向量
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
# 创建自编码器模型
autoencoder = Autoencoder(encoding_dim=32)
# 编译模型
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
# 训练模型
autoencoder.fit(x_train, x_train,
epochs=50,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
# 使用自编码器进行数据压缩和重建
encoded_imgs = autoencoder.encoder(x_test).numpy()
decoded_imgs = autoencoder.decoder(encoded_imgs).numpy()
# 可视化重建后的图像
import matplotlib.pyplot as plt
n = 10 # 显示前10张图像
plt.figure(figsize=(20, 4))
for i in range(n):
# 显示原始图像
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# 显示重建后的图像
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()
```
该代码使用Keras API构建自编码器模型,其中编码器和解码器均为两层全连接层。训练模型时使用MNIST数据集,并将每张图像展平成一维向量。最后将自编码器用于压缩和重建图像,并将原始图像和重建后的图像可视化展示出来。