from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=5,n_jobs=-1,random_state=1234) # 模型训练 kmeans_fit = kmeans.fit(data_scale) # 聚类中心 kmeans_cluster = kmeans_fit.cluster_centers_ print('聚类中心为\n',kmeans_fit.cluster_centers_) # 聚类后样本的类别标签 kmeans_label = kmeans_fit.labels_ print('聚类后样本标签为\n',kmeans_fit.labels_) # 聚类后各个类别数目 r1 = pd.Series(kmeans_label).value_counts() print('聚类后各个类别数目\n',r1) # 输出聚类分群结果 cluster_center = pd.DataFrame(kmeans_cluster,columns=['ZL','ZR','ZF','ZM','ZC']) cluster_center.index = pd.DataFrame(kmeans_label).drop_duplicates().iloc[:,0] cluster = pd.concat([r1,cluster_center],axis=1) # 修改第一列列名 list_column = list(cluster.columns) list_column[0] = '类别数目' cluster.columns = list_column 将上述代码转换为matlab语言
时间: 2024-01-22 22:17:35 浏览: 78
finding_no_of-clusters_in_kmeans.tar.gz_Kmeans
把Python代码转换为MATLAB代码可以参考以下示例:
```matlab
% 导入sklearn库中的KMeans类
addpath('sklearn.cluster')
from sklearn.cluster import KMeans
% 构造KMeans对象
kmeans = KMeans('n_clusters',5,'n_jobs',-1,'random_state',1234);
% 训练模型
kmeans_fit = kmeans.fit(data_scale);
% 获取聚类中心
kmeans_cluster = kmeans_fit.cluster_centers_;
disp('聚类中心为:');
disp(kmeans_fit.cluster_centers_);
% 获取样本的类别标签
kmeans_label = kmeans_fit.labels_;
disp('聚类后样本标签为:');
disp(kmeans_fit.labels_);
% 获取各个类别数目
r1 = tabulate(kmeans_label);
disp('聚类后各个类别数目:');
disp(r1);
% 输出聚类分群结果
cluster_center = array2table(kmeans_cluster,'VariableNames',{'ZL','ZR','ZF','ZM','ZC'});
cluster_center.Properties.RowNames = cellstr(num2str(unique(kmeans_label)));
cluster = [array2table(r1(:,2),'VariableNames',{'类别数目'}), cluster_center];
cluster.Properties.VariableNames{1} = '类别数目';
disp(cluster);
```
需要注意的是,MATLAB中没有直接对应Python中的pandas库,因此需要使用MATLAB自带的数据类型,如table和cell等。另外,Python中的value_counts()方法在MATLAB中可以使用tabulate()函数实现。
阅读全文