无监督--聚类算法
聚类算法
概述: 训练数据不存在类别标签信息,而且我们又需要根据数据特征将数据分成不同的类别, 聚类有时也被分为无监督分类,
和监督分类区别在于,聚类的训练数据没有对应的y值,而监督算法的数据有对应y值。
经典算法:K-均值聚类
K-均值聚类算法
优点:容易实现;
缺点:可能收敛到局部最小值,在大规模数据集上收敛较慢
适用数据类型: 数值型数据
思想:给定数据集k个簇的算法,簇的个数由用户给定,每个簇通过其质心,即簇中所有点的中心描述。
1、随机确定k个初始点作为质心;
2、为数据集中的每一个点找其最近的质心,并将其分配给该质心对应的簇
K-均值效果差的原因:
k-均值算法收敛到了局部最小值,而非全局最小值
思考:K-均值聚类中的簇的数目如何来定?
SSE(Sum of Squared Error, 误差平方和),度量聚类效果的指标
SSE越小表越接近他们的质心,聚类效果越好
改进方法:
二分k-均值算法:
场景:克服K-均值算法收敛于局部最小问题
思想:
1、首先将所有点作为一个簇,然后将该簇一分为二,之后选择其中一个继续划分,其选择哪一个划分
取决于是否可以最大程度降低SSE值,不断重复直到得到用户指定的簇数目为止
2、另一种做法,选择最大的簇进行划分,直到簇数目达到用户指定数目为止
代码实践
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
K-均值聚类
"""
from numpy import *
import matplotlib
from matplotlib import pyplot as plt
def loadDataSet(fileName):
"""
加载数据
:param fileName: 问价路径
:return: 数据组
"""
dataMat = []
with open(fileName) as fr:
for line in fr.readlines():
curLine = line.strip().split('\t')
fltLine = [float(i) for i in curLine]
dataMat.append(fltLine)
return dataMat
def distEclud(vecA, vecB):
"""
计算欧式距离
:param vecA:
:param vecB:
:return:
"""
return sqrt(sum(power(vecA - vecB, 2)))
def randCent(dataSet, k):
n = shape(dataSet)[1]
centroids = mat(zeros((k, n)))
for j in range(n):
minJ = min(dataSet[:, j])
rangeJ = float(max(dataSet[:, j]) - minJ)
centroids[:, j] = minJ + rangeJ * random.rand(k, 1)
return centroids
def kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):
"""
K-均值算法
:param dataSet:
:param k:
:param distMeas:
:param createCent:
:return:
"""
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m, 2)))
centroids = createCent(dataSet, k)
clusterChanged = True
while clusterChanged:
clusterChanged = False
for i in range(m):
minDist = inf
minIndex = -1
for j in range(k):
distJI = distMeas(centroids[j, :], dataSet[i, :])
if distJI < minDist:
minDist = distJI
minIndex = j
if clusterAssment[i, 0] != minIndex:
clusterChanged = True
clusterAssment[i, :] = minIndex, minDist**2
# print(centroids)
for cent in range(k):
ptsInClust = dataSet[nonzero(clusterAssment[:, 0].A == cent)[0]]
centroids[cent, :] = mean(ptsInClust, axis=0)
return centroids, clusterAssment
def biKMeans(dataSet, k, distMeas=distEclud):
"""
二分k-均值
:param dataSet:
:param k:
:param distMeas:
:return:
"""
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m, 2)))
centroid0 = mean(dataSet, axis=0).tolist()[0]
centList = [centroid0]
for j in range(m):
clusterAssment[j, 1] = distMeas(mat(centroid0), dataSet[j, :])**2
while len(centList) < k:
lowestSSE = inf
for i in range(len(centList)):
ptsInCurrCluster = dataSet[nonzero(clusterAssment[:, 0].A == i)[0], :]
centroidMat, splitClustAss = kMeans(ptsInCurrCluster, 2, distMeas)
sseSplit = sum(splitClustAss[:, 1])
sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:, 0].A != i)[0],1])
print(f'sseSplit: {sseSplit}, and notSplit: {sseNotSplit}')
if sseSplit + sseNotSplit < lowestSSE:
bestCentToSplit = i
bestNewCents = centroidMat
bestClustAss = splitClustAss.copy()
lowestSSE = sseSplit + sseNotSplit
bestClustAss[nonzero(bestClustAss[:, 0].A == 1)[0], 0] = len(centList) # change 1 to 3,4, or whatever
bestClustAss[nonzero(bestClustAss[:, 0].A == 0)[0], 0] = bestCentToSplit
print(f'the bestCentToSplit is: {bestCentToSplit}')
print(f'the len of bestClustAss is: {len(bestClustAss)}')
centList[bestCentToSplit] = bestNewCents[0, :].tolist()[0] # replace a centroid with two best centroids
centList.append(bestNewCents[1, :].tolist()[0])
clusterAssment[nonzero(clusterAssment[:, 0].A == bestCentToSplit)[0], :] = bestClustAss # reassign new clusters, and SSE
return mat(centList), clusterAssment
# 对地理坐标进行聚类
def distSlC(vecA, vecB):
"""
计算球面距离
:param vecA:
:param vecB:
:return:
"""
a = sin(vecA[0, 1] * pi / 180) * sin(vecB[0, 1] * pi / 180)
b = cos(vecA[0, 1] * pi / 180) * cos(vecB[0, 1] * pi / 180) * cos(pi * (vecB[0, 0] - vecA[0, 0]) / 180)
return arccos(a + b) * 6371.0
def clusterClubs(fileName, numClust=5):
datList = []
with open(fileName) as fr:
for line in fr.readlines():
lineArr = line.split('\t')
datList.append([float(lineArr[4]), float(lineArr[3])])
datMat = mat(datList)
myCentroids, clustAssing = biKMeans(datMat, numClust, distMeas=distSlC)
fig = plt.figure()
rect = [0.1, 0.1, 0.8, 0.8]
scatterMarkers = ['s', 'o', '^', '8', 'p', 'd', 'v', 'h', '>', '<']
axprops = dict(xticks=[], yticks=[])
ax0 = fig.add_axes(rect, label='ax0', **axprops)
imgP = plt.imread(r"D:\ml_source_code\machinelearninginaction\Ch10\Portland.png")
ax0.imshow(imgP)
ax1 = fig.add_axes(rect, label='ax1', frameon=False)
for i in range(numClust):
ptsInCurrCluster = datMat[nonzero(clustAssing[:, 0].A == i)[0], :]
markerStyle = scatterMarkers[i % len(scatterMarkers)]
ax1.scatter(ptsInCurrCluster[:, 0].flatten().A[0], ptsInCurrCluster[:, 1].flatten().A[0], marker=markerStyle,
s=90)
ax1.scatter(myCentroids[:, 0].flatten().A[0], myCentroids[:, 1].flatten().A[0], marker='+', s=300)
plt.show()
if __name__ == '__main__':
filePath = r"D:\ml_source_code\machinelearninginaction\Ch10\places.txt"
# datMat = mat(loadDataSet(filePath))
# centList, myNewAssments = biKMeans(datMat, 3)
# print(centList)
# print(myNewAssments)
clusterClubs(filePath, numClust=5)