卷积神经网络TSNE可视化python代码
时间: 2023-09-18 07:14:25 浏览: 205
以下是使用Python代码实现卷积神经网络TSNE可视化的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
# 构建卷积神经网络
input_img = Input(shape=(28, 28, 1))
x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = Flatten()(x)
x = Dense(64, activation='relu')(x)
output = Dense(10, activation='softmax')(x)
model = Model(input_img, output)
# 加载MNIST数据集
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 预处理数据
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5, batch_size=64)
# 提取卷积层输出
conv_layer = Model(inputs=model.input, outputs=model.layers[4].output)
conv_output = conv_layer.predict(x_test)
# 使用TSNE进行降维
tsne = TSNE(n_components=2, verbose=1)
tsne_output = tsne.fit_transform(conv_output)
# 绘制可视化图像
plt.figure(figsize=(10, 10))
plt.scatter(tsne_output[:, 0], tsne_output[:, 1], c=y_test)
plt.colorbar()
plt.show()
```
在上述代码中,我们首先构建了一个简单的卷积神经网络,然后加载MNIST数据集,并对数据进行预处理。接着,我们编译并训练了模型,然后提取了第4层卷积层的输出。最后,我们使用TSNE进行降维,并将结果可视化。可以看到,在可视化结果中,不同数字的数据点被分成了不同的簇,说明卷积神经网络成功地学习到了数字的特征。
阅读全文