Skip to content

Commit

Permalink
Add support for seeding RNG used for random sampling (#59). (#61)
Browse files Browse the repository at this point in the history
* Add support for seeding RNG used for random sampling (#59).

* Tweak docstring.

* Don't use 'int | None' for random_state type hint because it only works on Py 3.10+.

* Revert change to Cargo.lock.
  • Loading branch information
lebedov authored Jul 31, 2023
1 parent d5f8a8e commit 7fe2206
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 4 deletions.
2 changes: 1 addition & 1 deletion gap_statistic/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from gap_statistic.optimalK import OptimalK

__version__ = "2.0.0"
__version__ = "2.0.3"
7 changes: 5 additions & 2 deletions gap_statistic/optimalK.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def __init__(
clusterer: Callable = None,
clusterer_kwargs: dict = None,
n_iter: int = 10,
random_state: int = None
) -> None:
"""
Construct OptimalK to use n_jobs (multiprocessing using joblib, multiprocessing, or single core.
Expand All @@ -64,6 +65,7 @@ def __init__(
:param clusterer:
:param clusterer_kwargs:
:param n_iter int: only valid for 'rust' backend, iterations for Kmeans
:param random_state int: initialize RNG used to create random reference set
"""
if clusterer is not None and parallel_backend == "rust":
raise ValueError(
Expand All @@ -84,6 +86,7 @@ def __init__(
if clusterer is not None
else dict(iter=10, minit="points")
)
self._rs = np.random.RandomState(seed=random_state)

def __call__(
self,
Expand Down Expand Up @@ -260,7 +263,7 @@ def _calculate_gap(
) -> GapCalcResult:
"""
Calculate the gap value of the given data, n_refs, and number of clusters.
Return the resutling gap value and n_clusters
Return the resulting gap value and n_clusters
"""
# Holder for reference dispersion results
ref_dispersions = np.zeros(n_refs)
Expand All @@ -272,7 +275,7 @@ def _calculate_gap(
# For n_references, generate random sample and perform kmeans getting resulting dispersion of each loop
for i in range(n_refs):
# Create new random reference set uniformly over the range of each feature
random_data = np.random.random_sample(size=X.shape) * (b - a) + a
random_data = self._rs.random_sample(size=X.shape) * (b - a) + a

# Fit to it, getting the centroids and labels, and add to accumulated reference dispersions array.
centroids, labels = self.clusterer(
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

setup(
name="gap-stat",
version="2.0.2",
version="2.0.3",
author="Miles Granger",
maintainer="Miles Granger",
author_email="[email protected]",
Expand Down

0 comments on commit 7fe2206

Please sign in to comment.