from __future__ import print_function, division
import numpy as np
from mlfromscratch.utils import normalize, euclidean_distance, Plot
from mlfromscratch.unsupervised_learning import *
class KMeans():
"""A simple clustering method that forms k clusters by iteratively reassigning
samples to the closest centroids and after that moves the centroids to the center
of the new formed clusters.
Parameters:
-----------
k: int
The number of clusters the algorithm will form.
max_iterations: int
The number of iterations the algorithm will run for if it does
not converge before that.
"""
def __init__(self, k=2, max_iterations=500):
self.k = k
self.max_iterations = max_iterations
def _init_random_centroids(self, X):
""" Initialize the centroids as k random samples of X"""
n_samples, n_features = np.shape(X)
centroids = np.zeros((self.k, n_features))
for i in range(self.k):
centroid = X[np.random.choice(range(n_samples))]
centroids[i] = centroid
return centroids
def _closest_centroid(self, sample, centroids):
""" Return the index of the closest centroid to the sample """
closest_i = 0
closest_dist = float('inf')
for i, centroid in enumerate(centroids):
distance = euclidean_distance(sample, centroid)
if distance < closest_dist:
closest_i = i
closest_dist = distance
return closest_i
def _create_clusters(self, centroids, X):
""" Assign the samples to the closest centroids to create clusters """
n_samples = np.shape(X)[0]
clusters = [[] for _ in range(self.k)]
for sample_i, sample in enumerate(X):
centroid_i = self._closest_centroid(sample, centroids)
clusters[centroid_i].append(sample_i)
return clusters
def _calculate_centroids(self, clusters, X):
""" Calculate new centroids as the means of the samples in each cluster """
n_features = np.shape(X)[1]
centroids = np.zeros((self.k, n_features))
for i, cluster in enumerate(clusters):
centroid = np.mean(X[cluster], axis=0)
centroids[i] = centroid
return centroids
def _get_cluster_labels(self, clusters, X):
""" Classify samples as the index of their clusters """
# One prediction for each sample
y_pred = np.zeros(np.shape(X)[0])
for cluster_i, cluster in enumerate(clusters):
for sample_i in cluster:
y_pred[sample_i] = cluster_i
return y_pred
def predict(self, X):
""" Do K-Means clustering and return cluster indices """
# Initialize centroids as k random samples from X
centroids = self._init_random_centroids(X)
# Iterate until convergence or for max iterations
for _ in range(self.max_iterations):
# Assign samples to closest centroids (create clusters)
clusters = self._create_clusters(centroids, X)
# Save current centroids for convergence check
prev_centroids = centroids
# Calculate new centroids from the clusters
centroids = self._calculate_centroids(clusters, X)
# If no centroids have changed => convergence
diff = centroids - prev_centroids
if not diff.any():
break
return self._get_cluster_labels(clusters, X)
[Machine Learning From Scratch]-unsupervised_learning-k_means
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門家肯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來龄砰,“玉大人,你說我怎么就攤上這事讨衣』慌铮” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵反镇,是天一觀的道長固蚤。 經(jīng)常有香客問我,道長歹茶,這世上最難降的妖魔是什么夕玩? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮惊豺,結(jié)果婚禮上燎孟,老公的妹妹穿的比我還像新娘。我一直安慰自己尸昧,他們只是感情好揩页,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著烹俗,像睡著了一般爆侣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上幢妄,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼衍锚!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起嗤堰,我...
- 序言:老撾萬榮一對(duì)情侶失蹤戴质,失蹤者是張志新(化名)和其女友劉穎度宦,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體告匠,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡戈抄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了后专。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片划鸽。...
- 正文 年R本政府宣布丈冬,位于F島的核電站,受9級(jí)特大地震影響甘畅,放射性物質(zhì)發(fā)生泄漏埂蕊。R本人自食惡果不足惜,卻給世界環(huán)境...
- 文/蒙蒙 一疏唾、第九天 我趴在偏房一處隱蔽的房頂上張望蓄氧。 院中可真熱鬧,春花似錦槐脏、人聲如沸喉童。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽泄朴。三九已至,卻和暖如春露氮,著一層夾襖步出監(jiān)牢的瞬間祖灰,已是汗流浹背。 一陣腳步聲響...
- 正文 我出身青樓叁扫,卻偏偏與公主長得像三妈,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子莫绣,可洞房花燭夜當(dāng)晚...