日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python實(shí)現(xiàn)k-means算法_python

作者:咕嘟咕嘟_ ? 更新時(shí)間: 2022-03-29 編程語(yǔ)言

聚類(lèi)屬于無(wú)監(jiān)督學(xué)習(xí),K-means算法是很典型的基于距離的聚類(lèi)算法,采用距離作為相似性的評(píng)價(jià)指標(biāo),即認(rèn)為兩個(gè)對(duì)象的距離越近,其相似度就越大。該算法認(rèn)為簇是由距離靠近的對(duì)象組成的,因此把得到緊湊且獨(dú)立的簇作為最終目標(biāo)。

下面來(lái)看看python實(shí)現(xiàn)k-means算法的詳細(xì)代碼吧:

# -*- coding:utf-8 -*-
import random

import numpy as np
from matplotlib import pyplot


class K_Means(object):
? ? # k是分組數(shù);tolerance‘中心點(diǎn)誤差';max_iter是迭代次數(shù)
? ? def __init__(self, k=2, tolerance=0.0001, max_iter=300):
? ? ? ? self.k_ = k
? ? ? ? self.tolerance_ = tolerance
? ? ? ? self.max_iter_ = max_iter

? ? def fit(self, data):
? ? ? ? self.centers_ = {}
? ? ? ? for i in range(self.k_):
? ? ? ? ? ? self.centers_[i] = data[random.randint(0,len(data))]
? ? ? ? # print('center', self.centers_)
? ? ? ? for i in range(self.max_iter_):
? ? ? ? ? ? self.clf_ = {} #用于裝歸屬到每個(gè)類(lèi)中的點(diǎn)[k,len(data)]
? ? ? ? ? ? for i in range(self.k_):
? ? ? ? ? ? ? ? self.clf_[i] = []
? ? ? ? ? ? # print("質(zhì)點(diǎn):",self.centers_)
? ? ? ? ? ? for feature in data:
? ? ? ? ? ? ? ? distances = [] #裝中心點(diǎn)到每個(gè)點(diǎn)的距離[k]
? ? ? ? ? ? ? ? for center in self.centers_:
? ? ? ? ? ? ? ? ? ? # 歐拉距離
? ? ? ? ? ? ? ? ? ? distances.append(np.linalg.norm(feature - self.centers_[center]))
? ? ? ? ? ? ? ? classification = distances.index(min(distances))
? ? ? ? ? ? ? ? self.clf_[classification].append(feature)

? ? ? ? ? ? # print("分組情況:",self.clf_)
? ? ? ? ? ? prev_centers = dict(self.centers_)

? ? ? ? ? ? for c in self.clf_:
? ? ? ? ? ? ? ? self.centers_[c] = np.average(self.clf_[c], axis=0)

? ? ? ? ? ? # '中心點(diǎn)'是否在誤差范圍
? ? ? ? ? ? optimized = True
? ? ? ? ? ? for center in self.centers_:
? ? ? ? ? ? ? ? org_centers = prev_centers[center]
? ? ? ? ? ? ? ? cur_centers = self.centers_[center]
? ? ? ? ? ? ? ? if np.sum((cur_centers - org_centers) / org_centers * 100.0) > self.tolerance_:
? ? ? ? ? ? ? ? ? ? optimized = False
? ? ? ? ? ? if optimized:
? ? ? ? ? ? ? ? break

? ? def predict(self, p_data):
? ? ? ? distances = [np.linalg.norm(p_data - self.centers_[center]) for center in self.centers_]
? ? ? ? index = distances.index(min(distances))
? ? ? ? return index


if __name__ == '__main__':
? ? x = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
? ? k_means = K_Means(k=2)
? ? k_means.fit(x)
? ? for center in k_means.centers_:
? ? ? ? pyplot.scatter(k_means.centers_[center][0], k_means.centers_[center][1], marker='*', s=150)

? ? for cat in k_means.clf_:
? ? ? ? for point in k_means.clf_[cat]:
? ? ? ? ? ? pyplot.scatter(point[0], point[1], c=('r' if cat == 0 else 'b'))

? ? predict = [[2, 1], [6, 9]]
? ? for feature in predict:
? ? ? ? cat = k_means.predict(feature)
? ? ? ? pyplot.scatter(feature[0], feature[1], c=('r' if cat == 0 else 'b'), marker='x')

? ? pyplot.show()

原文鏈接:https://blog.csdn.net/EMIvv/article/details/122403531

欄目分類(lèi)
最近更新