程序示例–PCA for 數據可視化
我們有一張小鳥的圖片,這是一個三通道彩色圖像:
我們將圖片的像素按顏色進行聚類,并在三維空間觀察聚類成果:
似乎在三維空間可視化不是那么直觀,借助于PCA,我們將聚類結果降到二維空間進行可視化:
測試代碼:
import numpy
as np
import kmeans
import pca
from scipy
.io
import loadmat
from mpl_toolkits
.mplot3d
import Axes3D
import matplotlib
.pyplot
as plt
import matplotlib
.cm
as cmx
import matplotlib
.colors
as colors
def getCmap(count
):color_norm
= colors
.Normalize
(vmin
=0, vmax
=count
-1)scalar_map
= cmx
.ScalarMappable
(norm
=color_norm
, cmap
='hsv')def map_index_to_rgb_color(index
):return scalar_map
.to_rgba
(index
)return map_index_to_rgb_colorfig
= plt
.figure
()
ax
= fig
.add_subplot
(111, projection
='3d')data
= loadmat
('data/bird_small.mat')
A
= data
['A']A
= A
/ 255.0;height
, width
, channels
= A
.shape
X
= np
.mat
(A
.reshape
(height
* width
, channels
))m
, n
= X
.shapeclusterNum
= 16
cmap
= getCmap
(clusterNum
)
centroids
, clusterAssment
= kmeans
.kMeans
(X
, clusterNum
)
sampleSize
= 1000
sampleIndexs
= np
.random
.choice
(m
, sampleSize
)
clusters
= clusterAssment
[sampleIndexs
]
samples
= X
[sampleIndexs
]
for i
in range(sampleSize
):x
, y
, z
= samples
[i
,:].A
[0]center
= clusters
[i
, 0]color
= cmap
(center
)ax
.scatter
([x
], [y
], [z
], color
=color
, marker
='o')
plt
.show
()
reducedSamples
= pca
.PCA
(samples
, k
=2)[1]
for i
in range(sampleSize
):x
, y
= reducedSamples
[i
,:].A
[0]center
= clusters
[i
, 0]color
= cmap
(center
)plt
.scatter
([x
], [y
], color
=color
, marker
='o')
plt
.show
()
總結
以上是生活随笔為你收集整理的7.5 程序示例--PCA for 数据可视化-机器学习笔记-斯坦福吴恩达教授的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。