import numpy as np from tensorflow import keras from sklearn.decomposition import PCA import matplotlib.pyplot as plt (train_data, train_labels), (test_data, test_labels) = keras.datasets.mnist.load_data() Data_Vectorize = train_data.reshape(60000,784) N = 1000; index = np.where(train_labels==0)[0] index_0 = index[0:N] Data_0_Vectorize = Data_Vectorize[index_0] index = np.where(train_labels==1)[0] index_1 = index[0:N] Data_1_Vectorize = Data_Vectorize[index_1] Data_01_Vectorize = np.zeros([2*N,784]) Data_01_Vectorize[:N,:] = Data_0_Vectorize Data_01_Vectorize[N:,:] = Data_1_Vectorize My_pca = PCA(n_components=3) Data_01_Vectorize_DR = My_pca.fit_transform(Data_01_Vectorize) plt.scatter(Data_01_Vectorize_DR[:,0],Data_01_Vectorize_DR[:,1]) plt.xlabel('PC1') plt.ylabel('PC2') plt.show()在该代码基础上,针对“0”“1”混合样本,在PC1-PC2构成的低维空间中进行高斯混合聚类。聚类总数设置为2。在PC1-PC2散点图基础上画出高斯混合聚类的中心和3倍方差组成的椭圆形边界。
时间: 2024-02-13 14:02:15 浏览: 100
好的,我来回答你的问题。
针对“0”“1”混合样本,在PC1-PC2构成的低维空间中进行高斯混合聚类,可以使用sklearn中的GaussianMixture模型。具体实现步骤如下:
首先,需要导入GaussianMixture模型:
```
from sklearn.mixture import GaussianMixture
```
接着,对数据进行高斯混合聚类:
```
gmm = GaussianMixture(n_components=2).fit(Data_01_Vectorize_DR[:, :2])
labels = gmm.predict(Data_01_Vectorize_DR[:, :2])
```
这里将聚类总数设置为2,使用fit方法对数据进行拟合,再使用predict方法对数据进行聚类。
接下来,画出高斯混合聚类的中心和3倍方差组成的椭圆形边界。可以使用以下代码实现:
```
from matplotlib.patches import Ellipse
fig = plt.figure()
ax = fig.add_subplot(111)
colors = ['red', 'blue']
for i in range(2):
ax.scatter(Data_01_Vectorize_DR[labels == i, 0], Data_01_Vectorize_DR[labels == i, 1], c=colors[i])
for pos, covar, w in zip(gmm.means_, gmm.covariances_, gmm.weights_):
U, s, Vt = np.linalg.svd(covar)
angle = np.degrees(np.arctan2(U[1, 0], U[0, 0]))
width, height = 2 * np.sqrt(3 * s)
ellip = Ellipse(xy=pos, width=width, height=height, angle=angle, alpha=w)
ax.add_artist(ellip)
ellip.set_facecolor('none')
ellip.set_edgecolor('black')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.show()
```
这里使用matplotlib库的Ellipse类,根据高斯混合模型的均值和协方差矩阵画出椭圆形边界。其中,U, s, Vt = np.linalg.svd(covar)是对协方差矩阵进行奇异值分解,np.degrees(np.arctan2(U[1, 0], U[0, 0]))是计算旋转角度,width, height = 2 * np.sqrt(3 * s)是计算椭圆形边界的宽度和高度。
最终,可以得到画出高斯混合聚类的中心和3倍方差组成的椭圆形边界的PC1-PC2散点图。
阅读全文
相关推荐
















