生成一些数据

1.导入sklearn的包和画图的包

from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt

2.生成数据

x, y = make_blobs(n_features=2,n_samples=1000, centers=[[-2,-2],[-1,-1],[0,0],[1,1]],cluster_std=[0.4,0.2,0.2,0.2])#cluster_std是这四个中心点的离散程度

3.查看x

x

4.查看y

y#y是目标值,是分类的数据!!!

5.看一下点的分布 散点图

plt.figure(figsize = (20,8))
plt.scatter(x[:,0],x[:,1],c=y)#按照y来画不一样颜色的散点图
plt.show()

聚类

from sklearn.cluster import KMeans

Kmeans进行分类

1.建立模型

estimator = KMeans(n_clusters=4)

2.训练模型

estimator.fit(x)#无监督学习,【注意训练的时候只传递特征值,不需要目标值】,y是目标值,是分类的数据!!!

3.获取分类结果

y_predict = estimator.predict(x)
y_predict

4.绘制分类结果散点图

plt.figure(figsize=(20,8))
plt.scatter(x[:,0],x[:,1],c = y_predict)
plt.show()

尝试分成三类

1.建立模型

estimator = KMeans(n_clusters=3)

2.训练模型

estimator.fit(x)

3.结果

y_predict = estimator.predict(x)

4.绘图查看

plt.figure(figsize = (20,8))
plt.scatter(x[:,0],x[:,1],c = y_predict)
plt.show()


可以看出效果不好,所以改用聚类为3类比较好