# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2024.3.6 python 3.11
# os : windows 10
# database : mysql 9.0 sql server 2025, postgreSQL 18.0 Oracle 21c Neo4j
# Datetime : 2026/12/2 21:25
# User : geovindu
# Product : PyCharm
# Project : Pysimple
# File : dbscan.py
"""深圳二手房均价(2000-2026 代表性年份)× DBSCAN 密度聚类示例
任务对应:
1) 复用同一份深圳均价数据(元/㎡)
2) DBSCAN:密度聚类,核心点 / 边界点 / 噪声点;不用预先指定 K;能识别离群点与任意形状簇
示例包含四块:
A. k-距离曲线选 eps:DBSCAN 只有 eps 与 min_samples 两个关键参数,先把 eps 选出来
B. 价格数据的密度聚类:标出核心点 / 边界点 / 噪声点,看哪些年份被判为离群,
并与 K-Means(K=3) 与人工三档做一致性对照(ARI)
C. eps × min_samples 网格:证明「簇数不是用户给的,是密度算出来的」
D. 合成数据(已标注):两个半月形 + 均匀噪声,K-Means 切错、DBSCAN 切对------任意形状与离群识别
运行:
python dbscan.py
产物:
outputs/db_grid.csv eps × min_samples 网格(簇数 / 噪声点数 / ARI)
outputs/db_points.csv 每个年份的点类型(核心 / 边界 / 噪声)与所属簇
outputs/db_kdist.png k-距离曲线(选 eps 的常用办法)
outputs/db_result.png 密度聚类结果:三类点 + eps 邻域示意
outputs/db_grid.png eps × min_samples 网格(簇数与噪声数热力图)
outputs/db_shapes.png 半月形合成数据:K-Means vs DBSCAN
outputs/db_metrics.json 指标汇总
"""
from __future__ import annotations
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import font_manager
from matplotlib.patches import Circle
from sklearn.cluster import DBSCAN, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler
BASE_DIR = Path(__file__).resolve().parent
DATA_PATH = BASE_DIR / "data" / "shenzhen_price_2000_2026.csv"
OUT_DIR = BASE_DIR / "outputs"
RANDOM_STATE = 42
FEATURES = ["年份", "均价_元每平米"]
MIN_SAMPLES = 3
PALETTE = ["#7ed321", "#f5a623", "#9b59f0", "#1f6fb2", "#d9674a", "#5bc0de"]
NOISE_COLOR = "#b0b0b0"
def setup_chinese_font() -> str:
"""
:return:
"""
candidates = ["Microsoft YaHei", "SimHei", "SimSun", "Noto Sans CJK SC", "Source Han Sans SC"]
available = {f.name for f in font_manager.fontManager.ttflist}
for name in candidates:
if name in available:
plt.rcParams["font.sans-serif"] = [name]
plt.rcParams["axes.unicode_minus"] = False
return name
for path in (r"C:/Windows/Fonts/msyh.ttc", r"C:/Windows/Fonts/simhei.ttf"):
if Path(path).exists():
font_manager.fontManager.addfont(path)
name = font_manager.FontProperties(fname=path).get_name()
plt.rcParams["font.sans-serif"] = [name]
plt.rcParams["axes.unicode_minus"] = False
return name
return ""
def k_distance_curve(X: np.ndarray, k: int) -> np.ndarray:
"""
每个点到第 k 个最近邻的距离,升序排列。
DBSCAN 的 eps 常按这条曲线的「拐点」取:拐点左侧是簇内的密集点(距离很小),
右侧是离群点(距离突然拉开)。取得比拐点小 → 大量点变噪声;取得大 → 簇会被连成一片。
:param X:
:param k:
:return:
"""
nn = NearestNeighbors(n_neighbors=k + 1).fit(X)
dist, _ = nn.kneighbors(X)
return np.sort(dist[:, k])
def knee_index(y: np.ndarray) -> int:
"""
用「到首尾连线的最大垂距」找拐点(kneedle 的简化版),返回拐点的下标。
:param y:
:return:
"""
n = len(y)
x = np.arange(n)
x0, y0, x1, y1 = x[0], y[0], x[-1], y[-1]
denom = np.hypot(x1 - x0, y1 - y0)
if denom == 0:
return int(np.argmax(y))
d = np.abs((y1 - y0) * x - (x1 - x0) * y + x1 * y0 - y1 * x0) / denom
return int(np.argmax(d))
def point_types(labels: np.ndarray, core_mask: np.ndarray) -> np.ndarray:
"""
把每个点分成 核心点 / 边界点 / 噪声点 三类。
:param labels:
:param core_mask:
:return:
"""
types = np.empty(len(labels), dtype=object)
for i, lab in enumerate(labels):
if lab == -1:
types[i] = "噪声点"
elif core_mask[i]:
types[i] = "核心点"
else:
types[i] = "边界点"
return types
def main() -> None:
"""
:return:
"""
OUT_DIR.mkdir(parents=True, exist_ok=True)
font_name = setup_chinese_font()
df = pd.read_csv(DATA_PATH).sort_values("年份").reset_index(drop=True)
X_raw = df[FEATURES].to_numpy(dtype=float)
manual_band = pd.cut(df["均价_元每平米"], bins=[0, 20000, 50000, np.inf],
labels=[0, 1, 2], right=False).astype(int).to_numpy()
print("=" * 90)
print("1. 数据({} 条,{}--{},单位元/㎡)".format(len(df), df["年份"].min(), df["年份"].max()))
print("-" * 90)
print(df[["年份", "均价_元每平米"]].to_string(index=False))
scaler = StandardScaler().fit(X_raw) # 与 K-Means 一样:先标准化,否则均价主导距离
X = scaler.transform(X_raw)
# ---------------------------------------------------------------- A. 选 eps
print("\n" + "=" * 90)
print("2. DBSCAN 的两个参数:eps(邻域半径)与 min_samples(成为核心点的最小邻居数)")
print("-" * 90)
print("它是「密度」聚类,不需要预设簇数,但必须给 eps。常用办法:画 k-距离曲线找拐点。")
kd = k_distance_curve(X, MIN_SAMPLES)
ki = knee_index(kd)
eps_seq = float(np.round(kd[ki], 3))
print("\nmin_samples = {},各点到第 {} 近邻的距离(升序):".format(MIN_SAMPLES, MIN_SAMPLES))
print(" {}".format(" ".join("{:.2f}".format(v) for v in kd)))
print(" 拐点在第 {} 个点(距离 {:.3f})→ 取 eps = {:.3f}".format(ki + 1, kd[ki], eps_seq))
print(" 经验:eps 取在拐点附近;偏小会把整段行程切成噪声,偏大会把两段连成一簇。")
# ---------------------------------------------------------------- B. 价格数据聚类
db = DBSCAN(eps=eps_seq, min_samples=MIN_SAMPLES).fit(X)
labels = db.labels_
core_mask = np.zeros(len(labels), dtype=bool)
core_mask[db.core_sample_indices_] = True
ptypes = point_types(labels, core_mask)
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = int((labels == -1).sum())
print("\n" + "=" * 90)
print("3. 聚类结果(eps={:.3f}, min_samples={}):簇数 {},噪声点 {} 个".format(
eps_seq, MIN_SAMPLES, n_clusters, n_noise))
print("-" * 90)
out = pd.DataFrame({
"年份": df["年份"],
"均价_元每平米": df["均价_元每平米"],
"点类型": ptypes,
"所属簇": labels,
"人工档位": [["低位", "中位", "高位"][m] for m in manual_band],
})
print(out.to_string(index=False))
out.to_csv(OUT_DIR / "db_points.csv", index=False, encoding="utf-8-sig")
if n_noise:
print("\n被判为噪声的年份:{}".format(
", ".join("{}({} 元/㎡)".format(y, p) for y, p in
zip(df.loc[labels == -1, "年份"], df.loc[labels == -1, "均价_元每平米"]))))
else:
print("\n拐点 eps 下没有噪声点:所有年份都能连到某一簇,代价是「中位那三年」被并进了相邻簇。")
print("把 eps 收紧一点就能看到噪声点冒出来,同时簇数也会变------这就是密度聚类的取舍:")
# 收紧 eps 再看一次:三类点(核心/边界/噪声)都会出现,簇数也更细
eps_zoom, ms_zoom = 0.40, 2
dbz = DBSCAN(eps=eps_zoom, min_samples=ms_zoom).fit(X)
labs_z = dbz.labels_
core_z = np.zeros(len(labs_z), dtype=bool)
core_z[dbz.core_sample_indices_] = True
ptypes_z = point_types(labs_z, core_z)
n_cl_z = len(set(labs_z)) - (1 if -1 in labs_z else 0)
nz_z = int((labs_z == -1).sum())
print("\n收紧后(eps={:.2f}, min_samples={}):簇数 {},噪声点 {} 个".format(eps_zoom, ms_zoom, n_cl_z, nz_z))
if nz_z:
print(" 噪声年份:{}(2014 年 28,117 元/㎡ 卡在低位段与中位段之间,两侧都不够密)".format(
", ".join(str(y) for y in df.loc[labs_z == -1, "年份"])))
mz = labs_z != -1
if n_cl_z >= 2 and mz.sum() > n_cl_z:
print(" 与人工三档 ARI(非噪声样本)= {:.3f}".format(
float(adjusted_rand_score(manual_band[mz], labs_z[mz]))))
print(" 各簇年份:{}".format(
"; ".join("簇{}={}".format(j, ",".join(str(y) for y in df.loc[labs_z == j, "年份"]))
for j in range(n_cl_z))))
# 与有监督的两种参照对照
km3 = KMeans(n_clusters=3, init="k-means++", n_init=10, random_state=RANDOM_STATE).fit(X)
mask = labels != -1
if n_clusters >= 2 and mask.sum() > n_clusters:
ari_db = float(adjusted_rand_score(manual_band[mask], labels[mask]))
sil_db = float(silhouette_score(X[mask], labels[mask]))
else:
ari_db, sil_db = float("nan"), float("nan")
print("\n与两种参照对照(注意 DBSCAN 的簇数不是预设的):")
print(" 与人工三档 ARI = {:.3f}(只在非噪声样本上算,{} 个样本)".format(ari_db, int(mask.sum())))
print(" 与 K-Means(K=3) 的 ARI = {:.3f}".format(float(adjusted_rand_score(km3.labels_, labels))))
print(" DBSCAN 轮廓系数 = {:.3f}(K-Means 为 {:.3f})".format(
sil_db, float(silhouette_score(X, km3.labels_))))
# ---------------------------------------------------------------- C. 网格:簇数由密度决定
print("\n" + "=" * 90)
print("4. eps × min_samples 网格:改变参数,簇数自己变------这就是「不用预先给 K」")
print("-" * 90)
eps_grid = np.round(np.arange(0.20, 1.61, 0.20), 2)
ms_grid = [2, 3, 4, 5]
grid_rows = []
for ms in ms_grid:
for e in eps_grid:
d = DBSCAN(eps=float(e), min_samples=ms).fit(X)
labs = d.labels_
c = len(set(labs)) - (1 if -1 in labs else 0)
nz = int((labs == -1).sum())
m = labs != -1
ari = (float(adjusted_rand_score(manual_band[m], labs[m]))
if c >= 2 and m.sum() > c else float("nan"))
grid_rows.append({"eps": float(e), "min_samples": ms, "簇数": c, "噪声点数": nz,
"与人工三档ARI(非噪声)": round(ari, 3) if ari == ari else None})
grid_df = pd.DataFrame(grid_rows)
grid_df.to_csv(OUT_DIR / "db_grid.csv", index=False, encoding="utf-8-sig")
pivot_c = grid_df.pivot(index="min_samples", columns="eps", values="簇数")
pivot_n = grid_df.pivot(index="min_samples", columns="eps", values="噪声点数")
print("簇数(行=min_samples,列=eps):")
print(pivot_c.to_string())
print("\n噪声点数:")
print(pivot_n.to_string())
print("\n读法:同一份数据、同一个算法,簇数从 1 变到 5,全由 eps/min_samples 决定。")
print("DBSCAN 的「不用预设 K」不等于「不用调参」------它把 K 换成了密度阈值。")
# ---------------------------------------------------------------- D. 任意形状(合成数据)
print("\n" + "=" * 90)
print("5. 任意形状:两个半月 + 均匀噪声(合成数据,仅用于展示算法差异)")
print("-" * 90)
rng = np.random.default_rng(RANDOM_STATE)
X_moon, y_moon = make_moons(n_samples=300, noise=0.06, random_state=RANDOM_STATE)
noise_pts = rng.uniform(X_moon.min(axis=0) - 0.1, X_moon.max(axis=0) + 0.1, size=(30, 2))
X_syn = np.vstack([X_moon, noise_pts])
y_syn = np.concatenate([y_moon, np.full(len(noise_pts), -1)]) # -1 标记噪声
km_syn = KMeans(n_clusters=2, init="k-means++", n_init=10, random_state=RANDOM_STATE).fit(X_syn)
db_syn = DBSCAN(eps=0.22, min_samples=5).fit(X_syn)
labs_syn = db_syn.labels_
n_cl_syn = len(set(labs_syn)) - (1 if -1 in labs_syn else 0)
core_syn = np.zeros(len(labs_syn), dtype=bool)
core_syn[db_syn.core_sample_indices_] = True
ari_km = float(adjusted_rand_score(y_syn[y_syn != -1], km_syn.labels_[y_syn != -1]))
m2 = (labs_syn != -1) & (y_syn != -1)
ari_db = float(adjusted_rand_score(y_syn[m2], labs_syn[m2]))
print("真实结构:2 个半月 + {} 个均匀噪声点,共 {} 个点".format(len(noise_pts), len(X_syn)))
print("K-Means(K=2):ARI(不含噪声)= {:.3f},且把 {} 个噪声点强行塞进两簇".format(ari_km, len(noise_pts)))
print("DBSCAN(eps=0.22, min_samples=5):找到 {} 个簇、{} 个噪声点,ARI(不含噪声)= {:.3f}".format(
n_cl_syn, int((labs_syn == -1).sum()), ari_db))
print("\n为什么 K-Means 会错:它优化「到中心的距离」,只能切出凸的、近似球形的簇;")
print("两个半月互相缠绕,任何一刀直线都切不开。DBSCAN 只看「邻域里够不够密」,沿着形状自己长过去。")
# ---------------------------------------------------------------- 图 1:k-距离
fig, ax = plt.subplots(figsize=(9, 4.6), dpi=160)
ax.plot(np.arange(1, len(kd) + 1), kd, marker="o", linewidth=1.6, color="#1f6fb2")
ax.axhline(eps_seq, color="#d9674a", linestyle="--", linewidth=1.2)
ax.scatter([ki + 1], [kd[ki]], s=120, facecolors="none", edgecolors="#d9674a", linewidths=2, zorder=4)
ax.annotate("拐点 → eps = {:.2f}".format(eps_seq), xy=(ki + 1, kd[ki]),
xytext=(ki + 1, kd[ki] + (kd.max() - kd.min()) * 0.18), fontsize=10, color="#d9674a")
ax.set_xlabel("样本(按到第 {} 近邻的距离升序)".format(MIN_SAMPLES))
ax.set_ylabel("到第 {} 近邻的距离".format(MIN_SAMPLES))
ax.set_title("k-距离曲线:拐点左边是簇内点,右边是离群点", fontsize=11)
ax.grid(alpha=0.3)
fig.tight_layout()
fig.savefig(OUT_DIR / "db_kdist.png", bbox_inches="tight")
plt.close(fig)
# ---------------------------------------------------------------- 图 2:结果 + 三类点
fig, axes = plt.subplots(1, 2, figsize=(13.5, 5.2), dpi=160)
ax = axes[0]
for j in range(n_clusters):
m = labels == j
ax.scatter(X_raw[m, 0], X_raw[m, 1], s=70, color=PALETTE[j], edgecolors="black",
linewidths=0.7, label="簇{}".format(j), zorder=3)
if n_noise:
m = labels == -1
ax.scatter(X_raw[m, 0], X_raw[m, 1], s=110, marker="X", color=NOISE_COLOR,
edgecolors="black", linewidths=0.8, label="噪声点", zorder=4)
for y, p in zip(df.loc[labels == -1, "年份"], df.loc[labels == -1, "均价_元每平米"]):
ax.annotate("{} 年\n{}".format(int(y), int(p)), xy=(y, p), xytext=(y - 2.4, p + 4200),
fontsize=8, color="#555",
arrowprops=dict(arrowstyle="-", color="#999", linewidth=0.8))
ax.set_xlabel("年份")
ax.set_ylabel("均价(元/㎡)")
ax.set_title("密度聚类结果(eps={:.2f}, min_samples={})".format(eps_seq, MIN_SAMPLES), fontsize=11)
ax.legend(fontsize=9)
ax.grid(alpha=0.25)
ax = axes[1]
# 用「收紧 eps 后」的结果来展示三类点:核心点、边界点、噪声点都会出现
for j in range(n_cl_z):
m = labs_z == j
ax.scatter(X_raw[m, 0], X_raw[m, 1], s=70, color=PALETTE[j], edgecolors="black",
linewidths=0.7, label="簇{}({} 个)".format(j, int(m.sum())), zorder=3)
core_pts = ptypes_z == "核心点"
border_pts = ptypes_z == "边界点"
noise_pts_mask = ptypes_z == "噪声点"
ax.scatter(X_raw[core_pts, 0], X_raw[core_pts, 1], s=190, facecolors="none",
edgecolors="#2e7d5b", linewidths=1.8, label="核心点(外圈实线)", zorder=2)
ax.scatter(X_raw[border_pts, 0], X_raw[border_pts, 1], s=190, facecolors="none",
edgecolors="#f5a623", linewidths=1.8, linestyles="--", label="边界点(外圈虚线)", zorder=2)
if noise_pts_mask.any():
ax.scatter(X_raw[noise_pts_mask, 0], X_raw[noise_pts_mask, 1], s=140, marker="X",
color=NOISE_COLOR, edgecolors="black", linewidths=1.0, label="噪声点", zorder=4)
for y, p in zip(df.loc[labs_z == -1, "年份"], df.loc[labs_z == -1, "均价_元每平米"]):
ax.annotate("{} 年".format(int(y)), xy=(y, p), xytext=(y - 3.2, p + 3000),
fontsize=8, color="#555",
arrowprops=dict(arrowstyle="-", color="#999", linewidth=0.8))
# eps 邻域示意(按「年份」方向的标准差把标准化半径换算回原始单位)
if noise_pts_mask.sum() < len(labs_z):
ci = int(np.where(~noise_pts_mask)[0][0])
r_year = eps_zoom * np.std(X_raw[:, 0])
ax.add_patch(Circle((X_raw[ci, 0], X_raw[ci, 1]), radius=r_year, fill=False,
edgecolor="#d9674a", linestyle="--", linewidth=1.2))
ax.annotate("eps 邻域\n(按年份方向换算,示意)", xy=(X_raw[ci, 0], X_raw[ci, 1]),
xytext=(X_raw[ci, 0] + 1.6, X_raw[ci, 1] + 9000), fontsize=8, color="#d9674a")
ax.set_xlabel("年份")
ax.set_ylabel("均价(元/㎡)")
ax.set_title("收紧 eps={:.2f} 后:{} 簇 + {} 个噪声点(核心/边界/噪声三态)".format(
eps_zoom, n_cl_z, nz_z), fontsize=10.5)
ax.legend(fontsize=7.5, loc="upper left")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig(OUT_DIR / "db_result.png", bbox_inches="tight")
plt.close(fig)
# ---------------------------------------------------------------- 图 3:网格
fig, axes = plt.subplots(1, 2, figsize=(13.5, 4.4), dpi=160)
for ax, pivot, title, cmap in [
(axes[0], pivot_c, "簇数(行=min_samples,列=eps)", "YlGnBu"),
(axes[1], pivot_n, "噪声点数", "OrRd"),
]:
im = ax.imshow(pivot.values, aspect="auto", cmap=cmap)
ax.set_xticks(range(len(pivot.columns)))
ax.set_xticklabels(["{:.2f}".format(c) for c in pivot.columns], rotation=45, fontsize=8)
ax.set_yticks(range(len(pivot.index)))
ax.set_yticklabels(pivot.index)
ax.set_xlabel("eps")
ax.set_ylabel("min_samples")
ax.set_title(title, fontsize=11)
for i in range(pivot.shape[0]):
for j in range(pivot.shape[1]):
v = pivot.values[i, j]
ax.text(j, i, int(v), ha="center", va="center", fontsize=9,
color="white" if v > pivot.values.max() * 0.6 else "#333")
fig.colorbar(im, ax=ax, fraction=0.04, pad=0.02)
fig.suptitle("同一份数据、同一个算法:簇数与噪声数完全由 eps / min_samples 决定", fontsize=12)
fig.tight_layout()
fig.savefig(OUT_DIR / "db_grid.png", bbox_inches="tight")
plt.close(fig)
# ---------------------------------------------------------------- 图 4:任意形状
fig, axes = plt.subplots(1, 2, figsize=(12.6, 5), dpi=160)
ax = axes[0]
ax.scatter(X_syn[:, 0], X_syn[:, 1], c=[PALETTE[i] if i >= 0 else "#888" for i in km_syn.labels_],
s=22, alpha=0.85, edgecolors="none")
ax.scatter(km_syn.cluster_centers_[:, 0], km_syn.cluster_centers_[:, 1], marker="X", s=200,
color="#111", edgecolors="white", linewidths=1.2, zorder=4)
ax.set_title("K-Means(K=2):只能直线切,半月被腰断\nARI(不含噪声)= {:.2f}".format(ari_km), fontsize=10.5)
ax.set_xticks([])
ax.set_yticks([])
ax = axes[1]
for j in range(n_cl_syn):
m = labs_syn == j
ax.scatter(X_syn[m, 0], X_syn[m, 1], color=PALETTE[j], s=22, alpha=0.85, edgecolors="none",
label="簇{}".format(j))
m = labs_syn == -1
ax.scatter(X_syn[m, 0], X_syn[m, 1], color=NOISE_COLOR, marker="X", s=40,
edgecolors="black", linewidths=0.5, label="噪声点({})".format(int(m.sum())))
ax.set_title("DBSCAN(eps=0.22, min_samples=5):沿密度长过去\n找到 {} 簇 + {} 个噪声,ARI = {:.2f}".format(
n_cl_syn, int(m.sum()), ari_db), fontsize=10.5)
ax.legend(fontsize=8, loc="upper right")
ax.set_xticks([])
ax.set_yticks([])
fig.suptitle("合成数据(两个半月 + 均匀噪声):任意形状簇与离群点识别", fontsize=12)
fig.tight_layout()
fig.savefig(OUT_DIR / "db_shapes.png", bbox_inches="tight")
plt.close(fig)
# ---------------------------------------------------------------- 落盘
metrics = {
"n_samples": int(len(df)),
"features": FEATURES,
"scaled": "StandardScaler(z-score)",
"eps": round(float(eps_seq), 4),
"min_samples": MIN_SAMPLES,
"n_clusters": int(n_clusters),
"n_noise": int(n_noise),
"noise_years": [int(y) for y in df.loc[labels == -1, "年份"]],
"point_types": {"核心点": int((ptypes == "核心点").sum()),
"边界点": int((ptypes == "边界点").sum()),
"噪声点": int((ptypes == "噪声点").sum())},
"ari_vs_manual_bands_non_noise": None if ari_db != ari_db else round(ari_db, 3),
"ari_vs_kmeans3": round(float(adjusted_rand_score(km3.labels_, labels)), 3),
"silhouette_dbscan_non_noise": None if sil_db != sil_db else round(sil_db, 3),
"silhouette_kmeans3": round(float(silhouette_score(X, km3.labels_)), 3),
"zoom_run": {
"eps": eps_zoom, "min_samples": ms_zoom, "n_clusters": int(n_cl_z), "n_noise": int(nz_z),
"noise_years": [int(y) for y in df.loc[labs_z == -1, "年份"]],
"point_types": {"核心点": int(core_pts.sum()), "边界点": int(border_pts.sum()),
"噪声点": int(noise_pts_mask.sum())},
"ari_vs_manual_bands_non_noise": (round(float(adjusted_rand_score(manual_band[mz], labs_z[mz])), 3)
if n_cl_z >= 2 and mz.sum() > n_cl_z else None),
},
"grid": grid_df.to_dict(orient="records"),
"synthetic": {
"n_points": int(len(X_syn)), "n_noise_injected": int(len(noise_pts)),
"kmeans_ari": round(ari_km, 3), "dbscan_ari": round(ari_db, 3),
"dbscan_clusters": int(n_cl_syn), "dbscan_noise": int((labs_syn == -1).sum()),
},
}
(OUT_DIR / "db_metrics.json").write_text(json.dumps(metrics, ensure_ascii=False, indent=2), encoding="utf-8")
print("\n已输出:db_grid.csv / db_points.csv / db_kdist.png / db_result.png / db_grid.png / "
"db_shapes.png / db_metrics.json")
print("matplotlib 中文字体:{}".format(font_name or "未找到,可能显示为方块"))
if __name__ == "__main__":
main()