用堆叠自编码器进行图像分类Python代码
时间: 2023-06-11 09:04:30 浏览: 99
以下是使用堆叠自编码器进行图像分类的Python代码:
```
# 导入相关的库和模块
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Input, Dense, Flatten, Reshape
from tensorflow.keras.models import Model
# 加载 MNIST 数据集并进行预处理
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.astype('float32') / 255.
test_images = test_images.astype('float32') / 255.
train_images = np.reshape(train_images, (len(train_images), 28, 28, 1))
test_images = np.reshape(test_images, (len(test_images), 28, 28, 1))
# 定义编码器模型
input_img = Input(shape=(28, 28, 1))
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
# 定义解码器模型
x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
# 定义自编码器模型
autoencoder = Model(input_img, decoded)
# 定义编码模型
encoder = Model(input_img, encoded)
# 编译自编码器模型
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
# 训练自编码器模型
autoencoder.fit(train_images, train_images,
epochs=10,
batch_size=128,
shuffle=True,
validation_data=(test_images, test_images))
# 对测试集进行分类并输出结果
encoded_imgs = encoder.predict(test_images)
predicted_labels = np.argmax(encoded_imgs, axis=1)
accuracy = np.sum(predicted_labels == test_labels) / len(test_labels)
print("Accuracy:", accuracy)
```
阅读全文