Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Fuzzy c-regression models: switching regression with crossing lines#
In a switching regression problem, every sample \((\mathbf{x}_k, y_k)\) obeys one of \(c\) unknown linear laws, but which one is not known. Hathaway and Bezdek replaced the point prototypes of fuzzy c-means by regression models: the “distance” of a sample to cluster \(i\) is the squared residual \(E_{ik}=(y_k-\mathbf{x}_{e,k}^T\boldsymbol\theta_i)^2\) of the \(i\)-th model, and the alternating optimization of
alternates weighted least squares (with \(\mu_{ik}^m\) as weights) and the FCM membership update. Because the prototypes are hyperplanes, the clusters may cross each other. Clustering the points with FCM fails in this configuration, because its spherical clusters cut the cross into halves; GK, whose clusters stretch along the lines, separates them but describes each law only by an ellipsoid. This example compares the point prototypes with FCRM and shows the role of the restarts and of the exponent \(m\).
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import adjusted_rand_score
from fuzzyclust import FCM, GK
from fuzzyclust.models import FuzzyCRegression, make_switching_lines
from fuzzyclust.plotting import PALETTE, plot_clusters, plot_covariance_ellipses
X, y, labels = make_switching_lines(n_samples=300, slopes=(1.0, -1.0), intercepts=(0.0, 1.0), noise=0.1,
random_state=0)
Z = np.hstack([X, y[:, None]]) # the product space (x, y)
Point prototypes versus regression prototypes#
FCM and GK are run on the \((x, y)\) points, FCRM on the input–output pairs.
# [snippet:fit]
fcm = FCM(n_clusters=2, random_state=0).fit(Z)
gk = GK(n_clusters=2, random_state=0).fit(Z)
fcrm = FuzzyCRegression(n_clusters=2, n_init=5, random_state=0).fit(X, y)
print("slopes :", fcrm.coef_[:, 0].round(3))
print("intercepts:", fcrm.intercept_.round(3))
# [/snippet:fit]
grid = np.linspace(-2, 2, 100)[:, None]
fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), sharey=True)
for ax, model, name in zip(axes[:2], (fcm, gk), ("FCM", "GK"), strict=True):
plot_clusters(Z, model.labels_, model.cluster_centers_, ax=ax, legend=False)
if hasattr(model, "covariances_"):
plot_covariance_ellipses(model.cluster_centers_, model.covariances_, ax=ax)
ax.set_title(f"{name} on the points: ARI = {adjusted_rand_score(labels, model.labels_):.2f}")
plot_clusters(Z, fcrm.labels_, ax=axes[2], legend=False)
lines = fcrm.predict(grid)
for i in range(2):
axes[2].plot(grid[:, 0], lines[:, i], color=PALETTE[i], lw=2.5)
axes[2].set_title(f"FCRM on the pairs: ARI = {adjusted_rand_score(labels, fcrm.labels_):.2f}")
for ax in axes:
ax.set_xlabel("x")
axes[0].set_ylabel("y")
plt.tight_layout()

slopes : [-0.998 1.005]
intercepts: [ 0.98 -0.007]
FCM splits the plane into a left and a right half. GK finds two elongated ellipsoids that follow one line each and labels the points as well as FCRM; both mislabel only a few points at the crossing, where the two laws are equally close. FCRM, in addition, recovers the slopes and intercepts and assigns every point to the line with the smaller residual.
Memberships along the input#
The membership of a pair depends on both residuals: near the crossing
(\(x=0.5\)) both lines fit and the memberships approach 1/2, whereas
far from it the assignment is crisp. The membership can only be evaluated
for pairs. For a new input alone, the model returns the outputs of all
\(c\) local models (predict), because a switching model does not
know which law a new input obeys.
U = fcrm.predict_proba(X, y)
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
for i in range(2):
axes[0].scatter(X[labels == i, 0], U[labels == i, 0], s=10, color=PALETTE[i], label=f"generated by line {i + 1}")
axes[0].axhline(0.5, color="0.5", ls=":")
axes[0].set_xlabel("x")
axes[0].set_ylabel(r"membership $\mu_{1k}$ in model 1")
axes[0].set_title("Memberships are fuzzy only where the lines cross")
axes[0].legend(frameon=False, fontsize=8)
axes[1].plot(fcrm.objective_history_, "o-", color=PALETTE[0])
axes[1].set_xlabel("iteration")
axes[1].set_ylabel("$J$")
axes[1].set_title(f"Monotone decrease of the objective ({fcrm.n_iter_} iterations)")
axes[1].grid(True, color="0.9")
plt.tight_layout()

Three lines, and the need for restarts#
With more models the functional has more local minima, in particular when
two of the laws are similar. Here two parallel lines (slope 1, intercepts
0 and 1) are crossed by a third one. A random initial partition may
converge to a solution in which one model fits the “average” of the two
parallel lines and another one is wasted. Running n_init restarts and
keeping the lowest \(J\) eliminates most such solutions.
X3, y3, lab3 = make_switching_lines(
n_samples=450, slopes=(1.0, 1.0, -1.0), intercepts=(0.0, 1.0, 0.5), noise=0.1, random_state=3
)
# [snippet:restarts]
single = [FuzzyCRegression(n_clusters=3, random_state=s).fit(X3, y3) for s in range(12)]
best = FuzzyCRegression(n_clusters=3, n_init=12, random_state=0).fit(X3, y3)
objectives = np.array([m.objective_ for m in single])
aris = np.array([adjusted_rand_score(lab3, m.labels_) for m in single])
# [/snippet:restarts]
print(pd.DataFrame({"seed": range(12), "J": objectives.round(2), "ARI": aris.round(3)}).to_string(index=False))
print(f"best of 12 restarts: J = {best.objective_:.2f}, ARI = {adjusted_rand_score(lab3, best.labels_):.3f}")
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))
worst = single[int(np.argmax(objectives))]
for ax, model, name in zip(axes, (worst, best), ("worst single run", "best of 12 restarts"), strict=True):
plot_clusters(np.hstack([X3, y3[:, None]]), model.labels_, ax=ax, legend=False)
lines = model.predict(grid)
for i in range(3):
ax.plot(grid[:, 0], lines[:, i], color=PALETTE[i], lw=2.5)
ax.set_title(f"{name}: J = {model.objective_:.1f}, ARI = {adjusted_rand_score(lab3, model.labels_):.2f}")
ax.set_xlabel("x")
axes[0].set_ylabel("y")
plt.tight_layout()

seed J ARI
0 3.87 0.931
1 3.87 0.931
2 14.73 0.333
3 14.73 0.333
4 3.87 0.931
5 14.73 0.333
6 46.34 0.064
7 3.87 0.931
8 14.73 0.333
9 3.87 0.931
10 3.87 0.931
11 46.34 0.064
best of 12 restarts: J = 3.87, ARI = 0.931
Parameter study: the fuzziness exponent#
As in FCM, \(m\) controls how sharply the residual ratio is turned into memberships. A small \(m\) gives a nearly crisp assignment (close to the classical switching-regression EM with hard labels); a large \(m\) spreads the memberships. Here the fitted lines hardly move with \(m\), because the residual ratios away from the crossing are sharp.
# [snippet:m_scan]
rows = []
for m in (1.2, 1.5, 2.0, 3.0, 5.0):
model = FuzzyCRegression(n_clusters=2, m=m, n_init=5, random_state=0).fit(X, y)
rows.append(
{
"m": m,
"slopes": np.sort(model.coef_[:, 0]).round(3),
"ARI": adjusted_rand_score(labels, model.labels_),
"mean max membership": model.membership_.max(axis=1).mean(),
}
)
table = pd.DataFrame(rows)
# [/snippet:m_scan]
print(table.round(3).to_string(index=False))
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(table["m"], table["mean max membership"], "o-", color=PALETTE[0], label="mean of $\\max_i \\mu_{ik}$")
ax.plot(table["m"], table["ARI"], "s-", color=PALETTE[1], label="ARI with the generating lines")
ax.set_xlabel("fuzziness exponent $m$")
ax.set_title("Effect of $m$ on the FCRM partition")
ax.legend(frameon=False, fontsize=8)
ax.grid(True, color="0.9")
plt.tight_layout()

m slopes ARI mean max membership
1.2 [-0.998, 1.005] 0.96 0.999
1.5 [-0.998, 1.005] 0.96 0.993
2.0 [-0.998, 1.005] 0.96 0.981
3.0 [-0.999, 1.005] 0.96 0.938
5.0 [-1.0, 1.004] 0.96 0.832
Take-away. When the structure in the data is a set of linear laws
rather than a set of compact groups, the prototype must be a regression
model. FCRM measures the distance of a sample by its residual and thus
handles crossing lines that defeat FCM and that GK describes only by
ellipsoids. The method inherits
the local minima of the c-means functional (use n_init), and its
membership needs the output. Prediction from the input alone requires a
model with an input-space partition (Takagi–Sugeno) or the
hinging-hyperplane construction of the next examples. Keep \(m\) near
2; larger values make the partition fuzzier without improving the lines.
Total running time of the script: (0 minutes 0.496 seconds)