TensorFlow and Affinity Propagation
TensorFlow 2.21.0 does not provide a maintained high-level Affinity Propagation estimator. TensorFlow 1 placeholders and sessions are also not current eager-mode APIs. This example computes a valid similarity tensor and passes it to scikit-learn.
1. Build negative squared-distance similarities
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn.cluster import AffinityPropagation
from sklearn.datasets import make_blobs
from sklearn.metrics import adjusted_rand_score
X, reference = make_blobs(n_samples=180, centers=3, cluster_std=0.60, random_state=42)
X_tensor = tf.convert_to_tensor(X, dtype=tf.float64)
deltas = X_tensor[:, None, :] - X_tensor[None, :, :]
similarity_tensor = -tf.reduce_sum(tf.square(deltas), axis=2)
similarity = similarity_tensor.numpy()
np.testing.assert_allclose(similarity, similarity.T)
2. Fit with explicit preference and damping
off_diagonal = similarity[~np.eye(len(X), dtype=bool)]
preference = float(np.median(off_diagonal))
model = AffinityPropagation(
affinity="precomputed",
preference=preference,
damping=0.8,
random_state=42,
).fit(similarity)
labels = model.labels_
assert model.n_iter_ < model.max_iter
assert adjusted_rand_score(reference, labels) > 0.95
exemplars = X[model.cluster_centers_indices_]
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap="viridis", s=24)
plt.scatter(exemplars[:, 0], exemplars[:, 1], c="red", marker="x", s=100)
plt.title("Affinity Propagation with a TensorFlow similarity")
plt.close()
The explicit framework boundary is preferable to an incomplete custom loop. TensorFlow builds the representation; scikit-learn owns message passing, convergence checks, and exemplar extraction.