在本练习中,您将实现K-means算法并将其用于图像压缩。
- 您将从一个样本数据集开始,该数据集将帮助您直观地了解K-means算法的工作原理。
- 之后,您将使用K-means算法进行图像压缩,将图像中出现的颜色数量减少到该图像中最常见的颜色。
文章目录
import numpy as np
import matplotlib.pyplot as plt
from utils import *
%matplotlib inline
1-实现K-means
K-means算法是一种自动将相似数据点聚类在一起的方法。
- 具体来说,你会得到一套训练{𝑥1,……,𝑥(𝑚)},并且您希望将数据分组为几个有凝聚力的“集群”。
- K-means是一个迭代过程
- 首先猜测初始质心,然后
- 通过优化此猜测
- 反复将示例指定给它们最近的质心
- 根据指定重新计算质心。
在伪码中,K-means算法如下:
# Initialize centroids
# K is the number of clusters
#初始化质心
#K是簇的数量
centroids = kMeans_init_centroids(X, K)
for iter in range(iterations):
# Cluster assignment step:
# Assign each data point to the closest centroid.
# idx[i] corresponds to the index of the centroid
# assigned to example i
#群集分配步骤:
#将每个数据点指定给最近的质心。
#idx[i]对应于质心的索引
#分配给示例i
idx = find_closest_centroids(X, centroids)
# Move centroid step:
# Compute means based on centroid assignments
#移动质心步长:
#基于质心分配计算均值
centroids = compute_means(X, idx, K)
- 算法的内部循环重复执行两个步骤:
- (i) 分配每个训练示例𝑥(𝑖) 以及
- (ii)使用分配给每个质心的点重新计算每个质心的平均值。
- 这个𝐾-均值算法将总是收敛到质心的某个最终均值集。
- 然而,收敛解可能并不总是理想的,并且取决于质心的初始设置。
- 因此,在实践中,K-means算法通常在不同的随机初始化下运行几次。
- 从不同的随机初始化中在这些不同的解决方案之间进行选择的一种方法是选择具有最低成本函数值(失真)的解决方案。
在接下来的部分中,您将分别实现K-means
算法的两个阶段。
- 您将从完成
find_closest_centroid
开始,然后继续完成compute_centroids
。
1.1寻找最接近的质心
在K-means算法的“聚类分配”阶段,该算法分配每个训练示例𝑥(𝑖)到其最近的质心,给定质心的当前位置。
练习1
您的任务是完成find_closest_centroids
中的代码。
- 此函数获取数据矩阵X和质心内所有质心的位置。
- 它应该输出一个一维数组idx(与X具有相同数量的元素),该数组保存最近质心的索引({1,…,𝐾},𝐾是质心的总数)。
- 具体来说,对于每个例子𝑥(𝑖) 我们设置
𝑐^(i)
是最接近于其的质心的索引(对应于起始代码中的idx[i]),- 而u𝑗是𝑗的第一个质心的位置(值)。(存储在启动代码中的质心中)
如果你遇到了困难,你可以查看下面单元格后呈现的提示,以帮助你实现。
正确答案👇
def find_closest_centroids(X, centroids):
# Set K
K = centroids.shape[0]
# You need to return the following variables correctly
idx = np.zeros(X.shape[0], dtype=int)
### START CODE HERE ###
for i in range(X.shape[0]):
# Array to hold distance between X[i] and each centroids[j]
distance = []
for j in range(centroids.shape[0]):
norm_ij = np.linalg.norm(X[i]-centroids[j])
distance.append(norm_ij)
idx[i] = np.argmin(distance)
### END CODE HERE ###
return idx
自己写的答案👇
# UNQ_C1
# GRADED FUNCTION: find_closest_centroids
def find_closest_centroids(X, centroids):
"""
Computes the centroid memberships for every example
Args:
X (ndarray): (m, n) Input values
centroids (ndarray): k centroids
Returns:
idx (array_like): (m,) closest centroids
"""
# Set K
K = centroids.shape[0]
# You need to return the following variables correctly
idx = np.zeros(X.shape[0