數(shù)據(jù)集和地圖可以點贊關(guān)注收藏后評論區(qū)留下QQ郵箱或者私信博主要
聚類是一類機器學習基礎(chǔ)算法的總稱。
聚類的核心計算過程是將數(shù)據(jù)對象集合按相似程度劃分成多個類,劃分得到的每個類稱為聚類的簇
聚類不等于分類,其主要區(qū)別在于聚類所面對的目標類別是未知的
k-means聚類也稱為K均值聚類算法,是典型的聚類算法,對于給定的數(shù)據(jù)集和需要劃分的類數(shù)K,算法根據(jù)距離函數(shù)進行迭代處理,動態(tài) 的把數(shù)據(jù)劃分成K個簇,直到收斂為止,簇中心也稱為聚類中心
先來個小例子
這個是通過聚類算法對鳶尾花數(shù)據(jù)集的預測結(jié)果
?代碼如下
from sklearn.cluster import KMeans
from sklearn import datasets
import numpy as np
iris=datasets.load_iris()
x=iris.data
y=iris.target
clf=KMeans(n_clusters=3)
model=clf.fit(x)
predicted=model.predict(x)
print("預測值",predicted)
print("真實值",y)
print()
?同樣地k-means聚類算法廣泛地應用于人群分類,圖像分割,物種聚類等等問題中
下面以一個物流配送問題為例進行詳細講解
問題描述:雙十一期間,物流公司要給某城市的50個客戶配送貨物,假設(shè)公司只有5輛貨車,客戶的地理坐標在txt文件中,如何配送效率最高
問題分析:使用k-means算法,將地址數(shù)據(jù)分為5類,由于每一類客戶地址相近,可以分配給同一臺貨車
原地圖如下
經(jīng)過聚類分析后結(jié)果如下
?很明顯根據(jù)客戶的地址分為5個簇,每個簇由一臺貨車集中配送
源代碼如下文章來源:http://www.zghlxwxcb.cn/news/detail-433113.html
#coding=utf-8
from numpy import *
from matplotlib import pyplot as plt
import matplotlib; matplotlib.use('TkAgg')
def disteclud(veca,vecb):
return sqrt(sum(power(veca-vecb,2)))
def initcenter(dataset,k):
print('2.initalize cluster center')
shape=dataset.shape
n=shape[1]
classcenter=array(zeros((k,n)))
for j in range(n):
firstk=dataset[:k,j]
classcenter[:,j]=firstk
return classcenter
def mykmeans(dataset,k):
m=len(dataset)
clusterpoints=array(zeros((m,2)))
classCenter=initcenter(dataset,k)
clusterchanged=True
print('3.recompute and reallocated')
while clusterchanged:
clusterchanged=False
for i in range(m):
mindist=inf
minindex=-1
for j in range(k):
distji=disteclud(classCenter[j,:],dataset[i,:])
if distji<mindist:
mindist=distji;minindex=j
if clusterpoints[i,0]!=minindex:
clusterchanged=True
clusterpoints[i,:]=minindex,mindist**2
for cent in range(k):
ptsinclust=dataset[nonzero(clusterpoints[:,0]==cent)[0]]
classCenter[cent,:]=mean(ptsinclust,axis=0)
return classCenter,clusterpoints
def show(dataset,k,classCenter,clusterPoints):
print('4.load the map')
fig=plt.figure()
rect=[0.1,0.1,1.0,1.0]
axprops=dict(xticks=[],yticks=[])
ax0=fig.add_axes(rect,label='ax1',frameon=False)
imgp=plt.imread(r'C:\Users\Admin\Desktop\city.png')
ax0.imshow(imgp)
ax1=fig.add_axes(rect,label='ax1',frameon=False)
print('5.show the clusters')
numsamples=len(dataset)
mark=['ok','^b','om','og','sc']
for i in range(numsamples):
markindex=int(clusterPoints[i,0])%k
ax1.plot(dataset[i,0],dataset[i,1],mark[markindex])
for i in range(k):
markindex=int(clusterPoints[i,0])%k
ax1.plot(classCenter[i,0],classCenter[i,1],'^r',markersize=12)
plt.show()
print('1. load the dataset')
dataset=loadtxt(r'C:\Users\Admin\Desktop\testSet.txt')
k=5
classCenter,clssspoints=mykmeans(dataset,k)
show(dataset,k,classCenter,clssspoints)
數(shù)據(jù)集和地圖可以點贊關(guān)注收藏后評論區(qū)留下QQ郵箱或者私信博主要文章來源地址http://www.zghlxwxcb.cn/news/detail-433113.html
到了這里,關(guān)于python k-means聚類算法 物流分配預測實戰(zhàn)(超詳細,附源碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!