下面是在代码中具体实现获取中间层输出以及可视化的方法
%matplotlib inline
import numpy as np
np.random.seed(1337)
from keras.models import Model
from keras.layers import Dense,Input
from keras.datasets import mnist
import matplotlib.pyplot as plt
#数据处理
(X_train,Y_train),(X_test,Y_test) = mnist.load_data()
#normalized data
X_train = X_train.astype(‘float32’)/255.-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)
#搭建网络
encoder_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(encoder_dim,activation=‘relu’)(encoded)
decoded = Dense(10,activation=‘relu’)(encoder_output)
decoded = Dense(64,activation=‘relu’)(decoded)
decoded = Dense(128,activation=‘relu’)(decoded)
decoded_output = Dense(784,activation=‘relu’)(decoded)
#这是原模型
autoencoder = Model(inputs=input_img,outputs=decoded_output)
#这是截取从原模型的输入层到中间层的新模型
encoder = Model(inputs = input_img, outputs=encoder_output)
autoencoder.compile(optimizer=‘adam’,loss=‘mse’,metrics=[‘accuracy’])
autoencoder.fit(X_train, X_train, epochs=3,batch_size=256,shuffle=True)
#新模型调用predict函数即可得到相当于原模型的中间层的输出结果
encoded_imgs = encoder.predict(X_test)
print(encoded_imgs.shape)
#中间层输出结果可视化
plt.figure()
#其中encoded_imgs[:,0]和encoded_imgs[:,1]代表提取出的两个特征
plt.scatter(encoded_imgs[:,0],encoded_imgs[:,1],c=Y_test)
plt.show()