层次聚类算法之single-linkage和complete-linkage(C语言实现)

2023-10-11 04:48

本文主要是介绍层次聚类算法之single-linkage和complete-linkage(C语言实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

层次聚类试图在不同层次上对数据集合进行划分, 从而形成树形的聚类结构。数据集的划分可采用“自底向上”的聚合策略,也可以采用“自顶向下”的分拆策略。

AGNES是一种采用自底向上的聚合策略的层次聚合算法,它先将数据集中的每个样本看作是一个初始的聚类簇,然后在算法进行的每一步中找出距离最近的两个聚类来进行合并,该过程不断的重复,直到到达预设的聚类簇的个数。

改算法的关键是如何计算聚类之间的距离, 实际上,每一个聚类是一个样本的集合,因此,只需要采用关于集合的某种距离即可。

最近距离由两个簇的最近的样本来决定, 最大距离由两个簇的最远的样本来决定,由此分别产生的AGNES算法又分别称为single-linkage和complete-linkage算法。


single-linkage算法

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<io.h>int sample_size;
int sample_dimension;
char filename[200];double** data;
double** distance;
int cluster_count;void initialization();
void readDataFromFile();
double calculateDistance_BetweenTwoObject(int, int);
void initializationDistanceMatrix();
void AGNES();
void findMinDistance_BetweenClsuter_MIN(int*, int*);
void combineCluster(int, int);
void writeToFile(int);int main(int argc, char* argv[])
{if( argc != 4 ){printf("This algorithm requires 4 user-specified parameter""\n\t\tthe number of sample""\n\t\tthe dimension of sample""\n\t\tthe filename contain the sample""\n\n");exit(0);}sample_size = atoi(argv[1]);sample_dimension = atoi(argv[2]);strcat(filename, argv[3]);initialization();readDataFromFile();initializationDistanceMatrix();AGNES();return 0;
}/** initialize the dynamic array for storing sample* */
void initialization()
{//initializaion the sample dataint i, j;data = (double**)malloc(sizeof(double*) * (sample_size + 1));if( !data ){printf("data malloc error: 0");exit(0);}for( i = 1; i <= sample_size; i++ ){data[i] = (double*)malloc(sizeof(double) * (sample_dimension + 1));if( !data[i] ){printf("data malloc error: %d", i);exit(0);}}//initialiation the distance datadistance = (double**)malloc(sizeof(double*) * (sample_size + 1));if( !distance ){printf("distance malloc error: 0");exit(0);}for( i = 1; i <= sample_size; i++ ){distance[i] = (double*)malloc(sizeof(double) * (sample_size + 1));if( !distance[i] ){printf("distance malloc error: %d", i);exit(0);}}//the 0th element of all row indicate the clauterID of the objectfor( i = 1; i <= sample_size; i++ ){distance[i][0] = i;}
}/** read the sample data from file* */
void readDataFromFile()
{FILE* fread;int i;int j;if( NULL == (fread = fopen(filename, "r"))){printf("open file(%s) error: ", filename);exit(0);}for( i = 1; i <= sample_size; i++ ){for( j = 1; j <= sample_dimension; j++ ){if( 1 != fscanf(fread, "%lf ", &data[i][j])){printf("fscanf error: (%d, %d)", i, j);exit(0);}}}//testprintf("print the origin data:\n");for( i = 1; i <= sample_size; i++ ){for( j = 1; j <= sample_dimension; j++ ){printf("%f\t", data[i][j]);}printf("\n");}//test END
}/** calculate distance between two objects* */
double calculateDistance_BetweenTwoObject(int firstID, int secondID)
{double distance = 0.0;int i;for( i = 1; i <= sample_dimension; i++ ){distance = distance + pow(data[firstID][i] - data[secondID][i], 2);}return sqrt(distance);
}/** calculate initialization distance matrix* */
void initializationDistanceMatrix()
{int i, j;for( i = 1; i <= sample_size; i++ ){for( j = i; j <= sample_size; j++ ){distance[i][j] = calculateDistance_BetweenTwoObject(i, j);distance[j][i] = distance[i][j];}}//testprintf("print the origin distance matrix\n");for( i = 1; i <= sample_size; i++ ){for( j = 0; j <= sample_size; j++ ){printf("%f ", distance[i][j]);}printf("\n");}//test END
}/****************************************************************************************************************						AGNES***************************************************************************************************************/
void AGNES()
{cluster_count = sample_size;int cluster_1, cluster_2;int count = 1;while( cluster_count > 3 ){printf("-------------------%d--------------------\n", count);findMinDistance_BetweenClsuter_MIN(&cluster_1, &cluster_2);combineCluster(cluster_1, cluster_2);				cluster_count--;writeToFile(count++);}
}/** find two clusters the distance between them is minimun, and store the clusterID in @cluster_1 and @cluster_2, respectively.* */
void findMinDistance_BetweenClsuter_MIN(int* cluster_1, int* cluster_2)
{int i, j;double min_distance;int flag = 1;for( i = 1; i <= sample_size; i++ ){for( j = i + 1; j <= sample_size; j++ ){if( distance[i][0] == distance[j][0] ){printf("same cluster!!!! %d and %d\n\n", i , j);continue;}else if( flag == 1 ){min_distance = distance[i][j];*cluster_1 = i;*cluster_2 = j;flag = 0;printf("----get the initial minimum distance is %f(%d, %d)\n", min_distance, i, j);continue;}if( distance[i][j] < min_distance ){min_distance = distance[i][j];*cluster_1 = i;*cluster_2 = j;}}}printf("the minimum is %f :(%d, %d)\n", min_distance, *cluster_1, *cluster_2);
}/** combine the two clusters to one* */
void combineCluster(int cluster_1, int cluster_2)
{int i;int buffer;buffer = distance[cluster_2][0];for( i = 1; i <= sample_size; i++ ){if( distance[i][0] == buffer ){distance[i][0] = distance[cluster_1][0];}}//testprintf(" the minimum distance is %f, and the object is %d and %d\n", distance[cluster_1][cluster_2], cluster_1, cluster_2);int j;for( i = 1; i <= sample_size; i++ ){for( j = 0; j <= sample_size; j++ ){printf("%f ", distance[i][j]);}printf("\n");}
}/** write the result of clustering information to file* */
void writeToFile(int round)
{int i;int j;int* auxiliary = (int*)malloc(sizeof(int) * (sample_size + 1));if( !auxiliary ){printf("auxiliary malloc error");exit(0);}for( i = 1; i <= sample_size; i++ )auxiliary[i] = 0;for( i = 1; i <= sample_size; i++ ){auxiliary[(int)distance[i][0]]++;}int *clusterID = (int*)malloc(sizeof(int) * (sample_size - round + 1));if( !clusterID ){printf("clusterID malloc error");exit(0);}int counter = 1;for( i = 1; i <= sample_size; i++ ){if( auxiliary[i] != 0 )clusterID[counter++] = i;}//testprintf("cluster ID:");for( i = 1; i <= sample_size - round; i++ ){printf("%d ", clusterID[i]);}printf("\n");//test ENDprintf("writeToFile -----------round: %d\n", round);FILE** fwrite;fwrite = (FILE**)malloc(sizeof(FILE*) * (sample_size + 1));if( !fwrite ){printf("fwrite malloc error\n");exit(0);}char filename[200] = "";char instruction[200] = "";sprintf(instruction, "md  Round_%d", round);system(instruction);for( i = 1; i <= sample_size - round; i++ ){sprintf(filename, ".//Round_%d//cluster_%d.data", round, clusterID[i]);if( NULL == (fwrite[clusterID[i]] = fopen(filename, "w"))){printf("open file(%s) error\n", filename);exit(0);}}for( i = 1; i <= sample_size; i++ ){printf("%d ", (int)distance[i][0]);for( j = 1; j <= sample_dimension; j++ ){fprintf(fwrite[(int)distance[i][0]], "%f\t", data[i][j]);printf("%f ", data[i][j]);}fprintf(fwrite[(int)distance[i][0]], "\n");printf("\n");}for( i = 1; i <= sample_size - round; i++ ){fclose(fwrite[clusterID[i]]);}
}

complete-linkage算法

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<io.h>int sample_size;
int sample_dimension;
char filename[200];double** data;
double** distance;
int cluster_count;void initialization();
void readDataFromFile();
double calculateDistance_BetweenTwoObject(int, int);
void initializationDistanceMatrix();
void findMinDistance_BetweenClsuter_MAX(int*, int*);
void AGNES();
void combineCluster(int, int);
void updateDistance(int);
void writeToFile(int);int main(int argc, char* argv[])
{if( argc != 4 ){printf("This algorithm requires 4 user-specified parameter""\n\t\tthe number of sample""\n\t\tthe dimension of sample""\n\t\tthe filename contain the sample""\n\n");exit(0);}sample_size = atoi(argv[1]);sample_dimension = atoi(argv[2]);strcat(filename, argv[3]);initialization();readDataFromFile();initializationDistanceMatrix();AGNES();return 0;
}/** initialize the dynamic array for storing sample* */
void initialization()
{//initializaion the sample dataint i, j;data = (double**)malloc(sizeof(double*) * (sample_size + 1));if( !data ){printf("data malloc error: 0");exit(0);}for( i = 1; i <= sample_size; i++ ){data[i] = (double*)malloc(sizeof(double) * (sample_dimension + 1));if( !data[i] ){printf("data malloc error: %d", i);exit(0);}}//initialiation the distance datadistance = (double**)malloc(sizeof(double*) * (sample_size + 1));if( !distance ){printf("distance malloc error: 0");exit(0);}for( i = 0; i <= sample_size; i++ ){distance[i] = (double*)malloc(sizeof(double) * (sample_size + 1));if( !distance[i] ){printf("distance malloc error: %d", i);exit(0);}}//the 0th element of all row indicate the clauterID of the objectfor( i = 1; i <= sample_size; i++ ){distance[i][0] = i;}//where reserved if distance[0][i] = 1, for( i = 1; i <= sample_size; i++ ){distance[0][i] = 1;}
}/** read the sample data from file* */
void readDataFromFile()
{FILE* fread;int i;int j;if( NULL == (fread = fopen(filename, "r"))){printf("open file(%s) error: ", filename);exit(0);}for( i = 1; i <= sample_size; i++ ){for( j = 1; j <= sample_dimension; j++ ){if( 1 != fscanf(fread, "%lf ", &data[i][j])){printf("fscanf error: (%d, %d)", i, j);exit(0);}}}
}/** calculate distance between two objects* */
double calculateDistance_BetweenTwoObject(int firstID, int secondID)
{double distance = 0.0;int i;for( i = 1; i <= sample_dimension; i++ ){distance = distance + pow(data[firstID][i] - data[secondID][i], 2);}return sqrt(distance);
}/** calculate initialization distance matrix* */
void initializationDistanceMatrix()
{int i, j;for( i = 1; i <= sample_size; i++ ){for( j = i; j <= sample_size; j++ ){distance[i][j] = calculateDistance_BetweenTwoObject(i, j);distance[j][i] = distance[i][j];}}
}/****************************************************************************************************************						AGNES***************************************************************************************************************/
void AGNES()
{cluster_count = sample_size;int cluster_1, cluster_2;int count = 1;while( cluster_count > 3 ){printf("-------------------%d--------------------\n", count);findMinDistance_BetweenClsuter_MAX(&cluster_1, &cluster_2);combineCluster(cluster_1, cluster_2);updateDistance(cluster_1);		cluster_count--;writeToFile(count++);}
}/** find two clusters the distance between them is minimun, and store the clusterID in @cluster_1 and @cluster_2, respectively.* */
void findMinDistance_BetweenClsuter_MAX(int* cluster_1, int* cluster_2)
{int i, j;double min_distance;int flag = 1;int object_1;int object_2;for( i = 1; i <= sample_size; i++ ){for( j = i + 1; j <= sample_size; j++ ){if( distance[i][0] == distance[j][0] || ( distance[0][i] == 0 || distance[0][j] == 0 ) ){continue;}else if( flag == 1 ){min_distance = distance[i][j];object_1 = i;object_2 = j;flag = 0;continue;}if( distance[i][j] < min_distance ){min_distance = distance[i][j];object_1 = i;object_2 = j;}}}*cluster_1 = distance[object_1][0];*cluster_2 = distance[object_2][0];
}/** combine the two clusters to one* */
void combineCluster(int cluster_1, int cluster_2)
{int i;for( i = 1; i <= sample_size; i++ ){if( distance[i][0] == cluster_2 ){distance[i][0] = cluster_1;}}
}/** update distance data* */
void updateDistance(int clusterID)
{int i, j;int flag = 1;int save_i;for( i = 1; i <= sample_size; i++ ){if( distance[i][0] == clusterID && flag == 1 ){flag = 0;save_i = i;continue;}else if( distance[i][0] == clusterID && flag == 0 ){distance[0][i] = 0;for( j = 1; j <= sample_size; j++ ){if( distance[i][j] > distance[save_i][j] ){distance[save_i][j] = distance[i][j];}}}}for( i = 1; i <= sample_size; i++ ){distance[i][save_i] = distance[save_i][i];}
}/** write the result of clustering information to file* */
void writeToFile(int round)
{int i;int j;int* auxiliary = (int*)malloc(sizeof(int) * (sample_size + 1));if( !auxiliary ){printf("auxiliary malloc error");exit(0);}for( i = 1; i <= sample_size; i++ )auxiliary[i] = 0;for( i = 1; i <= sample_size; i++ ){auxiliary[(int)distance[i][0]]++;}int *clusterID = (int*)malloc(sizeof(int) * (sample_size - round + 1));if( !clusterID ){printf("clusterID malloc error");exit(0);}int counter = 1;for( i = 1; i <= sample_size; i++ ){if( auxiliary[i] != 0 )clusterID[counter++] = i;}printf("writeToFile -----------round: %d\n", round);FILE** fwrite;fwrite = (FILE**)malloc(sizeof(FILE*) * (sample_size + 1));if( !fwrite ){printf("fwrite malloc error\n");exit(0);}char filename[200] = "";char instruction[200] = "";sprintf(instruction, "md  Round_%d", round);system(instruction);for( i = 1; i <= sample_size - round; i++ ){sprintf(filename, ".//Round_%d//cluster_%d.data", round, clusterID[i]);if( NULL == (fwrite[clusterID[i]] = fopen(filename, "w"))){printf("open file(%s) error\n", filename);exit(0);}}for( i = 1; i <= sample_size; i++ ){printf("%d ", (int)distance[i][0]);for( j = 1; j <= sample_dimension; j++ ){fprintf(fwrite[(int)distance[i][0]], "%f\t", data[i][j]);}fprintf(fwrite[(int)distance[i][0]], "\n");}for( i = 1; i <= sample_size - round; i++ ){fclose(fwrite[clusterID[i]]);}
}


这篇关于层次聚类算法之single-linkage和complete-linkage(C语言实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/185619

相关文章

使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)

《使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)》在现代软件开发中,处理JSON数据是一项非常常见的任务,无论是从API接口获取数据,还是将数据存储为JSON格式,解析... 目录1. 背景介绍1.1 jsON简介1.2 实际案例2. 准备工作2.1 环境搭建2.1.1 添加

Java实现任务管理器性能网络监控数据的方法详解

《Java实现任务管理器性能网络监控数据的方法详解》在现代操作系统中,任务管理器是一个非常重要的工具,用于监控和管理计算机的运行状态,包括CPU使用率、内存占用等,对于开发者和系统管理员来说,了解这些... 目录引言一、背景知识二、准备工作1. Maven依赖2. Gradle依赖三、代码实现四、代码详解五

java如何分布式锁实现和选型

《java如何分布式锁实现和选型》文章介绍了分布式锁的重要性以及在分布式系统中常见的问题和需求,它详细阐述了如何使用分布式锁来确保数据的一致性和系统的高可用性,文章还提供了基于数据库、Redis和Zo... 目录引言:分布式锁的重要性与分布式系统中的常见问题和需求分布式锁的重要性分布式系统中常见的问题和需求

SpringBoot基于MyBatis-Plus实现Lambda Query查询的示例代码

《SpringBoot基于MyBatis-Plus实现LambdaQuery查询的示例代码》MyBatis-Plus是MyBatis的增强工具,简化了数据库操作,并提高了开发效率,它提供了多种查询方... 目录引言基础环境配置依赖配置(Maven)application.yml 配置表结构设计demo_st

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

el-select下拉选择缓存的实现

《el-select下拉选择缓存的实现》本文主要介绍了在使用el-select实现下拉选择缓存时遇到的问题及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录项目场景:问题描述解决方案:项目场景:从左侧列表中选取字段填入右侧下拉多选框,用户可以对右侧

Python pyinstaller实现图形化打包工具

《Pythonpyinstaller实现图形化打包工具》:本文主要介绍一个使用PythonPYQT5制作的关于pyinstaller打包工具,代替传统的cmd黑窗口模式打包页面,实现更快捷方便的... 目录1.简介2.运行效果3.相关源码1.简介一个使用python PYQT5制作的关于pyinstall

使用Python实现大文件切片上传及断点续传的方法

《使用Python实现大文件切片上传及断点续传的方法》本文介绍了使用Python实现大文件切片上传及断点续传的方法,包括功能模块划分(获取上传文件接口状态、临时文件夹状态信息、切片上传、切片合并)、整... 目录概要整体架构流程技术细节获取上传文件状态接口获取临时文件夹状态信息接口切片上传功能文件合并功能小

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur

C#实现文件读写到SQLite数据库

《C#实现文件读写到SQLite数据库》这篇文章主要为大家详细介绍了使用C#将文件读写到SQLite数据库的几种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下... 目录1. 使用 BLOB 存储文件2. 存储文件路径3. 分块存储文件《文件读写到SQLite数据库China编程的方法》博客中,介绍了文