機器學習實踐六---K-means聚類算法 和 主成分分析(PCA)

在這次練習中將實現K-means 聚類算法并應用它壓縮圖片,第二部分,將使用主成分分析算法去找到一個臉部圖片的低維描述。

K-means Clustering

Implementing K-means

K-means算法是一種自動將相似的數據樣本聚在一起的方法,K-means背后的直觀是一個迭代過程,它從猜測初始的質心開始,然后通過重復地將示例分配到最接近的質心,然后根據分配重新計算質心,來細化這個猜測。
具體步驟:

  1. 隨機初始K個質心
  2. 開始迭代
  3. 為每個樣本找到最近的質心
  4. 用分配給每個質心的點來計算每個質心的平均值,作為新的質心
  5. 回到三
  6. 收斂于最終的均值集
    在實踐中,K-means算法通常使用不同的隨機初始化運行幾次。從不同的隨機初始化中選擇不同的解的一種方法是選擇成本函數值(失真)最低的解。
Finding closest centroids

在這里插入圖片描述

Computing centroid means

for every centroid k we set
在這里插入圖片描述
新的形心重置為所有聚集該形心和的平均值

K-means on example dataset

def find_closest_centroids(X, centroids):idx = np.zeros((len(X), 1))print(idx.shape)K = len(centroids)print(K)t = [0 for i in range(K)]print(t)for i in range(len(X)):for j in range(K):temp = centroids[j, :] - X[i, :]t[j] = temp.dot(temp.T)index = t.index(min(t)) + 1print(index)idx[i] = indexreturn np.array(idx)
mat = loadmat("ex7data2.mat")
X = mat['X']
init_centroids = np.array([[3, 3], [6, 2], [8, 5]])
idx = find_closest_centroids(X, init_centroids)
print(idx[0:3])

計算出聚集樣本的平均數,得到新的centroids

def compute_centroids(X, idx):centroids = []# print(idx)K = len(np.unique(idx))m, n = X.shapecentroids = np.zeros((K, n))temp = np.zeros((K, n))count = np.zeros((K, 1))print(temp.shape)print(count.shape)for i in range(m):for j in range(K):if idx[i] == j:temp[j, :] = temp[j, :] + X[i, :]count[j] = count[j] + 1centroids = temp/countreturn centroids

繪制聚類過程

def plotData(X, centroids, idx=None):"""可視化數據,并自動分開著色。idx: 最后一次迭代生成的idx向量,存儲每個樣本分配的簇中心點的值centroids: 包含每次中心點歷史記錄"""colors = ['b', 'g', 'gold', 'darkorange', 'salmon', 'olivedrab','maroon', 'navy', 'sienna', 'tomato', 'lightgray', 'gainsboro''coral', 'aliceblue', 'dimgray', 'mintcream','mintcream']assert len(centroids[0]) <= len(colors), 'colors not enough 'subX = []  # 分號類的樣本點if idx is not None:for i in range(centroids[0].shape[0]):x_i = X[idx[:, 0] == i]subX.append(x_i)else:subX = [X]  # 將X轉化為一個元素的列表,每個元素為每個簇的樣本集,方便下方繪圖# 分別畫出每個簇的點,并著不同的顏色plt.figure(figsize=(8, 5))for i in range(len(subX)):xx = subX[i]plt.scatter(xx[:, 0], xx[:, 1], c=colors[i], label='Cluster %d' % i)plt.legend()plt.grid(True)plt.xlabel('x1', fontsize=14)plt.ylabel('x2', fontsize=14)plt.title('Plot of X Points', fontsize=16)# 畫出簇中心點的移動軌跡xx, yy = [], []for centroid in centroids:xx.append(centroid[:, 0])yy.append(centroid[:, 1])plt.plot(xx, yy, 'rx--', markersize=8)plotData(X, [init_centroids])
plt.show()
def run_k_means(X, centroids, max_iters):K = len(centroids)centroids_all = []centroids_all.append(centroids)centroid_i = centroidsfor i in range(max_iters):idx = find_closest_centroids(X, centroid_i)centroid_i = compute_centroids(X, idx)centroids_all.append(centroid_i)return idx, centroids_allidx, centroids_all = run_k_means(X, init_centroids, 20)
plotData(X, centroids_all, idx)
plt.show()

Random initialization

  1. 洗牌所有數據
  2. 取前k個作為centroids
    隨機選取K個樣本作為centroids
def initCentroids(X, K):m, n = X.shapeidx = np.random.choice(m, K)centroids = X[idx]return centroids
for i in range(K):centroids = initCentroids(X, K)idx, centroids_all = run_k_means(X, centroids, 10)plotData(X, centroids_all, idx)

Image compression with K-means

讀入圖片,128*128 RGB編碼圖片

from skimage import ioA = io.imread('bird_small.png')
print(A.shape)
plt.imshow(A)
A = A/255.
K-means on pixels
X = A.reshape(-1, 3)
K = 16
centroids = initCentroids(X, K)
idx, centroids_all = run_k_means(X, centroids, 10)img = np.zeros(X.shape)
centroids = centroids_all[-1]
for i in range(len(centroids)):img[idx == i] = centroids[i]img = img.reshape((128, 128, 3))fig, axes = plt.subplots(1, 2, figsize=(12, 6))
axes[0].imshow(A)
axes[1].imshow(img)

Principal Component Analysis

Example Dataset

mat = loadmat('ex7data1.mat')
X = mat['X']
print(X.shape)
plt.scatter(X[:,0], X[:,1], facecolors='none', edgecolors='b')
plt.show()

Implementing PCA

兩個步驟:

  1. 計算矩陣數據的協方差
  2. 使用SVD 方法得出特征向量
    使用歸一化是每個特征在同一范圍內。
def feature_normalize(X):means = X.mean(axis=0)stds = X.std(axis=0, ddof=1)X_norm = (X - means) / stdsreturn X_norm, means, stds
def pca(X):sigma = (X.T @ X) / len(X)U, S, V = np.linalg.svd(sigma)return U, S, V
X_norm, means, stds = feature_normalize(X)
U, S, V = pca(X_norm)
print(U[:,0])
plt.figure(figsize=(7, 5))
plt.scatter(X[:,0], X[:,1], facecolors='none', edgecolors='b')plt.plot([means[0], means[0] + 1.5*S[0]*U[0,0]],[means[1], means[1] + 1.5*S[0]*U[0,1]],c='r', linewidth=3, label='First Principal Component')
plt.plot([means[0], means[0] + 1.5*S[1]*U[1,0]],[means[1], means[1] + 1.5*S[1]*U[1,1]],c='g', linewidth=3, label='Second Principal Component')
plt.grid()
plt.axis("equal")
plt.legend()

Dimensionality Reduction with PCA

Projecting the data onto the principal components
def project_data(X, U, K):Z = X @ U[:, :K]return Z
def recover_data(Z, U, K):X_rec = Z @ U[:, :K].Treturn X_rec
Reconstructing an approximation of the data
X_rec = recover_data(Z, U, 1)
X_rec[0]
Visualizing the projections
plt.figure(figsize=(7,5))
plt.axis("equal")
plot = plt.scatter(X_norm[:,0], X_norm[:,1], s=30, facecolors='none',edgecolors='b',label='Original Data Points')
plot = plt.scatter(X_rec[:,0], X_rec[:,1], s=30, facecolors='none',edgecolors='r',label='PCA Reduced Data Points')plt.title("Example Dataset: Reduced Dimension Points Shown",fontsize=14)
plt.xlabel('x1 [Feature Normalized]',fontsize=14)
plt.ylabel('x2 [Feature Normalized]',fontsize=14)
plt.grid(True)for x in range(X_norm.shape[0]):plt.plot([X_norm[x,0],X_rec[x,0]],[X_norm[x,1],X_rec[x,1]],'k--')# 輸入第一項全是X坐標,第二項都是Y坐標
plt.legend()

Face Image Dataset

mat = loadmat('ex7faces.mat')
X = mat['X']
print(X.shape)
def display_data(X, row, col):fig, axs = plt.subplots(row, col, figsize=(8, 8))for r in range(row):for c in range(col):axs[r][c].imshow(X[r * col + c].reshape(32, 32).T, cmap='Greys_r')axs[r][c].set_xticks([])axs[r][c].set_yticks([])display_data(X, 10, 10)
PCA on Faces
X_norm, means, stds = feature_normalize(X)
U, S, V = pca(X_norm)
display_data(U[:,:36].T, 6, 6)
Dimensionality Reduction
z = project_data(X_norm, U, K=36)
X_rec = recover_data(z, U, K=36)
display_data(X_rec, 10, 10)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388930.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388930.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388930.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

航海家軟件公式全破解

水手突破 上趨勢:MA(LOW,20)*1.2,color0080ff,linethick2;次上趨勢:MA(LOW,20)*1.1,COLORYELLOW;次下趨勢:MA(HIGH,20)*0.9,COLORWHITE;下趨勢:MA(HIGH,20)*0.8,COLORGREEN,linethick2;ZD:(C-REF(C,1))/REF(C,1)*100;HDZF:(HHV(H,20)-C)/(HHV(H,20)-LLV(L,20));趨勢強度:IF(C&g…

打包 壓縮 命令tar zip

2019獨角獸企業重金招聘Python工程師標準>>> 打包 壓縮 命令tar zip tar語法 #壓縮 tar -czvf ***.tar.gz tar -cjvf ***.tar.bz2 #解壓縮 tar -xzvf ***.tar.gz tar -xjvf ***.tar.bz2 tar [主選項輔選項] 文件或目錄 主選項是必須要有的&#xff0c;它告訴tar要做…

mysql免安裝5.7.17_mysql免安裝5.7.17數據庫配置

首先要有 mysql-5.7.10-winx64環境: mysql-5.7.10-winx64 win10(64位)配置環境變量&#xff1a;1、把mysql-5.7.10-winx64放到D盤&#xff0c;進入D\mysql-5.7.10-winx64\bin目錄&#xff0c;復制路徑&#xff0c;配置環境變量&#xff0c;在path后面添加D\mysql-5.7.10-winx6…

tidb數據庫_異構數據庫復制到TiDB

tidb數據庫This article is based on a talk given by Tianshuang Qin at TiDB DevCon 2020.本文基于Tianshuang Qin在 TiDB DevCon 2020 上的演講 。 When we convert from a standalone system to a distributed one, one of the challenges is migrating the database. We’…

機器學習實踐七----異常檢測和推薦系統

Anomaly detection 異常檢測是機器學習中比較常見的應用&#xff0c;它主要用于非監督學習問題&#xff0c;從某些角度看&#xff0c; 它又類似于一些監督學習問題。 什么是異常檢測&#xff1f;來看幾個例子&#xff1a; 例1. 假設是飛機引擎制造商&#xff0c; 要對引擎進行…

CODE[VS] 1621 混合牛奶 USACO

題目描述 Description牛奶包裝是一個如此低利潤的生意,所以盡可能低的控制初級產品(牛奶)的價格變的十分重要.請幫助快樂的牛奶制造者(Merry Milk Makers)以可能的最廉價的方式取得他們所需的牛奶.快樂的牛奶制造公司從一些農民那購買牛奶,每個農民賣給牛奶制造公司的價格不一定…

apply和call用法

apply語法 func.apply(name, [array])第一個參數指定函數體內this對象的指向&#xff0e;第二個參數為一個帶下標的集合&#xff0c;可以是數組或類數組,apply方法把這個集合中的元素作為參數傳遞給被調用的函數var func function(a, b, c) {console.log([a, b, c]); // [1,2,…

剛認識女孩說不要浪費時間_不要浪費時間尋找學習數據科學的最佳方法

剛認識女孩說不要浪費時間重點 (Top highlight)Data science train is moving, at a constantly accelerating speed, and increasing its length by adding up new coaches. Businesses want to be on the data science train to keep up with the ever-evolving technology a…

測試工具之badboy

badboy這個工具本身用處不是很大&#xff0c;但有個錄制腳本的功能&#xff0c;還是jmeter腳本&#xff0c;所以針對這一點很多懶人就可以通過這個錄制腳本&#xff0c;而不需要自己去編寫 badboy工具最近還是2016年更新的&#xff0c;后面也沒在更新了&#xff0c;官方下載地址…

hive 集成sentry

2019獨角獸企業重金招聘Python工程師標準>>> 環境 apache-hive-2.3.3-bin apache-sentry-2.1.0-bin 1 2 sentry是目前最新的版本&#xff0c;支持hive的最高版本為2.3.3&#xff0c;hive版本如果高于2.3.3&#xff0c;會出一些版本兼容問題[親測] hive快速安裝 wget…

word模板生成word報表文檔

主要功能為根據word模板生成word報表文檔,注意引用Interop.Word.dll;首先要生成word程序對象Word.Application app new Word.Application();根據模板文件生成新文件框架File.Copy(TemplateFile, FileName);生成documnet對象ord.Document doc new Word.Document(); 打開…

isql 測試mysql連接_[libco] 協程庫學習,測試連接 mysql

歷史原因&#xff0c;一直使用 libev 作為服務底層&#xff1b;異步框架雖然性能比較高&#xff0c;但新人學習和使用門檻非常高&#xff0c;而且串行的邏輯被打散為狀態機&#xff0c;這也會嚴重影響生產效率。用同步方式實現異步功能&#xff0c;既保證了異步性能優勢&#x…

什么是數據倉庫,何時以及為什么要考慮一個

The term “Data Warehouse” is widely used in the data analytics world, however, it’s quite common for people who are new with data analytics to ask the above question.術語“數據倉庫”在數據分析領域中被廣泛使用&#xff0c;但是&#xff0c;對于數據分析新手來…

安裝好MongoDB,但服務中沒有MongoDB服務的解決辦法

以管理員身份打開CMD&#xff0c;添加路徑添加服務即可 winX 然后再選Amongod -dbpath "D:\MongoDB\Server\3.6\data\db" -logpath "D:\MongoDB\Server\3.6\data\log\mongo.log" -install -serviceName "MongoDB"轉載于:https://www.cnblogs.com…

DRF數據驗證+數據存儲

1.驗證數據的自定義類 class BooksDRFt(serializers.ModelSerializer):class Meta:model Bookfields __all__#要驗證的字段author serializers.CharField(requiredFalse)#要驗證的字段name serializers.CharField(min_length2, error_messages{required: 不能為空, min_len…

mysql變量 exec_MySQL slave_exec_mode 參數說明

背景&#xff1a;今天無意當中看到參數slave_exec_mode&#xff0c;從手冊里的說明看出該參數和MySQL復制相關&#xff0c;是可以動態修改的變量&#xff0c;默認是STRICT模式(嚴格模式)&#xff0c;可選值有IDEMPOTENT模式(冪等模式)。設置成IDEMPOTENT模式可以讓從庫避免1032…

C#word

主要功能為根據word模板生成word報表文檔,注意引用Interop.Word.dll;首先要生成word程序對象Word.Application app new Word.Application();根據模板文件生成新文件框架File.Copy(TemplateFile, FileName);生成documnet對象ord.Document doc new Word.Document(); 打開…

機器學習kaggle競賽實戰-泰坦尼克號

數據展示 首先登kaggle 下載泰坦尼克訓練相關數據 import pandas as pd import numpy as np data pd.read_csv(train.csv) print(data.shape) print(data.head) train data[:800] test data[800:] print(train.shape) print(test.shape)選擇特征 selected_features [Pcl…

上海大都會 H.A Simple Problem with Integers

題目描述 You have N integers A1, A2, ... , AN. You are asked to write a program to receive and execute two kinds of instructions: C a b means performing Ai (Ai2 mod 2018) for all Ai such that a ≤ i ≤ b.Q a b means query the sum of Aa, Aa1, ..., Ab. Note…

探索性數據分析入門_入門指南:R中的探索性數據分析

探索性數據分析入門When I started on my journey to learn data science, I read through multiple articles that stressed the importance of understanding your data. It didn’t make sense to me. I was naive enough to think that we are handed over data which we p…