[Keras深度学习浅尝]实战五·使用DNN自编码器实现聚类操作数据降维

[Keras深度学习浅尝]实战五·使用DNN自编码器实现聚类操作数据降维

代码部分

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

print(train_images.shape,train_labels.shape)

train_images = train_images.reshape(-1,28*28) / 255.0

test_images = test_images.reshape(-1,28*28) / 255.0

encoding_dim = 2
# encoder layers
input_img = keras.layers.Input(shape=(28*28,))
encoded = keras.layers.Dense(128, activation='relu')(input_img)
encoded = keras.layers.Dense(64, activation='relu')(encoded)
encoded = keras.layers.Dense(10, activation='relu')(encoded)
encoder_output = keras.layers.Dense(encoding_dim)(encoded)

# decoder layers
decoded = keras.layers.Dense(10, activation='relu')(encoder_output)
decoded = keras.layers.Dense(64, activation='relu')(decoded)
decoded = keras.layers.Dense(128, activation='relu')(decoded)
decoder_output = keras.layers.Dense(784, activation='tanh')(decoded)

# construct the autoencoder model

encoder = keras.Model(inputs=input_img, outputs=encoder_output)

autoencoder = keras.Model(inputs=input_img, outputs=decoder_output)


lr = 0.001
autoencoder.compile(optimizer=tf.train.AdamOptimizer(lr),
              loss='mse',
              metrics=['accuracy'])

print(autoencoder.summary())

autoencoder.fit(train_images,train_images,batch_size=1000,epochs=50)


# plotting
encoded_imgs = encoder.predict(test_images)
plt.scatter(encoded_imgs[:, 0], encoded_imgs[:, 1], c=test_labels)
plt.colorbar()
plt.show()

输出结果

Epoch 49/50
60000/60000 [==============================] - 4s 61us/step - loss: 0.0266 - acc: 0.0176
Epoch 50/50
60000/60000 [==============================] - 4s 60us/step - loss: 0.0266 - acc: 0.0182

在这里插入图片描述

发布了168 篇原创文章 · 获赞 398 · 访问量 19万+

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览