entropyx
Version:
A simple data mining library, written in TypeScript
73 lines • 2.65 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DBSCAN = void 0;
const distance_1 = require("@/base/distance");
const lodash_1 = require("lodash");
class DBSCAN {
constructor(options = {}) {
this.options = options;
this.points = [];
this.visited = [];
this.assigned = [];
this.clusters = [];
if (!this.options.epsilon)
this.options.epsilon = 0.2;
if (!this.options.minPoints)
this.options.minPoints = 20;
if (!this.options.distance)
this.options.distance = distance_1.Distance.euclidean;
}
fit(data) {
this.points = data;
this.visited = Array(data.length).fill(false);
this.assigned = Array(data.length).fill(false);
this.clusters = [];
const { epsilon, minPoints, distance } = this.options;
for (let i = 0; i < data.length; i++) {
if (this.visited[i]) {
continue;
}
this.visited[i] = true;
const neighbors = this.rangeQuery(i, epsilon, distance);
if (neighbors.length >= minPoints) {
this.assigned[i] = true;
const expandedNeighborhood = this.expandNeighborhood(neighbors, minPoints, epsilon, distance);
this.clusters.push([i, ...expandedNeighborhood]);
}
}
return {
clusters: this.clusters,
noise: this.points.filter((value, key) => !this.assigned[key]),
};
}
expandNeighborhood(neighbors, minPoints, epsilon, distance) {
const cluster = [];
for (let i = 0; i < neighbors.length; i++) {
const point = neighbors[i];
if (!this.visited[point]) {
this.visited[point] = true;
const expandedNeighborhood = this.rangeQuery(point, epsilon, distance);
if (expandedNeighborhood.length >= minPoints) {
neighbors = (0, lodash_1.union)(neighbors, expandedNeighborhood);
}
}
if (!this.assigned[point]) {
this.assigned[point] = true;
cluster.push(point);
}
}
return cluster;
}
rangeQuery(point, epsilon, distance) {
const neighbors = [];
for (let i = 0; i < this.points.length; i++) {
if (point != i &&
distance(this.points[i], this.points[point]) < epsilon) {
neighbors.push(i);
}
}
return neighbors;
}
}
exports.DBSCAN = DBSCAN;
//# sourceMappingURL=dbscan.js.map