本关任务
本关综合前面四个关卡的内容来实现K-means聚类算法。
相关说明
K-means是一类非常经典的无监督机器学习算法,通常在实际应用中用于从数据集中找出不同样本的聚集模式,其基本原理就是类中样本的距离要远远小于类间样本的距离。
K-means聚类算法的流程如下: 首先从数据集x1,x2,x3,…,xn中随机选择k个样本作为簇中心C=(C1,C2,…,Ck)。 然后,进入T轮迭代,在每个迭代中执行以下两个步骤。
一、对于每个样本 xi,计算距离其最近的簇中心yˉi=argmini dist(xi,Cj)
二、对于每一个簇j,重新计算其簇中心
yˉj=∑iI(yˉi=j)∑iI(yˉi=j)xi
其含义实际上就是对于每一个簇j,计算分配在其中的样本向量的平均值。
编程任务
本关卡要求你完整如下代码块中星号圈出来的区域,实现K-means的核心算法步骤:
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from distance import euclid_distance
from estimate import estimate_centers
from loss import acc
from near import nearest_cluster_center
#随机种子对聚类的效果会有影响,为了便于测试,固定随机数种子
np.random.seed(5)
#读入数据集
dataset = pd.read_csv('./data/iris.csv')
#取得样本特征矩阵
X = dataset[['150','4','setosa','versicolor']].as_matrix()
y = np.array(dataset['virginica'])
#读入数据
n_clusters, n_iteration = input().split(',')
n_clusters = int(n_clusters)#聚类中心个数
n_iteration = int(n_iteration)#迭代次数
#随机选择若干点作为聚类中心
point_index_lst = np.arange(len(y))
np.random.shuffle(point_index_lst)
cluster_centers = X[point_index_lst[:n_clusters]]
#开始算法流程
y_estimated = np.zeros(len(y))
# 请在此添加实现代码 #
#********** Begin *********#
#********** End ***********#
print('%.3f' % acc(y_estimated, y))
代码:
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from distance import euclid_distance
from estimate import estimate_centers
from loss import acc
from near import nearest_cluster_center
#随机种子对聚类的效果会有影响,为了便于测试,固定随机数种子
np.random.seed(5)
#读入数据集
dataset = pd.read_csv('./data/iris.csv')
#取得样本特征矩阵
X = dataset[['150','4','setosa','versicolor']].as_matrix()
y = np.array(dataset['virginica'])
#读入数据
n_clusters, n_iteration = input().split(',')
n_clusters = int(n_clusters)#聚类中心个数
n_iteration = int(n_iteration)#迭代次数
#随机选择若干点作为聚类中心
point_index_lst = np.arange(len(y))
np.random.shuffle(point_index_lst)
cluster_centers = X[point_index_lst[:n_clusters]]
#开始算法流程
y_estimated = np.zeros(len(y))
# 请在此添加实现代码 #
#********** Begin *********#
for iter in range(n_iteration):for xx_index in range(len(X)):#计算各个点最接近的聚类中心y_estimated[xx_index] = nearest_cluster_center(X[xx_index], cluster_centers)#计算各个聚类中心cluster_centers = estimate_centers(X, y_estimated, n_clusters)
#********** End ***********#
print('%.3f' % acc(y_estimated, y))