-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Add Quantum k-Means Clustering Implementation #11664
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
Closed
RahulPatnaik
wants to merge
8
commits into
TheAlgorithms:master
from
RahulPatnaik:quantum-kmeans-clustering
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7d1d891
Add Quantum k-Means Clustering Implementation
RahulPatnaik 027549b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] e2d0e50
Add type hints and doctests for quantum k-means clustering functions
RahulPatnaik 89f5f80
Merge branch 'quantum-kmeans-clustering' of https://github.com/RahulP…
RahulPatnaik c46141d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] caf89c4
Made relevant changes specified
RahulPatnaik facfce2
Merge branch 'quantum-kmeans-clustering' of https://github.com/RahulP…
RahulPatnaik 3655742
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
import cirq | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
from sklearn.datasets import make_blobs | ||
from sklearn.preprocessing import MinMaxScaler | ||
|
||
|
||
def generate_data(n_samples=100, n_features=2, n_clusters=2): | ||
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
data, labels = make_blobs( | ||
n_samples=n_samples, centers=n_clusters, n_features=n_features, random_state=42 | ||
) | ||
return MinMaxScaler().fit_transform(data), labels | ||
|
||
|
||
def quantum_distance(point1, point2): | ||
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Computes the quantum distance between two points. | ||
|
||
:param point1: First point as a numpy array. | ||
:param point2: Second point as a numpy array. | ||
:return: Quantum distance between the two points. | ||
|
||
>>> point_a = np.array([1.0, 2.0]) | ||
>>> point_b = np.array([1.5, 2.5]) | ||
>>> result = quantum_distance(point_a, point_b) | ||
>>> assert isinstance(result, float) | ||
""" | ||
qubit = cirq.LineQubit(0) | ||
diff = np.clip(np.linalg.norm(point1 - point2), 0, 1) | ||
theta = 2 * np.arcsin(diff) | ||
|
||
circuit = cirq.Circuit(cirq.ry(theta)(qubit), cirq.measure(qubit, key="result")) | ||
|
||
result = cirq.Simulator().run(circuit, repetitions=1000) | ||
return result.histogram(key="result").get(1, 0) / 1000 | ||
|
||
|
||
def initialize_centroids(data: np.ndarray, k: int) -> np.ndarray: | ||
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Initializes centroids for k-means clustering. | ||
|
||
:param data: The dataset from which to initialize centroids. | ||
:param k: The number of centroids to initialize. | ||
:return: An array of initialized centroids. | ||
|
||
>>> data = np.array([[1, 2], [3, 4], [5, 6]]) | ||
>>> centroids = initialize_centroids(data, 2) | ||
>>> assert centroids.shape == (2, 2) | ||
""" | ||
return data[np.random.choice(len(data), k, replace=False)] | ||
|
||
|
||
def assign_clusters(data, centroids): | ||
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
clusters = [[] for _ in range(len(centroids))] | ||
for point in data: | ||
closest = min( | ||
range(len(centroids)), key=lambda i: quantum_distance(point, centroids[i]) | ||
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) | ||
clusters[closest].append(point) | ||
return clusters | ||
|
||
|
||
def recompute_centroids(clusters): | ||
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return np.array([np.mean(cluster, axis=0) for cluster in clusters if cluster]) | ||
|
||
|
||
def quantum_kmeans(data, k, max_iters=10): | ||
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
RahulPatnaik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
centroids = initialize_centroids(data, k) | ||
|
||
for _ in range(max_iters): | ||
clusters = assign_clusters(data, centroids) | ||
new_centroids = recompute_centroids(clusters) | ||
if np.allclose(new_centroids, centroids): | ||
break | ||
centroids = new_centroids | ||
|
||
return centroids, clusters | ||
|
||
|
||
# Main execution | ||
n_samples, n_clusters = 10, 2 | ||
data, labels = generate_data(n_samples, n_clusters=n_clusters) | ||
|
||
plt.figure(figsize=(12, 5)) | ||
|
||
plt.subplot(121) | ||
plt.scatter(data[:, 0], data[:, 1], c=labels) | ||
plt.title("Generated Data") | ||
|
||
final_centroids, final_clusters = quantum_kmeans(data, n_clusters) | ||
|
||
plt.subplot(122) | ||
for i, cluster in enumerate(final_clusters): | ||
cluster = np.array(cluster) | ||
plt.scatter(cluster[:, 0], cluster[:, 1], label=f"Cluster {i+1}") | ||
plt.scatter( | ||
final_centroids[:, 0], | ||
final_centroids[:, 1], | ||
color="red", | ||
marker="x", | ||
s=200, | ||
linewidths=3, | ||
label="Centroids", | ||
) | ||
plt.title("Quantum k-Means Clustering with Cirq") | ||
plt.legend() | ||
|
||
plt.tight_layout() | ||
plt.show() | ||
|
||
print(f"Final Centroids:\n{final_centroids}") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.