import numpy as np
# k-means演算法的實現
# s = [[20, 5, 15], [9, 18, 10], [21, 10, 7], [17, 13, 25], [12, 21, 19]]
# 選定兩點
# 1.求距離
# 兩種型別
label1 =
label2 =
# 先假定兩個中心點
mean1 =[20
,15,14
]mean2 =[17
,19,26
]ls =
# 第乙個引數是待聚合的資料,第二個和第三個引數分別是其中心點
defdistance
(t1, t2, t3)
:global label1;
label1 =
global label2;
label2 =
length =
len(t1[0]
)for i in t1:
distance1 =
0 distance2 =
0 count =
0while
(count < length)
: distance1 = distance1 +
(i[count]
- t2[count])**
2 distance2 = distance2 +
(i[count]
- t3[count])**
2 count = count +1if
(distance1 > distance2)
:else
: remeans(la1=label1, la2=label2)
# 2.重新計算中心值
defremeans
(**label)
: flag =
0global mean1;
mean1 =
global mean2;
mean2 =
for key, value in label.items():
index =
0for i in
range
(len
(value[0]
)): temp = np.array(value)
row = temp[
:, index:index +1]
row =
[i for j in row for i in j]
length =
len(row)
count =
sum(i for i in row)
clx = count / length
if(flag ==0)
:else
: index = index +
1 flag = flag +
1# temp = np.array(temp)
# ls = np.array(ls)
# flag = 0
# while ((temp != ls).all() and flag < 20):
# 儲存臨時變數
temp1 =
temp2 =
flag =
0t1 =[[
20,5,
15],[
21,10,
7],[
17,13,
25],[
12,22,
17],[
21,10,
7],[
12,21,
19]]while
(temp1 != mean1 and temp2 != mean2 and flag <20)
: temp1 = mean1
temp2 = mean2
distance(t1, temp1, temp2)
flag = flag +
1print
("class1"
, label1)
print
("class"
, label2)
騷氣的Python之k means演算法
1.回顧 上次對驗證碼進行了去噪和灰度化,這次對它進一步地分類處理,這裡用顏色區分,顯然是分成4個類 2.關於演算法原理我就不多說,下面看 encoding utf 8 from pil import image import math import copy import random class...
kmeans演算法(python實現)
import numpy as np import matplotlib.pyplot as plt initialize center函式通過使用numpy庫的 zeros函式和random.uniform函式,隨機選取 了k個資料做聚類中心,並將結果存放在 了k個資料做聚類中心,並將結果存放在 ...
k means演算法實現python
import numpy as np import matplotlib.pyplot as plt 兩點距離 defdistance e1,e2 return np.sqrt e1 0 e2 0 2 e1 1 e2 1 2 集合中心 defmeans arr return np.array np....