python簡易實現k means

2021-09-23 08:11:07 字數 1200 閱讀 4084

用dist存放所有資料到中心的距離,有n行(n組資料),k+1列(前k列分別存放到第i個類中心的距離,最後一列存放分到了第幾類)

#!/usr/bin/env python 

# -*- coding:utf-8 -*-

import numpy as np

n = 100

x = np.arange(100)

y = np.arange(200, 300, 1)

# 1、選中心,此時假設分為兩個類

k = 2

center0 = np.array([x[0],y[0]])

center1 = np.array([x[1],y[1]])

dist = np.zeros([n, k+1])

while true:

# 2、計算距離

for i in range(n):

dist[i, 0] = np.sqrt((x[i]-center0[0])**2 + (y[i]-center0[1])**2)

dist[i, 1] = np.sqrt((x[i]-center1[0])**2 + (y[i]-center1[1])**2)

if dist[i, 0] <= dist[i, 1]: # 3、根據距離值的大小來分類

dist[i, 2] = 0

else:

dist[i, 2] = 1

# 4、 計算新的類中心

index0 = dist[:,2] == 0 # 所有行的第三列為0

index1 = dist[:,2] == 1 # 所有行的第三列為1

center0_new = np.array([x[index0].mean(), y[index0].mean()]) # 邏輯值索引

center1_new = np.array([x[index1].mean(), y[index1].mean()])

# 5、判定結束演算法

if (center0 == center0_new).all() and (center1 == center1_new).all() :

break

else:

center0 = center0_new

center1 = center1_new

print(dist)

print(center0,center1)

kmean聚類python實現

import pandas as pd import numpy as np import xlrd 匯入資料 df2 pd.read excel test2.xlsx data np.array df2 去掉前兩列 data data 2 分為k類 k 3 臨近均值e e 0.00001 獲得行數...

Kmean聚類演算法原理python實現

kmean聚類演算法是基於距離對物件進行分類的演算法,該演算法實現步驟如下 1 確定初始資料簇質心,質心的數量與需要分的類的數量一致 2 將資料集中的每乙個物件與不同質心計算距離,並將其分類到最近的質心簇中 3 更新資料簇質心,迭代計算,直到資料簇質心不再變化或者分類精度達到要求時,停止演算法。如下...

Python實現簡易Socket

客戶端 向服務端傳送資訊和接收服務端返回的資訊 import socket flag true client socket.socket client.connect localhost 8080 連線服務埠 while flag msg input strip 獲取要傳送的資訊 if len ms...