聚类算法-DBSCAN-C++优化算法
在聚类算法-DBSCAN-C++实现的基础上做了优化,优化前本人测试对900左右个点进行聚类,用时2000ms左右,经过优化后的算法用时在100ms左右,提升了近20倍。
优化前主要耗时的地方:
float squareDistance(point a,point b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
这个函数涉及到平方和再开方,在做聚类时,每一次循环都在调用它,并且聚类算法中含有很多次循环,还有两层for循环嵌套的地方也在调用这个函数,所以计算起来很耗时。
优化思路:
- 减少
squareDistance(point a,point b)的计算量:
假设有900个点,在优化前的算法中对这900个点中每两个点之间都会计算距离,因为有很多个for循环,所以做了很多次900个点的距离计算。优化的思路就是减少squareDistance(point a,point b)的运算量,将每个点的x的平方和y的平方提前算出来,保存起来,用的时候直接取出来使用。 - 将for循环的局部变量变为全局变量,用空间换时间(对空间要求有限制的这里可以不改)
- 将i++换为++i
对于循环次数比较大的时候,++i会比i++省时间(具体原理可以参考++i和i++的具体实现)
代码实现:
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <limits>
#include <cmath>
#include <stack>
using namespace std;
int i;
int j;
float datax[1000];
float datay[1000];
float cdatax[1000];
float cdatay[1000];
class point{
public:
float x;
float y;
int cluster=0;
int pointType=1;//1 noise 2 border 3 core
int pts=0;//points in MinPts
vector<int> corepts;
int visited = 0;
point (){
}
point (float a,float b,int c){
x = a;
y = b;
cluster = c;
pointType = 1;
pts = 0;
visited = 0
}
};
float stringToFloat(string i){
stringstream sf;
float score=0;
sf<<i;
sf>>score;
return score;

本文介绍了一种DBSCAN聚类算法的C++实现及其优化方法。通过减少距离计算和使用全局变量等手段,使得运行时间从2000ms降低到100ms左右,提升了近20倍效率。
最低0.47元/天 解锁文章
2755

被折叠的 条评论
为什么被折叠?



