Untitled
Anonymous
Plain Text
10/09/2025 8:28 AM
34.2 KB
13
Indexable
Never
# lab1_grupowanie_bez_fcm.py
# ----------------------------------------
# Zadanie: dwa raporty K-średnich (bez FCM)
# 1) K-means (euklidesowa), k=3 — raport po 4 i 10 iteracjach (tabele + wykresy)
# 2) K-means z odległością |x1_A - x1_B|, k=4 — raport po 10 iteracjach (tabela) + wykres po 4 iteracjach
#
# Skrypt jest samowystarczalny (posiada dane w kodzie). Jeśli masz plik 'spiralka.csv' obok,
# możesz zamiast danych wbudowanych wczytać go zakomentowaną sekcją z pandas.read_csv.
#
# Wymagania: numpy, pandas, matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
from typing import Callable, Dict, Tuple
# ====== Dane ======
# Jeśli chcesz wczytać z pliku CSV (z nagłówkami x1,x2), odkomentuj dwie linie poniżej:
# import pandas as pd
# df = pd.read_csv("spiralka.csv")
spiral_points = [
(-0.0824,0.9435),(0.0913,0.9575),(0.0476,1.0683),(0.2311,1.0452),(0.2269,0.9615),
(0.2717,1.057),(0.343,1.0724),(0.4765,1.006),(0.5039,0.9162),(0.5113,0.8803),
(0.6735,0.8263),(0.803,0.8494),(0.8318,0.8573),(0.7825,0.7032),(0.8566,0.7646),
(0.8544,0.6752),(1.0519,0.6502),(1.0302,0.5818),(1.1587,0.5559),(1.0992,0.4486),
(1.1175,0.3286),(1.1493,0.3144),(1.1607,0.1619),(1.2388,0.2232),(1.2136,0.1041),
(1.3375,0.0204),(1.2301,-0.0344),(1.2946,-0.0799),(1.3301,-0.2716),(1.3287,-0.248),
(1.2707,-0.4779),(1.2219,-0.564),(1.2314,-0.5076),(1.071,-0.6311),(1.0461,-0.8127),
(1.085,-0.7972),(1.1371,-0.7834),(0.9918,-1.0194),(0.8467,-1.0041),(0.9301,-1.1675),
(0.8569,-1.0805),(0.6782,-1.0943),(0.6759,-1.3292),(0.5377,-1.276),(0.4944,-1.2617),
(0.4819,-1.2857),(0.4601,-1.3957),(0.2684,-1.382),(0.1669,-1.4465),(0.1774,-1.4508),
(-0.0566,-1.4538),(-0.1226,-1.5564),(-0.1725,-1.5277),(-0.3374,-1.4758),(-0.4568,-1.5191),
(-0.4682,-1.4563),(-0.5552,-1.4464),(-0.6295,-1.4956),(-0.8523,-1.3649),(-0.8152,-1.3287),
(-0.952,-1.3021),(-0.9805,-1.2422),(-1.1398,-1.2181),(-1.1746,-1.157),(-1.3583,-1.1144),
(-1.3366,-0.8821),(-1.3595,-0.9266),(-1.4969,-0.7615),(-1.5441,-0.6479),(-1.4743,-0.6608),
(-1.5488,-0.4747),(-1.7169,-0.3264),(-1.7011,-0.2524),(-1.6954,-0.2604),(-1.7168,-0.0879),
(-1.779,-0.0625),(-1.7251,0.1885),(-1.7787,0.1831),(-1.7208,0.2806),(-1.7544,0.5381),
(-1.681,0.476),(-1.7296,0.5807),(-1.6673,0.727),(-1.5808,0.968),(-1.5305,1.0313),
(-1.5638,1.0163),(-1.3728,1.2606),(-1.2852,1.2611),(-1.3866,1.3016),(-1.1773,1.4962),
(-1.1918,1.6133),(-1.0784,1.6521),(-0.8967,1.6324),(-0.8501,1.7047),(-0.8084,1.8031),
(-0.6135,1.8584),(-0.5031,1.8191),(-0.334,1.8515),(-0.32,1.9158),(-0.2074,1.9929),
(0.0322,1.9473),
]
df = pd.DataFrame(spiral_points, columns=["x1", "x2"])
X = df[["x1", "x2"]].to_numpy()
# ====== K-means z możliwością customowej metryki ======
def kmeans_custom(
X: np.ndarray,
k: int,
iters: int,
dist: Callable[[np.ndarray, np.ndarray], float],
seed: int = 42,
snapshot_iters: Tuple[int, ...] = (),
) -> Dict[int, Dict]:
"""
Prosta implementacja K-średnich z wtykaną metryką (distance function).
- Inicjalizacja: k losowych, różnych próbek jako centroidy.
- Zwraca migawki (centry, etykiety, liczności) dla iteracji z snapshot_iters oraz ostatniej.
"""
rng = np.random.default_rng(seed)
n = X.shape[0]
idxs = rng.choice(n, size=k, replace=False)
centers = X[idxs].astype(float).copy()
def assign_labels(centers: np.ndarray) -> np.ndarray:
labels = np.empty(n, dtype=int)
for i, x in enumerate(X):
dists = [dist(x, c) for c in centers]
labels[i] = int(np.argmin(dists))
return labels
def recompute_centers(labels: np.ndarray, prev_centers: np.ndarray) -> np.ndarray:
new_centers = prev_centers.copy()
for j in range(k):
members = X[labels == j]
if len(members) > 0:
new_centers[j] = members.mean(axis=0)
return new_centers
snapshots: Dict[int, Dict] = {}
labels = assign_labels(centers)
for t in range(1, iters + 1):
centers = recompute_centers(labels, centers)
labels = assign_labels(centers)
if t in snapshot_iters or t == iters:
counts = np.bincount(labels, minlength=k)
snapshots[t] = {
"centers": centers.copy(),
"labels": labels.copy(),
"counts": counts.copy(),
}
return snapshots
def dist_euclidean(a: np.ndarray, b: np.ndarray) -> float:
return float(np.linalg.norm(a - b))
def dist_x1_only(a: np.ndarray, b: np.ndarray) -> float:
return float(abs(a[0] - b[0])) # tylko różnica po x1
# ====== Funkcje pomocnicze: podsumowania i wykresy ======
def cluster_summary(X: np.ndarray, labels: np.ndarray, centers: np.ndarray) -> pd.DataFrame:
rows = []
k = centers.shape[0]
for j in range(k):
members = X[labels == j]
count = len(members)
if count > 0:
x1min, x1max = members[:, 0].min(), members[:, 0].max()
x2min, x2max = members[:, 1].min(), members[:, 1].max()
else:
x1min = x1max = x2min = x2max = np.nan
rows.append(
{
"cluster": j,
"center_x1": centers[j, 0],
"center_x2": centers[j, 1],
"count": count,
"min_x1": x1min,
"max_x1": x1max,
"min_x2": x2min,
"max_x2": x2max,
}
)
return pd.DataFrame(rows).sort_values("cluster").reset_index(drop=True)
def plot_clusters(X: np.ndarray, labels: np.ndarray, centers: np.ndarray, title: str, out_path: Path):
plt.figure()
# (Zgodnie z wytycznymi: bez ustawiania stylów/kolorów; każdy wykres osobno)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=20)
plt.scatter(centers[:, 0], centers[:, 1], marker="X", s=200)
plt.xlabel("x1")
plt.ylabel("x2")
plt.title(title)
plt.tight_layout()
plt.savefig(out_path)
plt.close()
# ====== Raport 1: K-means (euklidesowa), k=3; snapshoty po 4 i 10 ======
snap_euclid = kmeans_custom(X, k=3, iters=10, dist=dist_euclidean, seed=123, snapshot_iters=(4,))
euclid_iter4 = snap_euclid[4]
euclid_iter10 = snap_euclid[10]
summary_euclid_4 = cluster_summary(X, euclid_iter4["labels"], euclid_iter4["centers"])
summary_euclid_10 = cluster_summary(X, euclid_iter10["labels"], euclid_iter10["centers"])
# Zapisy
OUT = Path("./wyniki_grupowanie_bez_fcm")
OUT.mkdir(parents=True, exist_ok=True)
summary_euclid_4.to_csv(OUT / "kmeans_euclid_iter4_summary.csv", index=False)
summary_euclid_10.to_csv(OUT / "kmeans_euclid_iter10_summary.csv", index=False)
plot_clusters(X, euclid_iter4["labels"], euclid_iter4["centers"], "K-means (Euclidean) – iter 4, k=3", OUT / "kmeans_euclid_iter4.png")
plot_clusters(X, euclid_iter10["labels"], euclid_iter10["centers"], "K-means (Euclidean) – iter 10, k=3", OUT / "kmeans_euclid_iter10.png")
# ====== Raport 2: K-means z metryką |x1_A - x1_B|, k=4; iteracje=10; wykres po 4 ======
snap_x1 = kmeans_custom(X, k=4, iters=10, dist=dist_x1_only, seed=456, snapshot_iters=(4,))
x1_iter4 = snap_x1[4]
x1_iter10 = snap_x1[10]
summary_x1_10 = cluster_summary(X, x1_iter10["labels"], x1_iter10["centers"])
summary_x1_10.to_csv(OUT / "kmeans_x1_iter10_summary.csv", index=False)
plot_clusters(X, x1_iter4["labels"], x1_iter4["centers"], "K-means (|x1 difference|) – iter 4, k=4", OUT / "kmeans_x1_iter4.png")
# ====== Krótka informacja w konsoli ======
print("Zapisano wyniki do folderu:", OUT.resolve())
print("- kmeans_euclid_iter4_summary.csv")
print("- kmeans_euclid_iter10_summary.csv")
print("- kmeans_euclid_iter4.png")
print("- kmeans_euclid_iter10.png")
print("- kmeans_x1_iter10_summary.csv")
print("- kmeans_x1_iter4.png")
}
)
}
)
]Editor is loading...
Leave a Comment