import numpy as np
import os
import matplotlib
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
np.random.seed(42)
from sklearn.datasets import make_blobs
# 指定五个中心,构造数据
blob_centers = np.array(
[[0.2, 2.3],
[-1.5, 2.3],
[-2.8, 1.8],
[-2.8, 2.8],
[-2.8, 1.3]])
blob_std = np.array([0.4, 0.3, 0.1, 0.1, 0.1]) # 发散程度不那么大
# 样本个数,中心点,发散程度
x, y = make_blobs(n_samples=2000,
centers=blob_centers,
cluster_std=blob_std,
random_state=7)
# print(x,y)
def plot_clusters(x, y=None):
plt.scatter(x[:, 0], x[:, 1], c=y, s=1)
plt.xlabel('$x_1$', fontsize=14)
plt.ylabel('$x_2$', fontsize=14, rotation=0)
# plt.figure(figsize=(8,4))
# plot_clusters(x)
# plt.show()
# 决策边界
from sklearn.cluster import KMeans
k = 5 # 五个簇
kmeans = KMeans(n_clusters=k, random_state=42)
# 训练并且得到预测结果
y_predict = kmeans.fit_predict(x)
# 预测值
print('y_pre:\n', y_predict)
# 标签值
print('labels:\n', kmeans.labels_)
# 中心点
print('center:\n', kmeans.cluster_centers_)
# 构造一组测试集
x_new = np.array([[0, 2], [3, 2], [-3, 3], [-3, 2.5]])
# 预测点所属的类(已经训练过了)
y_predict_new = kmeans.predict(x_new)
print(y_predict_new)
# transform 可以看一个点到各个中心点的距离
x_new_f = kmeans.transform(x_new)
print('x_new_f:\n', x_new_f)
# 可视化数据
def plot_data(x):
plt.plot(x[:, 0], x[:, 1], 'k.', markersize=2)
# 画centroids中心点
def plot_centroids(centroids, weights=None, circle_color='w', cross_color='k'):
if weights is not None:
centroids = centroids[weights > weights.max() / 10]
#画那个底色
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='o', s=30, linewidths=8,
color=circle_color, zorder=10, alpha=0.9)
#h画上面的叉
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=50, linewidths=5,
color=cross_color, zorder=11, alpha=1)
# 画决策边界
# 参数:clusterer 聚类的方法,例如kmeans;x 数据啊;resolustion,数据细化程度,show—就是否调用呗
def plot_decision_boundaries(clusterer, x, resolustion=1000, show_centroids=True,
show_xlabels=True, show_ylabels=True):
# 取这个用来画网格的
mins = x.min(axis=0) - 0.1
maxs = x.max(axis=0) + 0.1
print(mins, maxs)
xx, yy = np.meshgrid(np.linspace(mins[0], maxs[0], resolustion),
np.linspace(mins[1], maxs[1], resolustion))
z = clusterer.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
# 绘制区域颜色,不绘制等高线
plt.contourf(z, extent=(mins[0], maxs[0], mins[1], maxs[1]),
cmap='Pastel2')
# 绘制等高线,不绘制区域颜色
plt.contour(z, extent=(mins[0], maxs[0], mins[1], maxs[1]),
linewidths=1, colors='k')
# 画数据
plot_data(x)
# 画中心点
if show_centroids:
plot_centroids(clusterer.cluster_centers_)
# x坐标
if show_xlabels:
plt.xlabel('$x_1$', fontsize=14)
else:
plt.tick_params(labelbottom='off')
# y坐标
if show_ylabels:
plt.ylabel('$x_2$', fontsize=14, rotation=0)
else:
plt.tick_params(labelleft='off')
plt.figure(figsize=(8, 4))
plot_decision_boundaries(kmeans, x)
plt.show()
# 算法流程
# 簇类5,init随机初始化,n_init跑的次数,取最好的一次,最多迭代次数
k1 = KMeans(n_clusters=5, init='random', n_init=1, max_iter=1, random_state=1)
k2 = KMeans(n_clusters=5, init='random', n_init=1, max_iter=2, random_state=1)
k3 = KMeans(n_clusters=5, init='random', n_init=1, max_iter=3, random_state=1)
k1.fit(x)
k2.fit(x)
k3.fit(x)
# 第一步执行一次,分别画一个数据预测图,一个决策边界图
plt.figure(figsize=(10, 8))
plt.subplot(321) # 三行两列第一个
plot_data(x)
plot_centroids(k1.cluster_centers_,circle_color='r')
plt.title('update center')
plt.subplot(322) # 三行两列第二个
plot_data(x)
plot_decision_boundaries(k1,x,show_centroids=True,show_xlabels=False,show_ylabels=False)
plt.title('update label')
#第二步
plt.subplot(323) # 对比图
plot_data(x)
plot_decision_boundaries(k1,x,show_centroids=True,show_xlabels=False,show_ylabels=False)
plot_centroids(k2.cluster_centers_)
plt.subplot(324) # 三行两列
plot_data(x)
plot_decision_boundaries(k2,x,show_centroids=True,show_xlabels=False,show_ylabels=False)
#第三步更新
plt.subplot(325) # 三行两列第一个
plot_data(x)
plot_decision_boundaries(k3,x,show_centroids=True,show_xlabels=False,show_ylabels=False)
plot_centroids(k2.cluster_centers_)
plt.subplot(326) # 三行两列第二个
plot_data(x)
plot_decision_boundaries(k3,x,show_centroids=True,show_xlabels=False,show_ylabels=False)
plt.show()
but....参考的网址实在是忘记了 当时没复制