• sklearn机器学习——day07


    无监督学习:聚类,分类

    聚类算法又叫做“无监督分类”,其目的是将数据划分成有意义或有用的组(或簇)

     

     sklearn当中的聚类算法

    有两种表现形式:类、函数

    KMeans是如何工作的

     

     

     重要参数n_clusters

    n_clusters是KMeans中的k,表示着我们告诉模型我们要分几类。这是KMeans当中唯一一个必填的参数,默认为8 类,但通常我们的聚类结果会是一个小于8的结果。通常,在开始聚类之前,我们并不知道n_clusters究竟是多少, 因此我们要对它进行探索。

    1. #创建一个数据集
    2. from sklearn.datasets import make_blobs
    3. import matplotlib.pyplot as plt
    4. #自己创建数据集
    5. X, y = make_blobs(n_samples=500,n_features=2,centers=4,random_state=1)
    6. fig, ax1 = plt.subplots(1)
    7. ax1.scatter(X[:, 0], X[:, 1]
    8. ,marker='o' #点的形状
    9. ,s=8 #点的大小
    10. )
    11. plt.show()
    12. #如果我们想要看见这个点的分布,怎么办?
    13. color = ["red","pink","orange","gray"]
    14. fig, ax1 = plt.subplots(1)
    15. for i in range(4):
    16. ax1.scatter(X[y==i, 0], X[y==i, 1]
    17. ,marker='o' #点的形状
    18. ,s=8 #点的大小
    19. ,c=color[i]
    20. )
    21. plt.show()
    22. #基于这个分布,我们来使用Kmeans进行聚类
    23. from sklearn.cluster import KMeans
    24. n_clusters = 3
    25. cluster = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
    26. y_pred = cluster.labels_
    27. y_pred
    28. pre = cluster.fit_predict(X)
    29. pre == y_pred
    30. cluster_smallsub = KMeans(n_clusters=n_clusters, random_state=0).fit(X[:200])
    31. y_pred_ = cluster_smallsub.predict(X)
    32. y_pred == y_pred_
    33. centroid = cluster.cluster_centers_
    34. centroid
    35. centroid.shape
    36. inertia = cluster.inertia_
    37. inertia
    38. color = ["red","pink","orange","gray"]
    39. fig, ax1 = plt.subplots(1)
    40. for i in range(n_clusters):
    41. ax1.scatter(X[y_pred==i, 0], X[y_pred==i, 1]
    42. ,marker='o'
    43. ,s=8
    44. ,c=color[i]
    45. )
    46. ax1.scatter(centroid[:,0],centroid[:,1]
    47. ,marker="x"
    48. ,s=15
    49. ,c="black")
    50. plt.show()
    51. n_clusters = 4
    52. cluster_ = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
    53. inertia_ = cluster_.inertia_
    54. inertia_
    55. n_clusters = 5
    56. cluster_ = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
    57. inertia_ = cluster_.inertia_
    58. inertia_
    59. n_clusters = 6
    60. cluster_ = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
    61. inertia_ = cluster_.inertia_
    62. inertia_

     案例:轮廓系数找最佳n_clusters

    1. from sklearn.cluster import KMeans
    2. from sklearn.metrics import silhouette_samples, silhouette_score
    3. import matplotlib.pyplot as plt
    4. import matplotlib.cm as cm
    5. import numpy as np
    6. n_clusters = 4
    7. fig, (ax1, ax2) = plt.subplots(1, 2)
    8. fig.set_size_inches(18, 7)
    9. ax1.set_xlim([-0.1, 1])
    10. ax1.set_ylim([0, X.shape[0] + (n_clusters + 1) * 10])
    11. clusterer = KMeans(n_clusters=n_clusters, random_state=10).fit(X)
    12. cluster_labels = clusterer.labels_
    13. silhouette_avg = silhouette_score(X, cluster_labels)
    14. print("For n_clusters =", n_clusters,
    15. "The average silhouette_score is :", silhouette_avg)
    16. sample_silhouette_values = silhouette_samples(X, cluster_labels)
    17. y_lower = 10
    18. for i in range(n_clusters):
    19. ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]
    20. ith_cluster_silhouette_values.sort()
    21. size_cluster_i = ith_cluster_silhouette_values.shape[0]
    22. y_upper = y_lower + size_cluster_i
    23. color = cm.nipy_spectral(float(i)/n_clusters)
    24. ax1.fill_betweenx(np.arange(y_lower, y_upper)
    25. ,ith_cluster_silhouette_values
    26. ,facecolor=color
    27. ,alpha=0.7
    28. )
    29. ax1.text(-0.05
    30. , y_lower + 0.5 * size_cluster_i
    31. , str(i))
    32. y_lower = y_upper + 10
    33. ax1.set_title("The silhouette plot for the various clusters.")
    34. ax1.set_xlabel("The silhouette coefficient values")
    35. ax1.set_ylabel("Cluster label")
    36. ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
    37. ax1.set_yticks([])
    38. ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
    39. colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
    40. ax2.scatter(X[:, 0], X[:, 1]
    41. ,marker='o'
    42. ,s=8
    43. ,c=colors
    44. )
    45. centers = clusterer.cluster_centers_
    46. # Draw white circles at cluster centers
    47. ax2.scatter(centers[:, 0], centers[:, 1], marker='x',
    48. c="red", alpha=1, s=200)
    49. ax2.set_title("The visualization of the clustered data.")
    50. ax2.set_xlabel("Feature space for the 1st feature")
    51. ax2.set_ylabel("Feature space for the 2nd feature")
    52. plt.suptitle(("Silhouette analysis for KMeans clustering on sample data "
    53. "with n_clusters = %d" % n_clusters),
    54. fontsize=14, fontweight='bold')
    55. plt.show()

    重要参数init & random_state & n_init:让初始质心放好 

    重要参数max_iter & tol:让迭代停下来

    案例:Kmeans做矢量量化 

    非结构化数据往往占用比较 多的储存空间,文件本身也会比较大,运算非常缓慢,我们希望能够在保证数据质量的前提下,尽量地缩小非结构 化数据的大小,或者简化非结构化数据的结构。矢量量化就可以帮助我们实现这个目的。即压缩大小

    1. #导入需要的库
    2. import numpy as np
    3. import matplotlib.pyplot as plt
    4. from sklearn.cluster import KMeans
    5. from sklearn.metrics import pairwise_distances_argmin
    6. from sklearn.datasets import load_sample_image
    7. from sklearn.utils import shuffle
    8. #导入数据,探索数据
    9. china = load_sample_image("china.jpg")
    10. china
    11. china.dtype
    12. china.shape
    13. china[0][0]
    14. newimage = china.reshape((427 * 640,3))
    15. import pandas as pd
    16. pd.DataFrame(newimage).drop_duplicates().shape
    17. plt.figure(figsize=(15,15))
    18. plt.imshow(china)
    19. flower = load_sample_image("flower.jpg")
    20. plt.figure(figsize=(15,15))
    21. plt.imshow(flower)
    22. #决定超参数,数据预处理
    23. n_clusters = 64
    24. china = np.array(china, dtype=np.float64) / china.max()
    25. w, h, d = original_shape = tuple(china.shape)
    26. assert d == 3
    27. image_array = np.reshape(china, (w * h, d))
    28. china = np.array(china, dtype=np.float64) / china.max()
    29. w, h, d = original_shape = tuple(china.shape)
    30. w
    31. h
    32. d
    33. assert d == 3
    34. d_ = 5
    35. assert d_ == 3, "一个格子中的特征数目不等于3种"
    36. image_array = np.reshape(china, (w * h, d))
    37. image_array
    38. image_array.shape
    39. a = np.random.random((2,4))
    40. a
    41. a.reshape((4,2))
    42. np.reshape(a,(4,2))
    43. np.reshape(a,(2,2,2))
    44. np.reshape(a,(3,2))
    45. #对数据进行K-Means的矢量量化
    46. image_array_sample = shuffle(image_array, random_state=0)[:1000]
    47. kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(image_array_sample)
    48. kmeans.cluster_centers_
    49. labels = kmeans.predict(image_array)
    50. labels.shape
    51. image_kmeans = image_array.copy()
    52. for i in range(w*h):
    53. image_kmeans[i] = kmeans.cluster_centers_[labels[i]]
    54. image_kmeans
    55. pd.DataFrame(image_kmeans).drop_duplicates().shape
    56. image_kmeans = image_kmeans.reshape(w,h,d)
    57. image_kmeans.shape
    58. #对数据进行随机的矢量量化
    59. centroid_random = shuffle(image_array, random_state=0)[:n_clusters]
    60. labels_random = pairwise_distances_argmin(centroid_random,image_array,axis=0)
    61. labels_random.shape
    62. len(set(labels_random))
    63. image_random = image_array.copy()
    64. for i in range(w*h):
    65. image_random[i] = centroid_random[labels_random[i]]
    66. image_random = image_random.reshape(w,h,d)
    67. image_random.shape
    68. # 将原图,按KMeans矢量量化和随机矢量量化的图像绘制出来
    69. plt.figure(figsize=(10,10))
    70. plt.axis('off')
    71. plt.title('Original image (96,615 colors)')
    72. plt.imshow(china)
    73. plt.figure(figsize=(10,10))
    74. plt.axis('off')
    75. plt.title('Quantized image (64 colors, K-Means)')
    76. plt.imshow(image_kmeans)
    77. plt.figure(figsize=(10,10))
    78. plt.axis('off')
    79. plt.title('Quantized image (64 colors, Random)')
    80. plt.imshow(image_random)
    81. plt.show()

     

     

  • 相关阅读:
    kubernetesr进阶--污点和容忍之概述
    固定时间刷新算法
    查询自己电脑能够支持Win11系统升级的方法分享
    JMETER 后置处理器之正则表达式提取器
    源码分析:深入了解 equals、 ==、 hashcode
    国产MCU芯片(2):东软MCU概览
    bp神经网络模型拓扑结构,bp神经网络模型的建立
    都说测试行业饱和了,为什么我们公司给初级测试开到了12K?
    金现代产品方案部部长王宁,将出席“ISIG-低代码/零代码技术与应用发展峰会”
    C#:实现折半插入排序算法(附完整源码)
  • 原文地址:https://blog.csdn.net/weixin_44267765/article/details/126851766