用c++写一个一维AGNES聚类方法
时间: 2023-12-09 13:02:48 浏览: 57
下面是一个使用C++编写的一维AGNES聚类方法的示例代码:
```c++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// 计算欧几里得距离
double euclidean_distance(double a, double b) {
return sqrt(pow(a - b, 2));
}
// 计算两个簇之间的距离
double cluster_distance(vector<double>& cluster1, vector<double>& cluster2) {
double min_distance = INFINITY;
for (double& a : cluster1) {
for (double& b : cluster2) {
double distance = euclidean_distance(a, b);
if (distance < min_distance) {
min_distance = distance;
}
}
}
return min_distance;
}
// 将两个簇合并
void merge_clusters(vector<vector<double>>& clusters, int index1, int index2) {
// 将index2中的元素添加到index1中
for (double& a : clusters[index2]) {
clusters[index1].push_back(a);
}
// 删除index2
clusters.erase(clusters.begin() + index2);
}
// AGNES聚类
vector<vector<double>> agnes_clustering(vector<double>& data, int k) {
// 初始化每个数据点为一个簇
vector<vector<double>> clusters;
for (double& a : data) {
vector<double> cluster;
cluster.push_back(a);
clusters.push_back(cluster);
}
// 逐步合并簇
while (clusters.size() > k) {
int min_i = 0, min_j = 1;
double min_distance = cluster_distance(clusters[0], clusters[1]);
// 找到距离最近的两个簇
for (int i = 0; i < clusters.size(); i++) {
for (int j = i + 1; j < clusters.size(); j++) {
double distance = cluster_distance(clusters[i], clusters[j]);
if (distance < min_distance) {
min_distance = distance;
min_i = i;
min_j = j;
}
}
}
// 合并最近的两个簇
merge_clusters(clusters, min_i, min_j);
}
return clusters;
}
int main() {
vector<double> data = { 1, 2, 4, 10, 11, 13, 15, 16, 17, 18 };
int k = 3;
vector<vector<double>> clusters = agnes_clustering(data, k);
// 输出聚类结果
for (int i = 0; i < clusters.size(); i++) {
cout << "Cluster " << i + 1 << ": ";
for (double& a : clusters[i]) {
cout << a << " ";
}
cout << endl;
}
return 0;
}
```
该示例代码实现了一维数据的AGNES聚类方法,并可以指定聚成的簇数。输入数据为一维数组,输出结果为聚类后的簇。
阅读全文