Machine-Learning 编程作业
Programming Exercise 7:Kmeans and PCA
Part1 . K-means 聚类
Part2. K-means 算法对图片降维
Part3. 调用Sklearn库实现K-means算法
Part4. PCA算法对二维数据进行降维
Part5. PCA算法对图像进行降维处理
K-means 聚类
算法思想:以空间中K个点为中心进行聚类,对最靠近他们的对象归为相同类。然后通过迭代的方法逐次更新各聚类中心的值,直至得到最好的聚类结果。
算法描述:
- 适当选择K个初始中心点;
- 在第n次迭代中,对任意一个样本,求其到K个中心的距离,将该样本归到距离最关的中心所在的类;
- 利用均值等方法更新该类的中心值;
- 对于所有的K各聚类中心,如果利用(2),(3)的迭代方法更新后值保持不变时,或迭代一定次数之后,结束迭代,输出结果。
导入数据可视化
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
data = loadmat('data/ex7data2')
X = data['X']
data2 = pd.DataFrame(data['X'], columns=['X1', 'X2'])
print(data2.head())
fig, ax = plt.subplots(figsize=(6,4))#定义图的大小
ax.scatter(data2['X1'],data2['X2'] , s=5, c='b', marker='o', label='Examples')
ax.legend()#在图形中加入颜色不同的备注
ax.set_xlabel('X1')
ax.set_ylabel('X2')
plt.show()
结果如下:
定义初始聚类中心,归类,并迭代
#方法1: 人为规定初始聚类中心
# initial_center = np.array([[3, 3], [6, 2], [8, 5]])
#方法2: 随机初始化聚类中心
def init_center(X, k):
m, n = X.shape
center = np.zeros((k, n))
idx = np.random.randint(0, m, k)
for i in range(k):
center[i, :] = X[idx[i], :]
return center
initial_center = init_center(X, 3)
#对所有样本求出其所属的类
def find_center(X, center):
m = X.shape[0]
k = center.shape[0]
idx = np.zeros(m)
for i in range(m):
mdis = 10000
for j in range(k):
dist = np.sum((X[i, :] - center[j, :]) ** 2 )
if dist < mdis:
mdis = dist
idx[i] = j
return idx #存储m个样本对应的最近的聚类中心序号
idx = find_center(X, initial_center)
print(idx[0:5])
#对已分好的类,利用均值更新该类的中心点
def compute_center(X, idx, k):
m, n = X.shape
center = np.zeros((k, n))
for i in range(k):
#第一种
# indices = np.where(idx == i) #输出满足条件元素的坐标
# center[i, :] = (np.sum(X[indices, :], axis=1) / len(indices[0])).ravel()
#第二种
center[i] = np.mean(X[idx == i], axis=0) #对每一簇,计算新的聚类中心 axis=0对每一列求均值
return center
print(compute_center(X, idx, 3))
#迭代算法
def run_k_means(X, initial_centroids, max_iters):
m, n = X.shape
k = initial_centroids.shape[0]
idx = np.zeros(m)
centroids = initial_centroids
for i in range(max_iters):
idx = find_center(X, centroids)
centroids = compute_center(X, idx, k)
return idx, centroids
idx, center = run_k_means(X, initial_center, 10)
可视化最终迭代结果
#画图
cluster1 = X[np.where(idx == 0)[0],:]
cluster2 = X[np.where(idx == 1)[0],:]
cluster3 = X[np.where(idx == 2)[0],:]
fig, ax = plt.subplots(figsize=(6,4))
ax.scatter(cluster1[:,0], cluster1[:,1], s=5, color='r', label='Cluster 1')
ax.scatter(cluster2[:,0], cluster2[:,1], s=5, color='g', label='Cluster 2')
ax.scatter(cluster3[:,0], cluster3[:,1], s=5, color='b', label='Cluster 3')
ax.legend()
plt.show()
结果如下:
K-means 算法对图片降维
方法流程几乎和上面相同,只需对数据进行些许处理。代码如下:
读取图片并显示
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
from skimage import io
import cv2 as cv
from PIL import Image
#方法一: 读取图片并显示,cv读的不能画在工作窗
# img = cv.imread('data/bird_small.png')
# img = cv.resize(img, (400,400))
# cv.imshow('image', img)
# cv.waitKey(100)
# 方法二:用skimage库的io读取,会有看不懂的警告,但不影响
# pic = io.imread('data/bird_small.png')
# io.imshow(pic)
# plt.title('Original')
# plt.show()
#方法三: 这里用cv读进来plt画出来后是3通道颠倒了,所以不用cv读,并且这个可以显示在工作窗
img = Image.open('data/bird_small.png')
plt.imshow(img)
plt.title('Original')
plt.show()
结果如图:
运行K-means算法将,定义16个聚类中心点,相当于将彩色图片降维到16维。
data = loadmat('data/bird_small.mat')
# print(data)
A = data['A']
print(A.shape)
# 标准化取值范围
A = A / 255.
# 将A中的像素重组形状便于运算
X = np.reshape(A, (A.shape[0] * A.shape[1], A.shape[2]))
print(X.shape)
#随机初始化聚类中心
def init_center(X, k):
m, n = X.shape
center = np.zeros((k, n))
idx = np.random.randint(0, m, k)
for i in range(k):
center[i, :] = X[idx[i], :]
return center
#找出所有样本点对应的最近的聚类中心序号
def find_center(X, center):
m = X.shape[0]
k = center.shape[0]
idx = np.zeros(m)
for i in range(m):
mdis = 10000
for j in range(k):
dist = np.sum((X[i, :] - center[j, :]) ** 2 )
if dist < mdis:
mdis = dist
idx[i] = j
return idx #存储m个样本对应的最近的聚类中心序号
#重新计算中心点
def compute_center(X, idx, k):
m, n = X.shape
center = np.zeros((k, n))
for i in range(k):
#第一种
# indices = np.where(idx == i) #输出满足条件元素的坐标
# center[i, :] = (np.sum(X[indices, :], axis=1) / len(indices[0])).ravel()
#第二种
center[i] = np.mean(X[idx == i], axis=0) #对每一簇,计算新的聚类中心 axis=0对每一列求均值
return center
#运行K—means算法
def run_k_means(X, initial_centroids, max_iters):
m, n = X.shape
k = initial_centroids.shape[0]
idx = np.zeros(m)
centroids = initial_centroids
for i in range(max_iters):
idx = find_center(X, centroids)
centroids = compute_center(X, idx, k)
return idx, centroids
# 随机初始化聚类中心点
initial_center = init_center(X, 16)
#运行迭代
idx, center = run_k_means(X, initial_center, 10)
idx = find_center(X, center)
newX = center[idx.astype(int),:]
print(newX.shape)
可视化迭代后的结果:
#重组成图片形式
newX = np.reshape(newX, (A.shape[0], A.shape[1], A.shape[2]))
print(newX)
plt.imshow(newX)
plt.show()
最终结果如图:
根据降维结果可以看出,虽然我们舍弃了部分数据,但图像的主要特征仍然存在。
调用Sklearn库实现K-means算法
这个比较简单,只需调用函数,并设置相关参数即可,参数详情可以自行百度了解K-means函数的参数设置。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage import io
from sklearn.cluster import KMeans#导入kmeans库
image = io.imread('data/bird_small.png') / 255.
print(image.shape)
# io.imshow(image)
# plt.show()
#将像素矩阵重组,便于计算
data = image.reshape(128*128, 3)
print(data.shape)
#直接调用K-means算法,参数设置详见k-means函数
model = KMeans(n_clusters=16, n_init=10)
model.fit(data)
center = model.cluster_centers_
print(center.shape)
C = model.predict(data)
print(C.shape)
print(center[C].shape)
c_img = center[C].reshape((128,128,3))
#画图直观比较一下
fig, ax = plt.subplots(1, 2)
ax[0].imshow(image)
ax[1].imshow(c_img)
plt.show()
结果如下:
左边为原始图像,右边为调用K-means函数降维后的结果。
PCA算法对二维数据进行降维
该练习基于给出的二维数据,利用PCA算法,将其降维到一维并加以显示。
读取数据并显示
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
data = loadmat('data/ex7data1.mat')
print(data)
X = data['X']
fig, ax = plt.subplots(figsize=(6,4))
ax.scatter(X[:, 0], X[:, 1], s=5)
plt.show()
显示结果:
定义PCA函数,输出降维结果
def pca(X):
# 特征归一化
X = (X - X.mean()) / X.std()
# 计算协方差矩阵
X = np.matrix(X)
cov = (X.T * X) / X.shape[0]
U, S, V = np.linalg.svd(cov)
return U, S, V
U, S, V = pca(X)
print(U, S, V)
#利用已经得到的主成分U,计算投影矩阵,并可选保留顶部K个分量
def project_data(X, U, k):
U_reduced = U[:,:k]
return np.dot(X, U_reduced)
Z = project_data(X, U, 1)
print(Z)
将降维后的数据还原并显示
def recover_data(Z, U, k):
U_reduced = U[:,:k]
return np.dot(Z, U_reduced.T)
X_new = recover_data(Z, U, 1)
print(X_new)
fig, ax = plt.subplots(figsize=(12,8))
ax.scatter(list(X_new[:, 0]), list(X_new[:, 1]))
plt.show()
输出结果如下:
PCA算法对图像进行降维处理
给出的数据集包括5000张人脸图像,每张图像的大小为3232,每一张图像的像素存储为1024维数值,数据集维度为 50001024。我们可视化的时候选取钱100张图像就行。
读取数据,可视化
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
faces = loadmat('data/ex7faces.mat')
X = faces['X']
print(X.shape)
#定义可视化函数,n为传入的显示图片的数量
def plot_n_image(X, n):
""" plot first n images
n has to be a square number
"""
pic_size = int(np.sqrt(X.shape[1]))
grid_size = int(np.sqrt(n))
first_n_images = X[:n, :]
fig, ax_array = plt.subplots(nrows=grid_size, ncols=grid_size,
sharey=True, sharex=True, figsize=(8, 8))
for r in range(grid_size):
for c in range(grid_size):
ax_array[r, c].imshow(first_n_images[grid_size * r + c].reshape((32, 32)))
plt.yticks(np.array([]))
plt.xticks(np.array([]))
#显示前100张图像
plot_n_image(X, 100)
plt.show()
输出结果如下:
定义PCA函数,输出降维结果并可视化
这部分与Part4 练习中的代码基本相同。
def pca(X):
# 特征归一化
X = (X - X.mean()) / X.std()
# 计算协方差矩阵
X = np.matrix(X)
cov = (X.T * X) / X.shape[0]
U, S, V = np.linalg.svd(cov)
return U, S, V
def project_data(X, U, k):
U_reduced = U[:,:k]
return np.dot(X, U_reduced)
def recover_data(Z, U, k):
U_reduced = U[:,:k]
return np.dot(Z, U_reduced.T)
U, S, V = pca(X)
Z = project_data(X, U, 100)
X_recovered = recover_data(Z, U, 100)
plot_n_image(X_recovered, 100)
# face = np.reshape(X_recovered[3,:], (32, 32))
# plt.imshow(face)
plt.show()
最终降维结果如下:
可以看到虽然丢失了一些细节,但整体特征大致保持不变。这种的也就适合用于 人脸识别了吧,保留整体特性不变。对于表情识别的话,丢失的这些细节肯定会对结果有影响。
如上实验,可以看到我们读入的.mat文件画出来的是热量图,就是整体泛绿,并不是我们期待中的灰度图,这是因为图像的存储方式可能与 cv库读取的方式是相同的,用plt函数画出来的图他们的通道不同,要解决这个问题,我们只需在其中一行代码中添加一个参数即可,如下:
将 plot_n_image 函数的其中一行代码
ax_array[r, c].imshow(first_n_images[grid_size * r + c].reshape((32, 32)))
改为
ax_array[r, c].imshow(first_n_images[grid_size * r + c].reshape((32, 32)),cmap='Greys_r')
即可,这里’Greys_r’表示灰度图。结果如下图:
原图:
PCA降维后的图: