t-SNE高維數(shù)據(jù)可視化(python)這篇文章非常好,貼出來(lái)的代碼绅这,直接可正確運(yùn)行。 t-SNE算法理解:An illustrated introduction to the t-SNE algorithm? ?也可以了解一下:Python數(shù)據(jù)可視化模塊—Seaborn
一甘耿、什么是t-SNE?
t-SNE(t-distributedstochastic neighbor embedding?)是目前最為流行的一種高維數(shù)據(jù)降維的算法搓茬。
對(duì)計(jì)算機(jī)而言,處理高維數(shù)據(jù)絕對(duì)沒(méi)問(wèn)題试浙,但是人類能感知的確只有三個(gè)維度董瞻,因此很有必要將高維數(shù)據(jù)可視化的展現(xiàn)出來(lái)。那么如何將數(shù)據(jù)集從一個(gè)任意維度的降維到二維或三維呢田巴?钠糊??T-SNE就是一種數(shù)據(jù)降維的算法壹哺,其成立的前提是基于這樣的假設(shè):盡管現(xiàn)實(shí)世界中的許多數(shù)據(jù)集是嵌入在高維空間中抄伍,但是都具有很低的內(nèi)在維度。也就是說(shuō)高維數(shù)據(jù)經(jīng)過(guò)降維后管宵,在低維狀態(tài)下更能顯示出其本質(zhì)特性截珍。這就是流行學(xué)習(xí)的基本思想,也稱為非線性降維箩朴。
二岗喉、代碼解讀
下面就展示一下如何使用t-SNE算法可視化sklearn庫(kù)中的手寫字體數(shù)據(jù)集。詳細(xì)隧饼,請(qǐng)參考t-SNE高維數(shù)據(jù)可視化(python)這篇文章沈堡。
import numpyas np
import sklearn
from sklearn.manifold import TSNE
from sklearn.datasets import load_digits
RS =20150101
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import matplotlib
# We import seaborn to make nice plots.
import seabornas sns
sns.set_style('darkgrid')
sns.set_palette('muted')
sns.set_context("notebook", font_scale=1.5,
? ? ? ? ? ? ? ? rc={"lines.linewidth":2.5})
digits = load_digits()
# We first reorder the data points according to the handwritten numbers.
# ###X.shape=[1797,64]? 點(diǎn)數(shù)1797 維度64
X = np.vstack([digits.data[digits.target==i]for iin range(10)])
# print(X[0])
# ###y.shape=[1797]? 點(diǎn)的標(biāo)簽1797
y = np.hstack([digits.target[digits.target==i]for iin range(10)])
# print(y[0])
# ###使用TSNE算法將高維度數(shù)據(jù)點(diǎn)進(jìn)行降維處理
# ###X.shape=[1797,64]? 降維后為:[1797,2],即digits_proj.shape=[1797,2]
digits_proj = TSNE(random_state=RS).fit_transform(X)
def scatter(x, colors):
# We choose a color palette with seaborn.
? ? palette = np.array(sns.color_palette("hls", 10))
# We create a scatter plot.
? ? f = plt.figure(figsize=(8, 8))
ax = plt.subplot(aspect='equal')
sc = ax.scatter(x[:,0], x[:,1], lw=0, s=40,
? ? ? ? ? ? ? ? ? ? c=palette[colors.astype(np.int)])
plt.xlim(-25, 25)
plt.ylim(-25, 25)
ax.axis('off')
ax.axis('tight')
# We add the labels for each digit.
? ? txts = []
for iin range(10):
# Position of each label.
? ? ? ? xtext, ytext = np.median(x[colors == i, :], axis=0)
txt = ax.text(xtext, ytext, str(i), fontsize=24)
txt.set_path_effects([
PathEffects.Stroke(linewidth=5, foreground="w"),
? ? ? ? ? ? PathEffects.Normal()])
txts.append(txt)
return f, ax, sc, txts
# ##調(diào)用自定義的函數(shù),畫出數(shù)據(jù)分布的散點(diǎn)圖
scatter(digits_proj, y)
plt.savefig('digits_tsne-generated.png', dpi=120)
plt.show()
參考文章:
【1】t-SNE高維數(shù)據(jù)可視化(python)