# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from sklearn import datasets,manifold def load_data(): ''' 加載用於降維的數據 ''' # 使用 scikit-learn 自帶的 iris 數據集 iris=datasets.load_iris() return iris.data,iris.target #局部線性嵌入LLE降維模型 def test_LocallyLinearEmbedding(*data): X,y=data # 依次考察降維目標為 4維、3維、2維、1維 for n in [4,3,2,1]: lle=manifold.LocallyLinearEmbedding(n_components=n) lle.fit(X) print('reconstruction_error(n_components=%d) : %s'%(n, lle.reconstruction_error_)) # 產生用於降維的數據集 X,y=load_data() # 調用 test_LocallyLinearEmbedding test_LocallyLinearEmbedding(X,y)
def plot_LocallyLinearEmbedding_k(*data): ''' 測試 LocallyLinearEmbedding 中 n_neighbors 參數的影響,其中降維至 2維 ''' X,y=data # n_neighbors參數的候選值的集合 Ks=[1,5,25,y.size-1] fig=plt.figure() for i, k in enumerate(Ks): lle=manifold.LocallyLinearEmbedding(n_components=2,n_neighbors=k) #原始數據集轉換到二維 X_r=lle.fit_transform(X) ## 兩行兩列,每個單元顯示不同 n_neighbors 參數的 LocallyLinearEmbedding 的效果圖 ax=fig.add_subplot(2,2,i+1) # 顏色集合,不同標記的樣本染不同的顏色 colors=((1,0,0),(0,1,0),(0,0,1),(0.5,0.5,0),(0,0.5,0.5),(0.5,0,0.5),(0.4,0.6,0),(0.6,0.4,0),(0,0.6,0.4),(0.5,0.3,0.2)) for label ,color in zip( np.unique(y),colors): position=y==label ax.scatter(X_r[position,0],X_r[position,1],label="target= %d"%label,color=color) ax.set_xlabel("X[0]") ax.set_ylabel("X[1]") ax.legend(loc="best") ax.set_title("k=%d"%k) plt.suptitle("LocallyLinearEmbedding") plt.show() # 調用 plot_LocallyLinearEmbedding_k plot_LocallyLinearEmbedding_k(X,y)
def plot_LocallyLinearEmbedding_k_d1(*data): ''' 測試 LocallyLinearEmbedding 中 n_neighbors 參數的影響,其中降維至 1維 ''' X,y=data Ks=[1,5,25,y.size-1]# n_neighbors參數的候選值的集合 fig=plt.figure() for i, k in enumerate(Ks): lle=manifold.LocallyLinearEmbedding(n_components=1,n_neighbors=k) X_r=lle.fit_transform(X)#原始數據集轉換到 1 維 ax=fig.add_subplot(2,2,i+1)## 兩行兩列,每個單元顯示不同 n_neighbors 參數的 LocallyLinearEmbedding 的效果圖 colors=((1,0,0),(0,1,0),(0,0,1),(0.5,0.5,0),(0,0.5,0.5),(0.5,0,0.5), (0.4,0.6,0),(0.6,0.4,0),(0,0.6,0.4),(0.5,0.3,0.2),)# 顏色集合,不同標記的樣本染不同的顏色 for label ,color in zip( np.unique(y),colors): position=y==label ax.scatter(X_r[position],np.zeros_like(X_r[position]), label="target= %d"%label,color=color) ax.set_xlabel("X") ax.set_ylabel("Y") ax.legend(loc="best") ax.set_title("k=%d"%k) plt.suptitle("LocallyLinearEmbedding") plt.show() # 調用 plot_LocallyLinearEmbedding_k_d1 plot_LocallyLinearEmbedding_k_d1(X,y)