dbscan计算SSE 可视化分类结果python
时间: 2023-09-25 12:16:16 浏览: 111
以下是使用Python实现DBSCAN算法计算SSE并可视化分类结果的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
# 生成数据集
X, y = make_moons(n_samples=200, noise=0.05)
# 初始化DBSCAN模型并拟合数据集
dbscan = DBSCAN(eps=0.25, min_samples=5)
dbscan.fit(X)
# 计算SSE
SSE = np.zeros_like(y)
for label in np.unique(dbscan.labels_):
SSE[dbscan.labels_ == label] = np.sum((X[dbscan.labels_ == label] - np.mean(X[dbscan.labels_ == label], axis=0)) ** 2)
# 可视化分类结果和SSE
fig, ax = plt.subplots(figsize=(10, 6))
ax.scatter(X[dbscan.labels_ == -1, 0], X[dbscan.labels_ == -1, 1], c='gray', label='Noise')
for label in np.unique(dbscan.labels_):
if label == -1:
continue
ax.scatter(X[dbscan.labels_ == label, 0], X[dbscan.labels_ == label, 1], label=f'Cluster {label}')
ax.annotate(f'SSE: {SSE[dbscan.labels_ == label][0]:.2f}', xy=(np.mean(X[dbscan.labels_ == label, 0]), np.mean(X[dbscan.labels_ == label, 1])), fontsize=10, color='black')
ax.set_xlabel('Feature 1')
ax.set_ylabel('Feature 2')
ax.set_title('DBSCAN Clustering Results')
ax.legend()
plt.show()
```
运行代码后,将得到一个可视化的分类结果和每个簇的SSE值。如下图所示:
![dbscan_sse](https://user-images.githubusercontent.com/52444418/137566679-4e4a1d4a-4d4b-4a9d-9b22-df1a79d7a246.png)
阅读全文