/*
1.初始化数据
2.随机设置K个特征空间内的点作为初始的聚类中心
3.对于其他每个点计算到K个中心的距离,未知的点选择最近的一个聚类中心点作为标记类别
4.接着对着标记的聚类中之后,重新计算出每个聚类的新中点(平均值)
5.如果计算得出的新中心点与原中心点一样(质心不再移动),那么结束,否则重新进行第二步过程
*/
CREATE TABLE #T
(
p VARCHAR(10),
x DECIMAL(18,6),
y DECIMAL(18,6),
j INT
)
INSERT INTO #t(p,x,y) VALUES('p1',7,7)
INSERT INTO #t(p,x,y) VALUES('p2',2,3)
INSERT INTO #t(p,x,y) VALUES('p3',6,8)
INSERT INTO #t(p,x,y) VALUES('p4',1,4)
INSERT INTO #t(p,x,y) VALUES('p5',1,2)
INSERT INTO #t(p,x,y) VALUES('p6',3,1)
INSERT INTO #t(p,x,y) VALUES('p7',6,9)
INSERT INTO #t(p,x,y) VALUES('p8',8,8)
INSERT INTO #t(p,x,y) VALUES('p9',9,10)
INSERT INTO #t(p,x,y) VALUES('p10',5,5)
INSERT INTO #t(p,x,y) VALUES('p11',7,6)
INSERT INTO #t(p,x,y) VALUES('p12',9,3)
INSERT INTO #t(p,x,y) VALUES('p13',2,8)
INSERT INTO #t(p,x,y) VALUES('p14',5,11)
INSERT INTO #t(p,x,y) VALUES('p15',5,2)
DECLARE @K INT =2
SELECT TOP (@K) p,x,y,IDENTITY(INT,1,1) AS j
INTO #T2
FROM #T ORDER BY NEWID()
WHILE @@ROWCOUNT>0
BEGIN
UPDATE f SET j = e.j
FROM
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY p1 ORDER BY z) AS z2 FROM
(
SELECT a.p AS p1,b.p AS p2,SQRT(POWER(a.x-b.x,2)+POWER(a.y-b.y,2)) AS z
FROM #T a cross JOIN #T2 b
) c
) d
INNER JOIN #t2 e ON d.p2 = e.p
INNER JOIN #t f ON f.p = d.p1
WHERE z2=1
UPDATE a SET x = b.x ,y=b.y
FROM #T2 a
INNER JOIN
(
SELECT j,AVG(x) AS x,AVG(y) AS y
FROM #T
GROUP BY j
) b ON a.j = b.j
WHERE a.x <> b.x AND a.y<>b.y
END
SELECT * FROM #T ORDER BY j
DROP TABLE #T
DROP TABLE #T2
K-Means聚类算法
于 2024-04-12 10:25:31 首次发布
文章介绍了如何使用K-means算法对给定的数据集进行聚类,通过初始化数据,设置聚类中心,计算距离并更新中心点,直到质心不再变化。SQL脚本展示了在数据库中实现这一过程的步骤。
摘要由CSDN通过智能技术生成