無監(jiān)督學習
- 發(fā)現(xiàn)數(shù)據(jù)本身的分布特點
數(shù)據(jù)聚類 K-means
預先設定聚類個數(shù)煌往,再不斷更新聚類中心,多輪迭代后力穗,使得所有數(shù)據(jù)點到其所屬聚類中心距離的平方和趨于穩(wěn)定.
#matplotlib inline
import numpy as np
# 從sklearn.cluster中導入KMeans算法包
from sklearn.cluster import KMeans
# 從sklearn.metrics導入silhouette_score用于計算輪廓系數(shù)
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
# 初始化原始數(shù)據(jù)點。
x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])
x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 4, 3])
X = np.array(list(zip(x1, x2))).reshape(len(x1), 2)
plt.figure(figsize=(16, 8))
# 在1號子圖做出原始數(shù)據(jù)點陣的分布。
plt.subplot(2, 3, 1)
plt.xlim([0, 10])
plt.ylim([0, 10])
plt.title('Instances')
plt.scatter(x1, x2)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b']
markers = ['o', 's', 'D', 'v', '^', 'p', '*', '+']
clusters = [2, 3, 4, 5, 8]
subplot_counter = 1
sc_scores = []
for t in clusters:
subplot_counter += 1
plt.subplot(2, 3, subplot_counter)
# 根據(jù)每次不同的 cluster值進行聚類
kmeans_model = KMeans(n_clusters=t).fit(X)
for i, l in enumerate(kmeans_model.labels_):
plt.plot(x1[i], x2[i], color=colors[l], marker=markers[l], ls='None')
plt.xlim([0, 10])
plt.ylim([0, 10])
# 輪廓系數(shù)評估 聚類算法
sc_score = silhouette_score(X, kmeans_model.labels_, metric='euclidean')
sc_scores.append(sc_score)
# 繪制輪廓系數(shù)與不同類簇數(shù)量的直觀顯示圖诞外。
plt.title('K = %s, silhouette coefficient= %0.03f' %(t, sc_score))
print(sc_scores)
# 繪制輪廓系數(shù)與不同類簇數(shù)量的關系曲線。
plt.figure()
plt.plot(clusters, sc_scores, '*-')
plt.xlabel('Number of Clusters')
plt.ylabel('Silhouette Coefficient Score')
plt.tight_layout()
plt.show()
k-means
optdigits手寫體聚類
#%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 從sklearn.cluster中導入KMeans模型
from sklearn.cluster import KMeans
# 從sklearn導入度量函數(shù)庫metrics
from sklearn import metrics
# 使用pandas分別讀取訓練數(shù)據(jù)與測試數(shù)據(jù)集
digits_train = pd.read_csv('data/optdigits_train.csv', header=None)
digits_test = pd.read_csv('data/optdigits_test.csv', header=None)
# 從訓練與測試數(shù)據(jù)集上都分離出64維度的像素特征與1維度的數(shù)字目標
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]
X_test = digits_test[np.arange(64)]
y_test = digits_test[64]
# 初始化KMeans模型灾票,并設置聚類中心數(shù)量為10
kmeans = KMeans(n_clusters=10)
kmeans.fit(X_train)
# 逐條判斷每個測試圖像所屬的聚類中心
y_pred = kmeans.predict(X_test)
# 使用ARI進行KMeans聚類性能評估
print(metrics.adjusted_rand_score(y_test, y_pred))
print(digits_train[64].unique())
digits_train.head()
image.png
數(shù)據(jù)降維
對optdigits_train數(shù)據(jù)進行降維處理
#%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 從sklearn.decomposition導入PCA
from sklearn.decomposition import PCA
# 從sklearn.cluster中導入KMeans模型
from sklearn.cluster import KMeans
# 從sklearn導入度量函數(shù)庫metrics
from sklearn import metrics
# 使用pandas分別讀取訓練數(shù)據(jù)與測試數(shù)據(jù)集
digits_train = pd.read_csv('data/optdigits_train.csv', header=None)
digits_test = pd.read_csv('data/optdigits_test.csv', header=None)
# 分割訓練數(shù)據(jù)的特征向量和標記峡谊。
X_digits = digits_train[np.arange(64)]
y_digits = digits_train[64]
# 初始化一個可以將高維度特征向量(64維)壓縮至2個維度的PCA
estimator = PCA(n_components=2)
X_pca = estimator.fit_transform(X_digits)
def plot_pca_scatter():
colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray']
plt.figure(figsize=(12, 8))
for i in range(len(colors)):
px = X_pca[:, 0][y_digits.values == i]
py = X_pca[:, 1][y_digits.values == i]
plt.scatter(px, py, c=colors[i])
plt.legend(np.arange(0,10).astype(str))
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
plt.show()
plot_pca_scatter()
"""
print(X_pca.shape)
from mpl_toolkits.mplot3d import Axes3D
def plot_pca_scatter():
colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray']
fig = plt.figure(figsize=(12, 8))
ax = Axes3D(fig)
for i in range(len(colors)):
px = X_pca[:, 0][y_digits.values == i]
py = X_pca[:, 1][y_digits.values == i]
pz = X_pca[:, 2][y_digits.values == i]
ax.scatter(px, py, pz, c=colors[i])
ax.legend(np.arange(0,10).astype(str))
ax.set_xlabel('First Principal Component')
ax.set_ylabel('Second Principal Component')
ax.set_zlabel('Third Principal Component')
ax.view_init(elev=10,azim=235)
plt.show()
plot_pca_scatter()
"""
壓縮到2個維度
壓縮到3個維度
降維再進行模型訓練
使用PCA將原64維的圖像數(shù)據(jù)壓縮到20個維度
對壓縮過后的20維特征的訓練數(shù)據(jù)進行建模,并在測試數(shù)據(jù)上做出預測
# 導入基于線性核的支持向量機分類器
from sklearn.svm import LinearSVC
# 從sklearn.metrics導入classification_report用于更加細致的分類性能分析
from sklearn.metrics import classification_report
# 使用pandas分別讀取訓練數(shù)據(jù)與測試數(shù)據(jù)集
digits_train = pd.read_csv('data/optdigits_train.csv', header=None)
digits_test = pd.read_csv('data/optdigits_test.csv', header=None)
# 對訓練數(shù)據(jù)、測試數(shù)據(jù)進行特征向量(圖片像素)與分類目標的分隔
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]
X_test = digits_test[np.arange(64)]
y_test = digits_test[64]
print(X_test.shape)
# 使用默認配置初始化LinearSVC既们,對原始64維像素特征的訓練數(shù)據(jù)進行建模濒析,并在測試數(shù)據(jù)上做出預測,存儲在y_predict中
svc = LinearSVC()
svc.fit(X_train, y_train)
y_predict = svc.predict(X_test)
# 使用PCA將原64維的圖像數(shù)據(jù)壓縮到20個維度
estimator = PCA(n_components=20)
# 利用訓練特征決定(fit)20個正交維度的方向啥纸,并轉化(transform)原訓練特征
pca_X_train = estimator.fit_transform(X_train)
# 測試特征也按照上述的20個正交維度方向進行轉化(transform)
pca_X_test = estimator.transform(X_test)
# 使用默認配置初始化LinearSVC号杏,對壓縮過后的20維特征的訓練數(shù)據(jù)進行建模,并在測試數(shù)據(jù)上做出預測斯棒,存儲在pca_y_predict中
pca_svc = LinearSVC()
pca_svc.fit(pca_X_train, y_train)
pca_y_predict = pca_svc.predict(pca_X_test)
# 對使用原始圖像高維像素特征訓練的支持向量機分類器的性能作出評估
print(svc.score(X_test, y_test))
print(classification_report(y_test, y_predict, target_names=np.arange(10).astype(str)))
# 對使用PCA壓縮重建的低維圖像特征訓練的支持向量機分類器的性能作出評估
print(pca_svc.score(pca_X_test, y_test))
print(classification_report(y_test, pca_y_predict, target_names=np.arange(10).astype(str)))
image.png