In [16]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
from sklearn.datasets.samples_generator import make_blobs
# X为样本特征,Y为样本簇类别, 共1000个样本,每个样本3个特征,共4个簇
X, y = make_blobs(n_samples=10000, n_features=3, centers=[[3,3, 3], [0,0,0], [1,1,1], [2,2,2]], cluster_std=[0.2, 0.1, 0.2, 0.2], 
                  random_state =9)
print(X)
print(y)
fig = plt.figure()
ax = Axes3D(fig, rect=[0, 0, 1, 1], elev=30, azim=20)
plt.scatter(X[:, 0], X[:, 1], X[:, 2],marker='o')


[[ 2.38526096  2.1109917   2.23765695]
 [ 0.05761939 -0.0117989  -0.03393958]
 [ 3.08207073  3.19904227  3.08774759]
 ..., 
 [ 3.13804869  2.86955308  2.86443838]
 [ 2.95413001  3.42508432  3.28296407]
 [ 2.79195132  2.94196066  2.71457256]]
[3 1 0 ..., 0 0 0]
D:\soft\anaconda3\lib\site-packages\matplotlib\collections.py:877: RuntimeWarning: invalid value encountered in sqrt
  scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
Out[16]:
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0xbc71940>

In [17]:
from sklearn.decomposition import PCA
pca = PCA(n_components=3)
pca.fit(X)
print(pca.explained_variance_ratio_)
print(pca.explained_variance_)


[ 0.98318212  0.00850037  0.00831751]
[ 3.78483785  0.03272285  0.03201892]

In [18]:
pca = PCA(n_components=2)
pca.fit(X)
print(pca.explained_variance_ratio_)
print(pca.explained_variance_)


[ 0.98318212  0.00850037]
[ 3.78483785  0.03272285]

In [19]:
X_new = pca.transform(X)
print(X)
print('='*40)
print(X_new)
plt.scatter(X_new[:, 0], X_new[:, 1],marker='o')
plt.show()


[[ 2.38526096  2.1109917   2.23765695]
 [ 0.05761939 -0.0117989  -0.03393958]
 [ 3.08207073  3.19904227  3.08774759]
 ..., 
 [ 3.13804869  2.86955308  2.86443838]
 [ 2.95413001  3.42508432  3.28296407]
 [ 2.79195132  2.94196066  2.71457256]]
========================================
[[ 1.29049617  0.01162118]
 [-2.5902227  -0.04141849]
 [ 2.81225258 -0.05286925]
 ..., 
 [ 2.52492314 -0.0935418 ]
 [ 2.98206456  0.03861322]
 [ 2.28089246 -0.13618233]]