Kmeans

例如要把一组数据分成两个簇: 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
> dataset = matrix(c(1,2,
+ 1.2,2,
+ 8,9,
+ 0.9,1.8,
+ 7,10,
+ 8.8,9.2), nrow=6, byrow=T)
> dataset
      [,1] [,2]
[1,]  1.0  2.0
[2,]  1.2  2.0
[3,]  8.0  9.0
[4,]  0.9  1.8
[5,]  7.0 10.0
[6,]  8.8  9.2
> kmeans(dataset, 2, iter.max = 20)
K-means clustering with 2 clusters of sizes 3, 3
 
Cluster means:
       [,1]     [,2]
1 1.033333 1.933333
2 7.933333 9.400000
 
Clustering vector:
[1] 1 1 2 1 2 2
 
Within cluster sum of squares by cluster:
[1] 0.07333333 2.18666667
  (between_SS / total_SS =  98.6 %)
 
Available components:
 
[1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss" "betweenss"  
[7] "size"



可以看到,两个簇的中心是: 
?
1
2
3
4
Cluster means:
       [,1]     [,2]
1 1.033333 1.933333
2 7.933333 9.400000
6个数据的簇标号分别是: 
?
1
2
Clustering vector:
[1] 1 1 2 1 2 2

可视化: 
?
1
2
> result = kmeans(dataset, 2, iter.max = 20)
> plot(c(dataset[,1]), c(dataset[,2]), col=result$cluster)



 


参考: 
http://stat.ethz.ch/R-manual/R-devel/library/stats/html/kmeans.html 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyCharm是一个Python集成开发环境(IDE),而KMeans是一种常用的聚类算法。如果你想在PyCharm中使用KMeans算法,你需要先安装科学计算库,比如NumPy和scikit-learn。 首先,确保你已经安装了PyCharm和Python。然后,打开PyCharm并创建一个新的Python项目。 接下来,你需要安装所需的库。在PyCharm的菜单栏中,选择"File" -> "Settings"。在弹出的窗口中,选择 "Project: [你的项目名字]" -> "Python Interpreter"。点击右上角的加号"+"按钮,搜索并安装NumPy和scikit-learn。安装完成后,关闭设置窗口。 现在,你可以在项目中创建一个新的Python文件,开始编写KMeans代码。首先,导入所需的库: ```python import numpy as np from sklearn.cluster import KMeans ``` 然后,你可以定义你的数据。KMeans算法需要一个样本矩阵作为输入,每一行代表一个样本,每一列代表一个特征。例如: ```python data = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]]) ``` 接下来,创建一个KMeans对象,并指定聚类的数量: ```python kmeans = KMeans(n_clusters=2) ``` 然后,使用fit方法对数据进行聚类: ```python kmeans.fit(data) ``` 最后,你可以使用labels_属性获得每个样本的聚类标签,使用cluster_centers_属性获得聚类中心: ```python labels = kmeans.labels_ centers = kmeans.cluster_centers_ ``` 这样,你就可以在PyCharm中使用KMeans算法进行聚类分析了。记得保存和运行你的代码,查看结果。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值