Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added OPTICS clustering algorithm #295

Merged
merged 8 commits into from
Sep 12, 2024
302 changes: 302 additions & 0 deletions lib/scholar/cluster/optics.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,302 @@
defmodule Scholar.Cluster.OPTICS do
@moduledoc """
OPTICS (Ordering Points To Identify the Clustering Structure) is an algorithm
for finding density-based clusters in spatial data.
norm4nn marked this conversation as resolved.
Show resolved Hide resolved
It is closely related to DBSCAN, finds core sample of high density and expands
clusters from them. Unlike DBSCAN, keeps cluster hierarchy for a variable
neighborhood radius. Clusters are then extracted using a DBSCAN-like
method.
"""
import Nx.Defn
require Nx

@derive {Nx.Container, containers: [:labels, :min_samples, :max_eps, :eps, :algorithm]}
defstruct [:labels, :min_samples, :max_eps, :eps, :algorithm]

opts = [
min_samples: [
default: 5,
type: :pos_integer,
doc: """
The number of samples in a neighborhood for a point to be considered as a core point.
"""
],
max_eps: [
type: {:custom, Scholar.Options, :beta, []},
doc: """
The maximum distance between two samples for one to be considered as in the neighborhood of the other.
Default value of Nx.Constants.infinity() will identify clusters across all scales.
"""
],
eps: [
type: {:custom, Scholar.Options, :beta, []},
doc: """
The maximum distance between two samples for one to be considered as in the neighborhood of the other.
By default it assumes the same value as max_eps.
"""
],
algorithm: [
default: :brute,
type: :atom,
doc: """
Algorithm used to compute the k-nearest neighbors. Possible values:

* `:brute` - Brute-force search. See `Scholar.Neighbors.BruteKNN` for more details.

* `:kd_tree` - k-d tree. See `Scholar.Neighbors.KDTree` for more details.

* `:random_projection_forest` - Random projection forest. See `Scholar.Neighbors.RandomProjectionForest` for more details.

* Module implementing `fit(data, opts)` and `predict(model, query)`. predict/2 must return a tuple containing indices
of k-nearest neighbors of query points as well as distances between query points and their k-nearest neighbors.
Also has to take num_neighbors as argument.
"""
]
]

@opts_schema NimbleOptions.new!(opts)

@doc """
Perform OPTICS clustering for `x` which is tensor of `{n_samples, n_features} shape.

## Options

#{NimbleOptions.docs(@opts_schema)}

## Return Values

The function returns a labels tensor of shape `{n_samples}`.
Cluster labels for each point in the dataset given to fit().
Noisy samples are labeled as -1.

## Examples

iex> x = Nx.tensor([[1, 2], [2, 5], [3, 6], [8, 7], [8, 8], [7, 3]])
iex> Scholar.Cluster.OPTICS.fit(x, min_samples: 2)
#Nx.Tensor<
s64[6]
[-1, -1, -1, -1, -1, -1]
>
iex> Scholar.Cluster.OPTICS.fit(x, eps: 4.5, min_samples: 2)
#Nx.Tensor<
s64[6]
[0, 0, 0, 1, 1, 1]
>
iex> Scholar.Cluster.OPTICS.fit(x, eps: 2, min_samples: 2)
#Nx.Tensor<
s64[6]
[-1, 0, 0, 1, 1, -1]
>
iex> Scholar.Cluster.OPTICS.fit(x, eps: 2, min_samples: 2, algorithm: :kd_tree, metric: {:minkowski, 1})
#Nx.Tensor<
s64[6]
[-1, 0, 0, 1, 1, -1]
>
iex> Scholar.Cluster.OPTICS.fit(x, eps: 1, min_samples: 2)
#Nx.Tensor<
s64[6]
[-1, -1, -1, 0, 0, -1]
>
iex> Scholar.Cluster.OPTICS.fit(x, eps: 4.5, min_samples: 3)
#Nx.Tensor<
s64[6]
[0, 0, 0, 1, 1, -1]
>
"""

defn fit(x, opts \\ []) do
if Nx.rank(x) != 2 do
raise ArgumentError,
"""
expected x to have shape {num_samples, num_features}, \
got tensor with shape: #{inspect(Nx.shape(x))}
"""
end

x = Scholar.Shared.to_float(x)
module = validate_options(x, opts)

%__MODULE__{
module
| labels: fit_p(x, module)
}
end

deftransformp validate_options(x, opts \\ []) do
{opts, algorithm_opts} = Keyword.split(opts, [:min_samples, :max_eps, :eps, :algorithm])
opts = NimbleOptions.validate!(opts, @opts_schema)
min_samples = opts[:min_samples]

if min_samples < 2 do
raise ArgumentError,
"""
min_samples must be an int in the range [2, inf), got min_samples = #{inspect(min_samples)}
"""
end

algorithm_opts = Keyword.put(algorithm_opts, :num_neighbors, min_samples)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this line is needed anymore.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It turns out that it is needed, in the same function, few lines below I call function .fit() from algorithm_module , which requires :num_neighbors. However the value I set here doesn't have any meaning so it can be any positive integer like 1 for example. It wouldn't be required if I could pass just algorithm_module to module struct, but it doesn't seem to be possible.


algorithm_module =
case opts[:algorithm] do
:brute ->
Scholar.Neighbors.BruteKNN

:kd_tree ->
Scholar.Neighbors.KDTree

:random_projection_forest ->
Scholar.Neighbors.RandomProjectionForest

module when is_atom(module) ->
module
end
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remember to run mix format :)


model = algorithm_module.fit(x, algorithm_opts)

max_eps =
case opts[:max_eps] do
nil -> Nx.Constants.infinity(Nx.type(x))
any -> any
end

eps =
case opts[:eps] do
nil -> max_eps
any -> any
end

if eps > max_eps do
raise ArgumentError,
"""
eps can't be greater than max_eps, got eps = #{inspect(eps)} and max_eps = #{inspect(max_eps)}
"""
end

%__MODULE__{
labels: Nx.broadcast(-1, {Nx.axis_size(x, 0)}),
min_samples: min_samples,
max_eps: max_eps,
eps: eps,
algorithm: model
}
end

defnp fit_p(x, module) do
{core_distances, reachability, _predecessor, ordering} = compute_optics_graph(x, module)

cluster_optics_dbscan(reachability, core_distances, ordering, module)
end

defnp compute_optics_graph(x, %__MODULE__{max_eps: max_eps, min_samples: min_samples} = module) do
n_samples = Nx.axis_size(x, 0)
reachability = Nx.broadcast(Nx.Constants.max_finite(Nx.type(x)), {n_samples})
predecessor = Nx.broadcast(-1, {n_samples})
{_neighbors, distances} = run_knn(x, x, module)
core_distances = Nx.slice_along_axis(distances, min_samples - 1, 1, axis: 1)

core_distances =
Nx.select(core_distances > max_eps, Nx.Constants.infinity(), core_distances)

ordering = Nx.broadcast(0, {n_samples})
processed = Nx.broadcast(0, {n_samples})

{_order_idx, core_distances, reachability, predecessor, _processed, ordering, _x, _module} =
while {order_idx = 0, core_distances, reachability, predecessor, processed, ordering, x,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be vectorized.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you provide a more specific to hint on how to vectorize? Or maybe you can do a separate pass later and vectorize it? Given they are getting acquainted with the codebase + Nx, it may be a bit too complex to pull off. :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be honest, I didn't think much about it, nor am I insisting on vectorization for this pull request. I just mentioned it as something to think of. Should have written that as well. 😅

That said, the fact that the condition in the loop is order_idx < num_samples and order_idx is incremented in every iteration kinda indicates that this could be vectorized. I need to have a closer look.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're absolutely right about the struct—it should be included to maintain consistency.

Also, I get a headache just thinking about vectorizing this entire section of code . Implementing it in its current state was already pretty complex.

Copy link
Member

@krstopro krstopro Aug 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very well, you can leave vectorization to someone else :)

module},
order_idx < n_samples do
unprocessed_mask = processed == 0
point = Nx.argmin(Nx.select(unprocessed_mask, reachability, Nx.Constants.infinity()))
processed = Nx.put_slice(processed, [point], Nx.new_axis(1, 0))
ordering = Nx.put_slice(ordering, [order_idx], Nx.new_axis(point, 0))

{reachability, predecessor} =
set_reach_dist(core_distances, reachability, predecessor, point, processed, x, module)

{order_idx + 1, core_distances, reachability, predecessor, processed, ordering, x, module}
end

reachability =
Nx.select(
reachability == Nx.Constants.max_finite(Nx.type(x)),
Nx.Constants.infinity(),
reachability
)

{core_distances, reachability, predecessor, ordering}
end

defnp set_reach_dist(
core_distances,
reachability,
predecessor,
point_index,
processed,
x,
%__MODULE__{max_eps: max_eps} = module
) do
n_features = Nx.axis_size(x, 1)
n_samples = Nx.axis_size(x, 0)
t = Nx.take(x, point_index, axis: 0)
p = Nx.broadcast(t, {1, n_features})
{neighbors, distances} = run_knn(x, p, %__MODULE__{module | min_samples: n_samples})
neighbors = Nx.flatten(neighbors)
distances = Nx.flatten(distances)
indices_ngbrs = Nx.argsort(neighbors)
neighbors = Nx.take(neighbors, indices_ngbrs)
distances = Nx.take(distances, indices_ngbrs)
are_neighbors_processed = Nx.take(processed, neighbors)

filtered_neighbors =
Nx.select(
are_neighbors_processed or distances > max_eps,
-1 * neighbors,
neighbors
)

dists = Nx.flatten(Scholar.Metrics.Distance.pairwise_minkowski(p, x))
core_distance = Nx.take(core_distances, point_index)
rdists = Nx.max(dists, core_distance)
improved = rdists < reachability
improved = Nx.select(improved, filtered_neighbors, -1)

improved =
Nx.select(
improved == -1 and filtered_neighbors > 0,
Nx.multiply(filtered_neighbors, -1),
filtered_neighbors
)

rdists = Nx.select(improved >= 0, rdists, 0)
reversed_improved = Nx.max(improved * -1, 0)

reachability =
Nx.select(improved <= 0, Nx.take(reachability, reversed_improved), rdists)

predecessor =
Nx.select(improved <= 0, Nx.take(predecessor, reversed_improved), point_index)

{reachability, predecessor}
end

deftransformp run_knn(x, p, %__MODULE__{algorithm: algorithm_module, min_samples: k} = _module) do
nbrs = algorithm_module.__struct__.fit(x, num_neighbors: k)
algorithm_module.__struct__.predict(nbrs, p)
end

defnp cluster_optics_dbscan(
reachability,
core_distances,
ordering,
%__MODULE__{eps: eps} = _module
) do
far_reach = Nx.flatten(reachability > eps)
near_core = Nx.flatten(core_distances <= eps)
far_and_not_near = Nx.multiply(far_reach, 1 - near_core)
far_reach = Nx.take(far_reach, ordering)
near_core = Nx.take(near_core, ordering)
far_and_near = far_reach * near_core
labels = Nx.as_type(Nx.cumulative_sum(far_and_near), :s8) - 1
labels = Nx.take(labels, Nx.argsort(ordering))
Nx.select(far_and_not_near, -1, labels)
end
end
Loading