python降维将多列数据压缩为一列_Python机器学习(Sebastian著 ) 学习笔记——第五章通过降维压缩数据(Windows Spyder Python 3.6)...
數(shù)據(jù)壓縮是機(jī)器學(xué)習(xí)領(lǐng)域中重要的內(nèi)容,通過(guò)數(shù)據(jù)壓縮技術(shù)可以將原始數(shù)據(jù)集變換到一個(gè)維度更低的新的特征子空間,幫助對(duì)數(shù)據(jù)存儲(chǔ)和分析。
降維壓縮數(shù)據(jù),分為無(wú)監(jiān)督和有監(jiān)督兩類,先來(lái)介紹無(wú)監(jiān)督數(shù)據(jù)壓縮——主成分分析(Principal Component Analysis,PCA)
PCA是在高維數(shù)據(jù)中找到最大方差的方向,并將數(shù)據(jù)映射到一個(gè)維度不大于原始數(shù)據(jù)的新的子空間上,可以基于特征之間的關(guān)系識(shí)別出數(shù)據(jù)內(nèi)在的模式。
PCA算法的流程:
對(duì)原始d維數(shù)據(jù)集做標(biāo)準(zhǔn)化出來(lái)
構(gòu)造樣本的協(xié)方差矩陣
計(jì)算協(xié)方差矩陣的特征值和相應(yīng)的特征向量
選擇與前k個(gè)最大特征值對(duì)應(yīng)的特征向量,其中k為新特征空間的維度
通過(guò)前k個(gè)特征向量構(gòu)建映射矩陣W
通過(guò)映射矩陣W將d維的輸入數(shù)據(jù)集X轉(zhuǎn)換到新的k維特征子空間
#獲取葡萄酒數(shù)據(jù)集
import pandas as pd
df_wine = pd.read_csv('D:\Python\data\wine.data', header=None)
#將數(shù)據(jù)集劃分為訓(xùn)練集(70%)和測(cè)試集(30%),并使用單位方差進(jìn)行標(biāo)準(zhǔn)化
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
sc = StandardScaler()
X_train_std = sc.fit_transform(X_train)
X_test_std = sc.fit_transform(X_test)
#構(gòu)造協(xié)方差矩陣
import numpy as np
cov_mat = np.cov(X_train_std.T) #協(xié)方差矩陣
eigen_vals, eigen_vecs = np.linalg.eig(cov_mat) #使用Numpy的linalg.eig函數(shù)計(jì)算數(shù)據(jù)集協(xié)方差矩陣的特征值對(duì)
print ('\nEigenvalues \n%s' % eigen_vals)
#特征值的方差貢獻(xiàn)率
tot = sum(eigen_vals)
var_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)]
cum_var_exp = np.cumsum(var_exp) #Numpy cumsum計(jì)算累計(jì)方差
import matplotlib.pyplot as plt
plt.bar(range(1, 14), var_exp, alpha=0.5, align='center', label='individual explained variance') #單個(gè)方差貢獻(xiàn)
plt.step(range(1, 14), cum_var_exp, where='mid', label='cumulative explained variance') #累計(jì)方差貢獻(xiàn)
plt.ylabel('Explained variance ratio')
plt.xlabel('Principal components')
plt.legend(loc='best')
plt.show()
eigen_pairs = [(np.abs(eigen_vals[i]), eigen_vecs[:, i])
for i in range(len(eigen_vals))]
eigen_pairs.sort(key = lambda k : k[0], reverse=True) #按特征值的降序排列特征
w = np.hstack((eigen_pairs[0][1] [:, np.newaxis], eigen_pairs[1][1][:, np.newaxis])) #選取兩個(gè)最大特征值對(duì)應(yīng)的特征向量 得到一個(gè)13*2的映射矩陣W
print ('Matrix W:\n', w)
X_train_std[0].dot(w)
print (X_train_std[0].dot(w))
X_train_pca = X_train_std.dot(w) #矩陣點(diǎn)積 將124*13的訓(xùn)練集轉(zhuǎn)換為包含兩個(gè)主成分的子空間上 124*2
print(X_train_pca)
#二維散點(diǎn)圖可視化
colors = ['r', 'b', 'g']
markers = ['s', 'x', 'o']
for l, c, m in zip(np.unique(y_train), colors, markers):
plt.scatter(X_train_pca[y_train == l, 0],
X_train_pca[y_train == l, 1],
c=c, label=l, marker=m)
plt.xlabel('PC 1')
plt.ylabel('PC 2')
plt.legend(loc='lower left')
plt.show()
scikit-learn中提供的PCA類 對(duì)數(shù)據(jù)集預(yù)處理再使用邏輯斯蒂回歸對(duì)轉(zhuǎn)換后的數(shù)據(jù)進(jìn)行分類
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
#對(duì)二維數(shù)據(jù)集決策邊界可視化
def plot_decision_regions(X, y, classifier, resolution=0.02):
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))]) #ListedColormap定義顏色 標(biāo)記符號(hào),通過(guò)顏色列表生成顏色示例圖
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
alpha=0.8, c=cmap(idx),
marker=markers[idx], label=cl)
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
lr = LogisticRegression()
X_train_pca = pca.fit_transform(X_train_std)
X_test_pca = pca.transform(X_test_std)
lr.fit(X_train_pca, y_train)
plot_decision_regions(X_train_pca, y_train, classifier=lr)
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.legend(loc='lower left')
plt.show()
總結(jié)
以上是生活随笔為你收集整理的python降维将多列数据压缩为一列_Python机器学习(Sebastian著 ) 学习笔记——第五章通过降维压缩数据(Windows Spyder Python 3.6)...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 格莱美壁纸好不好?为什么选择格莱美壁纸
- 下一篇: mysql单表最大数据量_你的Mysql