main content

density-凯发k8网页登录

density-based spatial clustering of applications with noise (dbscan)

since r2019a

description

example

idx = dbscan(x,epsilon,minpts) partitions observations in the n-by-p data matrix x into clusters using the dbscan algorithm (see algorithms). dbscan clusters the observations (or points) based on a threshold for a neighborhood search radius epsilon and a minimum number of neighbors minpts required to identify a core point. the function returns an n-by-1 vector (idx) containing cluster indices of each observation.

example

idx = dbscan(x,epsilon,minpts,name,value) specifies additional options using one or more name-value pair arguments. for example, you can specify 'distance','minkowski','p',3 to use the minkowski distance metric with an exponent of three in the dbscan algorithm.

example

idx = dbscan(d,epsilon,minpts,'distance','precomputed') returns a vector of cluster indices for the precomputed pairwise distances d between observations. d can be the output of or , or a more general dissimilarity vector or matrix conforming to the output format of pdist or pdist2, respectively.

example

[idx,corepts] = dbscan(___) also returns a logical vector corepts that contains the core points identified by dbscan, using any of the input argument combinations in the previous syntaxes.

examples

cluster a 2-d circular data set using dbscan with the default euclidean distance metric. also, compare the results of clustering the data set using dbscan and k-means clustering with the squared euclidean distance metric.

generate synthetic data that contains two noisy circles.

rng('default') % for reproducibility
% parameters for data generation
n = 300;  % size of each cluster
r1 = 0.5; % radius of first circle
r2 = 5;   % radius of second circle
theta = linspace(0,2*pi,n)';
x1 = r1*[cos(theta),sin(theta)]  rand(n,1); 
x2 = r2*[cos(theta),sin(theta)]  rand(n,1);
x = [x1;x2]; % noisy 2-d circular data set

visualize the data set.

scatter(x(:,1),x(:,2))

figure contains an axes object. the axes object contains an object of type scatter.

the plot shows that the data set contains two distinct clusters.

perform dbscan clustering on the data. specify an epsilon value of 1 and a minpts value of 5.

idx = dbscan(x,1,5); % the default distance metric is euclidean distance

visualize the clustering.

gscatter(x(:,1),x(:,2),idx);
title('dbscan using euclidean distance metric')

figure contains an axes object. the axes object with title dbscan using euclidean distance metric contains 2 objects of type line. one or more of the lines displays its values using only markers these objects represent 1, 2.

using the euclidean distance metric, dbscan correctly identifies the two clusters in the data set.

perform dbscan clustering using the squared euclidean distance metric. specify an epsilon value of 1 and a minpts value of 5.

idx2 = dbscan(x,1,5,'distance','squaredeuclidean');

visualize the clustering.

gscatter(x(:,1),x(:,2),idx2);
title('dbscan using squared euclidean distance metric')

figure contains an axes object. the axes object with title dbscan using squared euclidean distance metric contains 2 objects of type line. one or more of the lines displays its values using only markers these objects represent 1, 2.

using the squared euclidean distance metric, dbscan correctly identifies the two clusters in the data set.

perform k-means clustering using the squared euclidean distance metric. specify k = 2 clusters.

kidx = kmeans(x,2); % the default distance metric is squared euclidean distance

visualize the clustering.

gscatter(x(:,1),x(:,2),kidx);
title('k-means using squared euclidean distance metric')

figure contains an axes object. the axes object with title k-means using squared euclidean distance metric contains 2 objects of type line. one or more of the lines displays its values using only markers these objects represent 1, 2.

using the squared euclidean distance metric, k-means clustering fails to correctly identify the two clusters in the data set.

perform dbscan clustering using a matrix of pairwise distances between observations as input to the dbscan function, and find the number of outliers and core points. the data set is a lidar scan, stored as a collection of 3-d points, that contains the coordinates of objects surrounding a vehicle.

load the x, y, z coordinates of the objects.

load('lidar_subset.mat') 
loc = lidar_subset;

to highlight the environment around the vehicle, set the region of interest to span 20 meters to the left and right of the vehicle, 20 meters in front and back of the vehicle, and the area above the surface of the road.

xbound = 20; % in meters
ybound = 20; % in meters
zlowerbound = 0; % in meters

crop the data to contain only points within the specified region.

indices = loc(:,1) <= xbound & loc(:,1) >= -xbound ...
    & loc(:,2) <= ybound & loc(:,2) >= -ybound ...
    & loc(:,3) > zlowerbound;
loc = loc(indices,:);

visualize the data as a 2-d scatter plot. annotate the plot to highlight the vehicle.

scatter(loc(:,1),loc(:,2),'.');
annotation('ellipse',[0.48 0.48 .1 .1],'color','red')

figure contains an axes object. the axes object contains an object of type scatter.

the center of the set of points (circled in red) contains the roof and hood of the vehicle. all other points are obstacles.

precompute a matrix of pairwise distances d between observations by using the pdist2 function.

d = pdist2(loc,loc);

cluster the data by using dbscan with the pairwise distances. specify an epsilon value of 2 and a minpts value of 50.

[idx, corepts] = dbscan(d,2,50,'distance','precomputed');

visualize the results and annotate the figure to highlight a specific cluster.

numgroups = length(unique(idx));
gscatter(loc(:,1),loc(:,2),idx,hsv(numgroups));
annotation('ellipse',[0.54 0.41 .07 .07],'color','red')
grid

figure contains an axes object. the axes object contains 12 objects of type line. one or more of the lines displays its values using only markers these objects represent -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11.

as shown in the scatter plot, dbscan identifies 11 clusters and places the vehicle in a separate cluster.

dbscan assigns the group of points circled in red (and centered around (3,–4)) to the same cluster (group 7) as the group of points in the southeast quadrant of the plot. the expectation is that these groups should be in separate clusters. you can try using a smaller value of epsilon to split up large clusters and further partition the points.

the function also identifies some outliers (an idx value of –1 ) in the data. find the number of points that dbscan identifies as outliers.

sum(idx == -1)
ans = 412

dbscan identifies 412 outliers out of 19,070 observations.

find the number of points that dbscan identifies as core points. a corepts value of 1 indicates a core point.

sum(corepts == 1)
ans = 18446

dbscan identifies 18,446 observations as core points.

see for a more extensive example.

input arguments

input data, specified as an n-by-p numeric matrix. the rows of x correspond to observations (or points), and the columns correspond to variables.

data types: single | double

pairwise distances between observations, specified as a numeric row vector that is the output of , numeric square matrix that is the output of , logical row vector, or logical square matrix. d can also be a more general dissimilarity vector or matrix that conforms to the output format of pdist or pdist2, respectively.

for the aforementioned specifications, the following table describes the formats that d can take, given an input matrix x that has n observations (rows) and p dimensions (columns).

specificationformat
numeric row vector (output of pdist(x))
  • a row vector of length n(n – 1)/2, corresponding to pairs of observations in x

  • distances arranged in the order (2,1), (3,1), ..., (n,1), (3,2), ..., (n,2), ..., (n,n – 1))

numeric square matrix (output of pdist2(x,x))
  • an n-by-n matrix, where d(i,j) is the distance between observations i and j in x

  • a symmetric matrix having diagonal elements equal to zero

logical row vector
  • a row vector of length n(n – 1)/2, corresponding to pairs of observations in x

  • a logical row vector with elements indicating distances that are less than or equal to epsilon

  • elements of d arranged in the order (2,1), (3,1), ..., (n,1), (3,2), ..., (n,2), ..., (n,n – 1))

logical square matrix
  • an n-by-n matrix, where d(i,j) indicates the distance between observations i and j in x that are less than or equal to epsilon

note

if d is a logical vector or matrix, then the value of epsilon must be empty; for example, dbscan(d,[],5,'distance','precomputed').

data types: single | double | logical

epsilon neighborhood of a point, specified as a numeric scalar that defines a neighborhood search radius around the point. if the epsilon neighborhood of a point contains at least minpts neighbors, then dbscan identifies the point as a core point.

the value of epsilon must be empty ([]) when d is a logical vector or matrix.

example: dbscan(x,2.5,10)

example: dbscan(d,[],5,'distance','precomputed'), for a logical matrix or vector d

data types: single | double

minimum number of neighbors required for a core point, specified as a positive integer. the epsilon neighborhood of a core point in a cluster must contain at least minpts neighbors, whereas the epsilon neighborhood of a border point can contain fewer neighbors than minpts.

example: dbscan(x,2.5,5)

data types: single | double

name-value arguments

specify optional pairs of arguments as name1=value1,...,namen=valuen, where name is the argument name and value is the corresponding value. name-value arguments must appear after other arguments, but the order of the pairs does not matter.

before r2021a, use commas to separate each name and value, and enclose name in quotes.

example: dbscan(d,2.5,5,'distance','precomputed') specifies dbscan clustering using a precomputed matrix of pairwise distances d between observations, an epsilon neighborhood of 2.5, and a minimum of 5 neighbors.

distance metric, specified as the comma-separated pair consisting of 'distance' and a character vector, string scalar, or function handle, as described in this table.

valuedescription
'precomputed'

precomputed distances. you must specify this option if the first input to dbscan is a vector or matrix of pairwise distances d.

'euclidean'

euclidean distance (default)

'squaredeuclidean'

squared euclidean distance. (this option is provided for efficiency only. it does not satisfy the triangle inequality.)

'seuclidean'

standardized euclidean distance. each coordinate difference between observations is scaled by dividing by the corresponding element of the standard deviation, s = std(x,'omitnan'). use scale to specify another value for s.

'mahalanobis'

mahalanobis distance using the sample covariance of x, c = cov(x,'omitrows'). use cov to specify another value for c, where the matrix c is symmetric and positive definite.

'cityblock'

city block distance

'minkowski'

minkowski distance. the default exponent is 2. use p to specify a different exponent, where p is a positive scalar value.

'chebychev'

chebychev distance (maximum coordinate difference)

'cosine'

one minus the cosine of the included angle between points (treated as vectors)

'correlation'

one minus the sample correlation between points (treated as sequences of values)

'hamming'

hamming distance, which is the percentage of coordinates that differ

'jaccard'

one minus the jaccard coefficient, which is the percentage of nonzero coordinates that differ

'spearman'

one minus the sample spearman's rank correlation between observations (treated as sequences of values)

@distfun

custom distance function handle. a distance function has the form

function d2 = distfun(zi,zj)
% calculation of distance
...
where
  • zi is a 1-by-n vector containing a single observation.

  • zj is an m2-by-n matrix containing multiple observations. distfun must accept a matrix zj with an arbitrary number of observations.

  • d2 is an m2-by-1 vector of distances, and d2(k) is the distance between observations zi and zj(k,:).

if your data is not sparse, you can generally compute distance more quickly by using a built-in distance instead of a function handle.

for definitions, see .

when you use the 'seuclidean', 'minkowski', or 'mahalanobis' distance metric, you can specify the additional name-value pair argument 'scale', 'p', or 'cov', respectively, to control the distance metrics.

example: dbscan(x,2.5,5,'distance','minkowski','p',3) specifies an epsilon neighborhood of 2.5, a minimum of 5 neighbors to grow a cluster, and use of the minkowski distance metric with an exponent of 3 when performing the clustering algorithm.

exponent for the minkowski distance metric, specified as the comma-separated pair consisting of 'p' and a positive scalar.

this argument is valid only if 'distance' is 'minkowski'.

example: 'p',3

data types: single | double

covariance matrix for the mahalanobis distance metric, specified as the comma-separated pair consisting of 'cov' and a symmetric, positive definite, numeric matrix.

this argument is valid only if 'distance' is 'mahalanobis'.

data types: single | double

scaling factors for the standardized euclidean distance metric, specified as the comma-separated pair consisting of 'scale' and a numeric vector of positive values.

each dimension (column) of x has a corresponding value in 'scale'; therefore, 'scale' is of length p (the number of columns in x). for each dimension of x, dbscan uses the corresponding value in 'scale' to standardize the difference between x and a query point.

this argument is valid only if 'distance' is 'seuclidean'.

data types: single | double

output arguments

cluster indices, returned as a numeric column vector. idx has n rows, and each row of idx indicates the cluster assignment of the corresponding observation in x. an index equal to –1 indicates an outlier (or noise point).

note

cluster assignment using the dbscan algorithm is dependent on the order of observations. therefore, shuffling the rows of x can lead to different cluster assignments for the observations. for more details, see algorithms.

data types: double

indicator for core points, returned as an n-by-1 logical vector indicating the indices of the core points identified by dbscan. a value of 1 in any row of corepts indicates that the corresponding observation in x is a core point. otherwise, corepts has a value of 0 for rows corresponding to observations that are not core points.

data types: logical

more about

core points

core points in a cluster are points that have at least a minimum number of neighbors (minpts) in their epsilon neighborhood (epsilon). each cluster must contain at least one core point.

border points

border points in a cluster are points that have fewer than the required minimum number of neighbors for a core point (minpts) in their epsilon neighborhood (epsilon). generally, the epsilon neighborhood of a border point contains significantly fewer points than the epsilon neighborhood of a core point.

noise points

noise points are outliers that do not belong to any cluster.

tips

  • for improved speed when iterating over many values of epsilon, consider passing in d as the input to dbscan. this approach prevents the function from having to compute the distances at every point of the iteration.

  • if you use to precompute d, do not specify the or name-value pair arguments of pdist2 to select or sort columns of d. selecting fewer than n distances results in an error, because dbscan expects d to be a square matrix. sorting the distances in each column of d leads to a loss in the interpretation of d and can give meaningless results when used in the dbscan function.

  • for efficient memory usage, consider passing in d as a logical matrix rather than a numeric matrix to dbscan when d is large. by default, matlab® stores each value in a numeric matrix using 8 bytes (64 bits), and each value in a logical matrix using 1 byte (8 bits).

  • to select a value for minpts, consider a value greater than or equal to the number of dimensions of the input data plus one [1]. for example, for an n-by-p matrix x, set 'minpts' equal to p 1 or greater.

  • one possible strategy for selecting a value for epsilon is to generate a k-distance graph for x. for each point in x, find the distance to the kth nearest point, and plot sorted points against this distance. generally, the graph contains a knee. the distance that corresponds to the knee is typically a good choice for epsilon, because it is the region where points start tailing off into outlier (noise) territory [1].

algorithms

  • dbscan is a density-based clustering algorithm that is designed to discover clusters and noise in data. the algorithm identifies three kinds of points: core points, border points, and noise points [1]. for specified values of epsilon and minpts, the dbscan function implements the algorithm as follows:

    1. from the input data set x, select the first unlabeled observation x1 as the current point, and initialize the first cluster label c to 1.

    2. find the set of points within the epsilon neighborhood epsilon of the current point. these points are the neighbors.

      1. if the number of neighbors is less than minpts, then label the current point as a noise point (or an outlier). go to step 4.

        note

        dbscan can reassign noise points to clusters if the noise points later satisfy the constraints set by epsilon and minpts from some other point in x. this process of reassigning points happens for border points of a cluster.

      2. otherwise, label the current point as a core point belonging to cluster c.

    3. iterate over each neighbor (new current point) and repeat step 2 until no new neighbors are found that can be labeled as belonging to the current cluster c.

    4. select the next unlabeled point in x as the current point, and increase the cluster count by 1.

    5. repeat steps 2–4 until all points in x are labeled.

  • if two clusters have varying densities and are close to each other, that is, the distance between two border points (one from each cluster) is less than epsilon, then dbscan can merge the two clusters into one.

  • every valid cluster might not contain at least minpts observations. for example, dbscan can identify a border point belonging to two clusters that are close to each other. in such a situation, the algorithm assigns the border point to the first discovered cluster. as a result, the second cluster is still a valid cluster, but it can have fewer than minpts observations.

references

[1] ester, m., h.-p. kriegel, j. sander, and x. xiaowei. “a density-based algorithm for discovering clusters in large spatial databases with noise.” in proceedings of the second international conference on knowledge discovery in databases and data mining, 226-231. portland, or: aaai press, 1996.

version history

introduced in r2019a

see also

| | | | |

topics

    网站地图