DBSCAN聚类
2020-06-27 本文已影响0人
还闹不闹
#!/usr/bin/python
# coding=utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cluster import KMeans, DBSCAN
# 画图支持中文显示
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 负号
plt.rcParams['axes.unicode_minus'] = False
# 显示所有列
pd.set_option('display.max_columns', None)
# 显示所有行
pd.set_option('display.max_rows', None)
# 设置value的显示长度为10000,默认为50
pd.set_option('display.width',10000)
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
#
np.set_printoptions(linewidth=1000)
# %matplotlib inline
# 造数据
X1, y1 = datasets.make_circles(n_samples=5000, factor=.6, noise=.05, random_state=9) # 非凸
X2, y2 = datasets.make_blobs(n_samples=1000, n_features=2, centers=[[1.2,1.2]], cluster_std=[[.1]], random_state=9) # 凸
'''DBSCAN在非凸数据聚类上有优势'''
print(type(X1), type(y2))
print('X1:\n', X1[0:3], '\ny1:\n', y1[0:3], '\nX2:\n', X2[0:3], '\ny2:\n', y2[0:3])
X = np.concatenate((X1, X2))
Y = np.concatenate((y1, y2))
print('X:\n', X[0:3], '\nY:\n', Y[0:3])
plt.scatter(X[:, 0], X[:, 1], marker='o')
plt.show()
# k-means
y_pred = KMeans(n_clusters=3, random_state=9).fit_predict(X)
plt.figure()
plt.title('k-means聚类')
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.savefig('G:\\rnn\k-means聚类.png')
plt.show()
# DBSCAN
y_pred = DBSCAN(eps=0.1, min_samples=10).fit_predict(X) # 减少ϵ-邻域的大小,默认是0.5,减到0.1
plt.figure()
plt.title('DBSCAN聚类')
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.savefig('G:\\rnn\DBSCAN聚类.png')
plt.show()
G:\rasa_demo\decision_tree\venv\Scripts\python.exe G:/rasa_demo/decision_tree/dbscan.py
<class 'numpy.ndarray'> <class 'numpy.ndarray'>
X1:
[[-0.86315295 0.47850988]
[ 0.7739279 -0.72241513]
[ 0.60629645 0.24250833]]
y1:
[0 0 1]
X2:
[[1.23974288 1.36597036]
[1.19910822 1.35391397]
[1.11447743 1.20255205]]
y2:
[0 0 0]
X:
[[-0.86315295 0.47850988]
[ 0.7739279 -0.72241513]
[ 0.60629645 0.24250833]]
Y:
[0 0 1]
Process finished with exit code 0