[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

在这里插入图片描述

©️2020 CSDN 皮肤主题: 1024 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值