{"id":1627,"date":"2019-09-10T17:21:17","date_gmt":"2019-09-10T09:21:17","guid":{"rendered":"http:\/\/www.sniper97.cn\/?p=1627"},"modified":"2019-09-10T17:21:17","modified_gmt":"2019-09-10T09:21:17","slug":"%e3%80%90%e6%9c%ba%e5%99%a8%e5%ad%a6%e4%b9%a0%e3%80%91k-means%e4%b8%8epca","status":"publish","type":"post","link":"http:\/\/www.sniper97.cn\/index.php\/note\/machine-learning-in-action\/1627\/","title":{"rendered":"\u3010\u5434\u6069\u8fbe\u673a\u5668\u5b66\u4e60\u3011K-means\u4e0ePCA"},"content":{"rendered":"\n<p>\u5434\u6069\u8fbe\u673a\u5668\u5b66\u4e60\u7b2c\u516b\u5468\uff1aK-means\u4e0ePCA\uff08K-means and PCA\uff09\u3002<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"370\" height=\"221\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-61.png\" alt=\"\" class=\"wp-image-1634\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-61.png 370w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-61-300x179.png 300w\" sizes=\"(max-width: 370px) 100vw, 370px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">1.\u4f7f\u7528K-means\u8fdb\u884c\u7c07\u5206\u7c7b<\/h2>\n\n\n<p>K-means\uff0c\u805a\u7c7b\u7b97\u6cd5\uff0c\u901a\u8fc7\u5bfb\u627e\u6700\u63a5\u8fd1\u5206\u7c7b\u4e2d\u5fc3\u7684\u70b9\u6765\u5bfb\u627e\u5206\u7c7b\u4e2d\u5fc3\u3002<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"477\" height=\"266\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-55.png\" alt=\"\" class=\"wp-image-1628\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-55.png 477w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-55-300x167.png 300w\" sizes=\"(max-width: 477px) 100vw, 477px\" \/><\/figure><\/div>\n\n\n<p>\u9996\u5148\u5bfc\u5305\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat<\/code><\/pre>\n\n\n<p>\u5c06\u70b9\u5206\u7c7b\uff08\u4f9d\u636e\u73b0\u6709\u5206\u7c7b\u4e2d\u5fc3\u70b9 \uff09\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>def findClosestCentroids(X, centroids):\n    \"\"\"\n    output a one-dimensional array idx that holds the\n    index of the closest centroid to every training example.\n    \u8f93\u51fa\u4e00\u4e2a\u4e00\u7ef4\u6570\u7ec4idx\uff0c\u5176\u4e2d\u5305\u542b\u6700\u63a5\u8fd1\u6bcf\u4e2a\u5206\u7c7b\u7684\u4e2d\u5fc3\u7684\u70b9\u96c6\u5408\u3002\n    :param X: \u6570\u636e\u70b9\n    :param centroids: \u5206\u7c7b\u4e2d\u5fc3\u70b9\n    :return:\n    \"\"\"\n    idx = []\n    max_dist = 1000000  # \u9650\u5236\u4e00\u4e0b\u6700\u5927\u8ddd\u79bb\n    for i in range(len(X)):\n        minus = X[i] - centroids  # \u8be5\u70b9\u4e0e\u4e09\u4e2a\u5206\u7c7b\u4e2d\u5fc3\u7684\u8ddd\u79bb\n        dist = minus[:, 0] ** 2 + minus[:, 1] ** 2  # \u8ba1\u7b97\u6b27\u51e0\u91cc\u5fb7\u8ddd\u79bb\n        if dist.min() &lt; max_dist:  # \u9650\u5236\u6700\u5927\u8ddd\u79bb\n            ci = np.argmin(dist)  # \u5bfb\u627e\u6700\u5c0f\u8ddd\u79bb\u7684\u70b9\n            idx.append(ci)\n    return np.array(idx)<\/code><\/pre>\n\n\n<p>\u8bfb\u53d6\u6570\u636e\uff0c\u8bbe\u5b9a\u4e09\u4e2a\u4e2d\u5fc3\u70b9\uff0c\u5206\u7c7b\u6570\u636e\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>mat = loadmat('data\/ex7data2.mat')\n# print(mat.keys())\nX = mat['X']\ninit_centroids = np.array([[3, 3], [6, 2], [8, 5]])\nidx = findClosestCentroids(X, init_centroids)\n# [0 2 1]\nprint(idx[0:3])<\/code><\/pre>\n\n\n<p>\u8ba1\u7b97\u65b0\u7684\u5206\u7c7b\u4e2d\u5fc3\u70b9\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>def computeCentroids(X, idx):\n    \"\"\"\n    \u8ba1\u7b97\u65b0\u7684\u5206\u7c7b\u4e2d\u5fc3\u70b9\n    :param X: \u6570\u636e\u70b9\n    :param idx: \u5206\u7c7b\u7684\u4e00\u7ef4\u6570\u7ec4\n    :return:\n    \"\"\"\n    centroids = []\n    for i in range(len(np.unique(idx))):  # \u904d\u5386\u6bcf\u4e00\u4e2ak\n        u_k = X[idx == i].mean(axis=0)  # \u6c42\u6bcf\u5217\u7684\u5e73\u5747\u503c\n        centroids.append(u_k)\n    return np.array(centroids)<\/code><\/pre>\n\n\n<p>\u6253\u5370\u7ed3\u679c\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>\"\"\"\n[[2.42830111 3.15792418]\n [5.81350331 2.63365645]\n [7.11938687 3.6166844 ]]\n\"\"\"\nprint(computeCentroids(X, idx))<\/code><\/pre>\n\n\n<p>\u753b\u56fe\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>def plotData(X, centroids, idx=None):\n    \"\"\"\n    \u53ef\u89c6\u5316\u6570\u636e\uff0c\u5e76\u81ea\u52a8\u5206\u5f00\u7740\u8272\u3002\n    :param X: \u539f\u59cb\u6570\u636e\n    :param centroids: \u5305\u542b\u6bcf\u6b21\u4e2d\u5fc3\u70b9\u5386\u53f2\u8bb0\u5f55\n    :param idx: \u6700\u540e\u4e00\u6b21\u8fed\u4ee3\u751f\u6210\u7684idx\u5411\u91cf\uff0c\u5b58\u50a8\u6bcf\u4e2a\u6837\u672c\u5206\u914d\u7684\u7c07\u4e2d\u5fc3\u70b9\u7684\u503c\n    :return:\n    \"\"\"\n    # \u989c\u8272\u5217\u8868\n    colors = ['b', 'g', 'gold', 'darkorange', 'salmon', 'olivedrab', 'maroon', 'navy', 'sienna', 'tomato', 'lightgray',\n              'gainsboro', 'coral', 'aliceblue', 'dimgray', 'mintcream', 'mintcream']\n    # \u65ad\u8a00\uff0c\u5982\u679c\u6761\u4ef6\u4e3a\u771f\u5c31\u6b63\u5e38\u8fd0\u884c\uff0c\u6761\u4ef6\u4e3a\u5047\u5c31\u51fa\u53d1\u5f02\u5e38\n    assert len(centroids[0]) &lt;= len(colors), 'colors not enough '\n    subX = []  # \u5206\u53f7\u7c7b\u7684\u6837\u672c\u70b9\n    if idx is not None:\n        for i in range(centroids[0].shape[0]):\n            x_i = X[idx == i]\n            subX.append(x_i)\n    else:\n        subX = [X]  # \u5c06X\u8f6c\u5316\u4e3a\u4e00\u4e2a\u5143\u7d20\u7684\u5217\u8868\uff0c\u6bcf\u4e2a\u5143\u7d20\u4e3a\u6bcf\u4e2a\u7c07\u7684\u6837\u672c\u96c6\uff0c\u65b9\u4fbf\u4e0b\u65b9\u7ed8\u56fe\n    # \u5206\u522b\u753b\u51fa\u6bcf\u4e2a\u7c07\u7684\u70b9\uff0c\u5e76\u7740\u4e0d\u540c\u7684\u989c\u8272\n    plt.figure(figsize=(8, 5))\n    for i in range(len(subX)):\n        xx = subX[i]\n        plt.scatter(xx[:, 0], xx[:, 1], c=colors[i], label='Cluster %d' % i)\n    plt.legend()\n    plt.grid(True)\n    plt.xlabel('x1', fontsize=14)\n    plt.ylabel('x2', fontsize=14)\n    plt.title('Plot of X Points', fontsize=16)\n    # \u753b\u51fa\u7c07\u4e2d\u5fc3\u70b9\u7684\u79fb\u52a8\u8f68\u8ff9\n    xx, yy = [], []\n    for centroid in centroids:\n        xx.append(centroid[:, 0])\n        yy.append(centroid[:, 1])\n    plt.plot(xx, yy, 'rx--', markersize=8)\n    plt.show()\nplotData(X, [init_centroids])<\/code><\/pre>\n\n\n<p>\u53ef\u4ee5\u770b\u5230\u6211\u4eec\u521d\u59cb\u5316\u7684\u4e09\u4e2a\u5206\u7c7b\u4e2d\u5fc3\u70b9\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"451\" height=\"280\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-56.png\" alt=\"\" class=\"wp-image-1629\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-56.png 451w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-56-300x186.png 300w\" sizes=\"(max-width: 451px) 100vw, 451px\" \/><\/figure><\/div>\n\n\n<p>\u7136\u540e\u6267\u884cK-means\u7b97\u6cd5\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>def runKmeans(X, centroids, max_iters):\n    \"\"\"\n    \u6267\u884ck-\u5747\u503c\u7b97\u6cd5\n    :param X:  \u539f\u59cb\u6570\u636e\n    :param centroids: \u4e2d\u5fc3\u70b9\n    :param max_iters:\u6700\u5927\u8fed\u4ee3\u6b21\u6570\n    :return:\n    \"\"\"\n    # k  \uff0c\u867d\u7136\u6ca1\u5565\u7528\n    K = len(centroids)\n    # \u6240\u6709\u7684\u70b9\uff08\u591a\u6b21\u8fed\u4ee3\uff09\n    centroids_all = []\n    centroids_all.append(centroids)\n    centroid_i = centroids\n    for i in range(max_iters):\n        idx = findClosestCentroids(X, centroid_i)\n        centroid_i = computeCentroids(X, idx)\n        centroids_all.append(centroid_i)\n    return idx, centroids_all\nidx, centroids_all = runKmeans(X, init_centroids, 20)\nplotData(X, centroids_all, idx)<\/code><\/pre>\n\n\n<p>\u5206\u7c7b\u7ed3\u679c\u4ee5\u53ca\u5206\u7c7b\u4e2d\u5fc3\u70b9\u53d8\u5316\u7684\u8fc7\u7a0b\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"451\" height=\"275\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-57.png\" alt=\"\" class=\"wp-image-1630\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-57.png 451w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-57-300x183.png 300w\" sizes=\"(max-width: 451px) 100vw, 451px\" \/><\/figure><\/div>\n\n\n<p>\u4e0b\u9762\u662f\u968f\u673a\u521d\u59cb\u5316\u548c\u8fdb\u884c\u4e09\u6b21\u7684\u7ed3\u679c\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code>def initCentroids(X, K):\n    \"\"\"\n    \u968f\u673a\u521d\u59cb\u5316\n    :param X:\n    :param K:\n    :return:\n    \"\"\"\n    m, n = X.shape\n    idx = np.random.choice(m, K)  # \u968f\u673a\u4ecem\u4e2d\u9009\u62e9k\u4e2a\n    centroids = X[idx]\n    return centroids\n# \u968f\u673a\u5bfb\u627e\u4e09\u4e2a\u968f\u673a\u521d\u59cb\u4e2d\u5fc3\nfor i in range(3):\n    centroids = initCentroids(X, 3)\n    idx, centroids_all = runKmeans(X, centroids, 10)\n    plotData(X, centroids_all, idx)<\/code><\/pre>\n\n\n<p>\u4e09\u5f20\u56fe\u5206\u522b\u4e3a\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"451\" height=\"276\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-58.png\" alt=\"\" class=\"wp-image-1631\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-58.png 451w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-58-300x184.png 300w\" sizes=\"(max-width: 451px) 100vw, 451px\" \/><\/figure><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"445\" height=\"280\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-59.png\" alt=\"\" class=\"wp-image-1632\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-59.png 445w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-59-300x189.png 300w\" sizes=\"(max-width: 445px) 100vw, 445px\" \/><\/figure><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"449\" height=\"278\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-60.png\" alt=\"\" class=\"wp-image-1633\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-60.png 449w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-60-300x186.png 300w\" sizes=\"(max-width: 449px) 100vw, 449px\" \/><\/figure><\/div>\n\n\n<p>\u53ef\u4ee5\u770b\u51fa\u6548\u679c\u53c2\u5dee\u4e0d\u9f50\uff0c\u8fd9\u662f\u56e0\u4e3a\u521d\u59cb\u7684\u5206\u7c7b\u4e2d\u5fc3\u70b9\u7684\u9009\u62e9\u4e0d\u540c\uff0c\u5bfc\u81f4\u7ed3\u679c\u4e0d\u540c\u3002<\/p>\n\n\n<p>\u6574\u7406\u540e\u7684\u4ee3\u7801\uff1a<\/p>\n\n\n<pre class=\"wp-block-code\"><code># -*- coding:utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\ndef loadData():\n    \"\"\"\n    \u8bfb\u53d6\u6570\u636e\n    :return:\n    \"\"\"\n    mat = sio.loadmat('data\/ex7data2.mat')\n    X = mat['X']\n    return X, mat\ndef findClosestControids(X, centroids):\n    \"\"\"\n    \u5bfb\u627e\u91cc\u5206\u7c7b\u4e2d\u5fc3\u70b9\u6700\u8fd1\u7684\u70b9\u96c6\u5408\n    :param X: \u539f\u59cb\u6570\u636e\n    :param centroids: \u5206\u7c7b\u4e2d\u5fc3\u70b9\n    :return: \u5206\u7c7b\u7ed3\u679c\u7ec4\u6210\u7684\u4e00\u7ef4\u6570\u7ec4\n    \"\"\"\n    idx = []\n    max_distance = 1000000  # \u6700\u5927\u8ddd\u79bb\n    for i in range(len(X)):\n        # \u8be5\u70b9\u548c\u5404\u4e2a\u70b9\u7684\u8ddd\u79bb\n        distances = X[i] - centroids\n        # \u8ba1\u7b97\u6b27\u51e0\u91cc\u5fb7\u8ddd\u79bb\n        euclid_distance = distances[:,0] ** 2 + distances[:,1] ** 2\n        if euclid_distance.min() &lt; max_distance:\n            ci = np.argmin(euclid_distance)\n            idx.append(ci)\n    return np.array(idx)\ndef computeCentroids(X, idx):\n    \"\"\"\n    \u8ba1\u7b97\u5206\u7c7b\u4e2d\u5fc3\n    :param X: \u539f\u59cb\u6570\u636e\n    :param idx: \u4e00\u7ef4\u5206\u7c7b\u7ed3\u679c\u6570\u7ec4\n    :return: \u8ba1\u7b97\u540e\u7684\u4e2d\u5fc3\u70b9\n    \"\"\"\n    centroids = []\n    for i in range(len(np.unique(idx))):\n        # \u8ba1\u7b97\u6bcf\u4e00\u5217\u7684\u5e73\u5747\u503c\n        u_k = X[idx == i].mean(axis=0)\n        centroids.append(u_k)\n    return np.array(centroids)\ndef runKmeans(X, centroids, max_iters):\n    \"\"\"\n    k\u5747\u503c\u7b97\u6cd5\uff0c\n    :param X: \u539f\u59cb\u6570\u636e\n    :param centroids: \u4e2d\u5fc3\u70b9\n    :param max_iters: \u6700\u5927\u8fed\u4ee3\u6b21\u6570\n    :return: \u6267\u884c\u540e\u7684\u5206\u7c7b\u7ed3\u679c\u4ee5\u53ca\u4e2d\u5fc3\u70b9\u53d8\u5316\u8f68\u8ff9\n    \"\"\"\n    centroid_all = []\n    centroid_all.append(centroids)\n    idx = []\n    for i in range(max_iters):\n        idx = findClosestControids(X, centroids)\n        centroid_i = computeCentroids(X, idx)\n        centroid_all.append(centroid_i)\n    return idx, centroid_all\ndef initCentroids(X, K):\n    \"\"\"\n    \u968f\u673a\u521d\u59cb\u5316\u7c7b\u4e2d\u5fc3\u70b9\n    :param X: \u539f\u59cb\u6570\u636e\n    :param K: \u5206k\n    :return: \u627e\u5230\u7684\u4e2d\u5fc3\u70b9\n    \"\"\"\n    m, n = np.shape(X)\n    centroid_index = np.random.choice(m, K)\n    centroids = X[centroid_index]\n    return centroids\ndef plotData(X, centroids, idx=None):\n    \"\"\"\n    \u53ef\u89c6\u5316\u6570\u636e\uff0c\u5e76\u81ea\u52a8\u5206\u5f00\u7740\u8272\u3002\n    :param X: \u539f\u59cb\u6570\u636e\n    :param centroids: \u5305\u542b\u6bcf\u6b21\u4e2d\u5fc3\u70b9\u5386\u53f2\u8bb0\u5f55\n    :param idx: \u6700\u540e\u4e00\u6b21\u8fed\u4ee3\u751f\u6210\u7684idx\u5411\u91cf\uff0c\u5b58\u50a8\u6bcf\u4e2a\u6837\u672c\u5206\u914d\u7684\u7c07\u4e2d\u5fc3\u70b9\u7684\u503c\n    :return:\n    \"\"\"\n    # \u989c\u8272\u5217\u8868\n    colors = ['b', 'g', 'gold', 'darkorange', 'salmon', 'olivedrab', 'maroon', 'navy', 'sienna', 'tomato', 'lightgray',\n              'gainsboro', 'coral', 'aliceblue', 'dimgray', 'mintcream', 'mintcream']\n    # \u65ad\u8a00\uff0c\u5982\u679c\u6761\u4ef6\u4e3a\u771f\u5c31\u6b63\u5e38\u8fd0\u884c\uff0c\u6761\u4ef6\u4e3a\u5047\u5c31\u51fa\u53d1\u5f02\u5e38\n    assert len(centroids[0]) &lt;= len(colors), 'colors not enough '\n    subX = []  # \u5206\u53f7\u7c7b\u7684\u6837\u672c\u70b9\n    if idx is not None:\n        for i in range(centroids[0].shape[0]):\n            x_i = X[idx == i]\n            subX.append(x_i)\n    else:\n        subX = [X]  # \u5c06X\u8f6c\u5316\u4e3a\u4e00\u4e2a\u5143\u7d20\u7684\u5217\u8868\uff0c\u6bcf\u4e2a\u5143\u7d20\u4e3a\u6bcf\u4e2a\u7c07\u7684\u6837\u672c\u96c6\uff0c\u65b9\u4fbf\u4e0b\u65b9\u7ed8\u56fe\n    # \u5206\u522b\u753b\u51fa\u6bcf\u4e2a\u7c07\u7684\u70b9\uff0c\u5e76\u7740\u4e0d\u540c\u7684\u989c\u8272\n    plt.figure(figsize=(8, 5))\n    for i in range(len(subX)):\n        xx = subX[i]\n        plt.scatter(xx[:, 0], xx[:, 1], c=colors[i], label='Cluster %d' % i)\n    plt.legend()\n    plt.grid(True)\n    plt.xlabel('x1', fontsize=14)\n    plt.ylabel('x2', fontsize=14)\n    plt.title('Plot of X Points', fontsize=16)\n    # \u753b\u51fa\u7c07\u4e2d\u5fc3\u70b9\u7684\u79fb\u52a8\u8f68\u8ff9\n    xx, yy = [], []\n    for centroid in centroids:\n        xx.append(centroid[:, 0])\n        yy.append(centroid[:, 1])\n    plt.plot(xx, yy, 'rx--', markersize=8)\n    plt.show()\nif __name__ == '__main__':\n    # \u8bfb\u53d6\u6570\u636e\n    X, _ = loadData()\n    # \u6267\u884c\u4e09\u6b21\n    for i in range(3):\n        # \u968f\u673a\u521d\u59cb\u5316\n        centroids = initCentroids(X, 3)\n        idx, centroids_all = runKmeans(X, centroids, 10)\n        plotData(X, centroids_all, idx)\n        pass\n<\/code><\/pre>\n\n\n<p><\/p>\n\n\n<h2 class=\"wp-block-heading\">2.\u4f7f\u7528K-means\u8fdb\u884c\u56fe\u50cf\u538b\u7f29\uff08\u901a\u8fc7\u51cf\u5c11\u56fe\u50cf\u4e2d\u51fa\u73b0\u7684\u989c\u8272\u7684\u6570\u91cf \uff09<\/h2>\n\n\n<p>\u9996\u5148\u5bfc\u5305\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">from skimage import io<br \/>import numpy as np<br \/>import matplotlib.pyplot as plt<\/pre>\n\n\n<p>\u8bfb\u53d6\u6570\u636e\u5e76\u67e5\u770b\u56fe\u50cf\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">A = io.imread('data\/bird_small.png')<br \/># (128, 128, 3)<br \/>print(A.shape)<br \/>plt.imshow(A)<br \/>plt.show()<\/pre>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"477\" height=\"403\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-62.png\" alt=\"\" class=\"wp-image-1639\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-62.png 477w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-62-300x253.png 300w\" sizes=\"(max-width: 477px) 100vw, 477px\" \/><\/figure><\/div>\n\n\n<p>\u7136\u540e\u5c31\u662f\u548c\u4e0a\u9762\u4e00\u6837\u7684\u4e2d\u5fc3\u70b9\u521d\u59cb\u5316\u3001\u4e2d\u5fc3\u70b9\u8ba1\u7b97\u548c\u5206\u7c7b\u8ba1\u7b97\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">def initCentroids(X, K):<br \/>    <em>\"\"\"\u968f\u673a\u521d\u59cb\u5316\"\"\"<br \/><\/em><em>    <\/em>m, n = X.shape<br \/>    idx = np.random.choice(m, K)<br \/>    centroids = X[idx]<br \/><br \/>    return centroids<br \/><br \/><br \/>def runKmeans(X, centroids, max_iters):<br \/>    K = len(centroids)<br \/>    centroids_all = []<br \/>    centroids_all.append(centroids)<br \/>    centroid_i = centroids<br \/>    for i in range(max_iters):<br \/>        idx = findClosestCentroids(X, centroid_i)<br \/>        centroid_i = computeCentroids(X, idx)<br \/>        centroids_all.append(centroid_i)<br \/><br \/>    return idx, centroids_all<br \/><br \/><br \/>def findClosestCentroids(X, centroids):<br \/>    <em>\"\"\"<br \/><\/em><em>    output a one-dimensional array idx that holds the<br \/><\/em><em>    index of the closest centroid to every training example.<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>idx = []<br \/>    max_dist = 1000000  # \u9650\u5236\u4e00\u4e0b\u6700\u5927\u8ddd\u79bb<br \/>    for i in range(len(X)):<br \/>        minus = X[i] - centroids  # here use numpy's broadcasting<br \/>        dist = minus[:, 0] ** 2 + minus[:, 1] ** 2<br \/>        if dist.min() &lt; max_dist:<br \/>            ci = np.argmin(dist)<br \/>            idx.append(ci)<br \/>    return np.array(idx)<br \/><br \/><br \/>def computeCentroids(X, idx):<br \/>    centroids = []<br \/>    for i in range(len(np.unique(idx))):  # np.unique() means K<br \/>        u_k = X[idx == i].mean(axis=0)  # \u6c42\u6bcf\u5217\u7684\u5e73\u5747\u503c<br \/>        centroids.append(u_k)<br \/><br \/>    return np.array(centroids)<br \/><\/pre>\n\n\n<p>\u6700\u540e\u67e5\u770b\u64cd\u4f5c\u540e\u7684\u56fe\u7247\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">X = A.reshape(-1, 3)<br \/>K = 16<br \/>centroids = initCentroids(X, K)<br \/>idx, centroids_all = runKmeans(X, centroids, 10)<br \/><br \/><br \/>img = np.zeros(X.shape)<br \/>centroids = centroids_all[-1]<br \/>for i in range(len(centroids)):<br \/>    img[idx == i] = centroids[i]<br \/><br \/>img = img.reshape((128, 128, 3))<br \/><br \/>fig, axes = plt.subplots(1, 2, figsize=(12, 6))<br \/>axes[0].imshow(A)<br \/>axes[1].imshow(img)<br \/>plt.show()<br \/><\/pre>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"548\" height=\"274\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-63.png\" alt=\"\" class=\"wp-image-1640\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-63.png 548w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-63-300x150.png 300w\" sizes=\"(max-width: 548px) 100vw, 548px\" \/><\/figure><\/div>\n\n\n<p>\u53ef\u4ee5\u770b\u5230\u56fe\u7247\u7684\u6837\u5b50\u57fa\u672c\u88ab\u4fdd\u7559\uff0c\u4f46\u662f\u538b\u7f29\u540e\u7684\u56fe\u7247\u53ea\u670916\u79cd\u989c\u8272\u3002<\/p>\n\n\n<p>\u6574\u7406\u540e\u7684\u4ee3\u7801\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\"># -*- coding:utf-8 -*-<br \/><br \/>import numpy as np<br \/>from skimage import io<br \/>import matplotlib.pyplot as plt<br \/><br \/><br \/>def loadData():<br \/>    <em>\"\"\"<br \/><\/em><em>    \u8bfb\u53d6\u6570\u636e<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>mig = io.imread('data\/bird_small.png')<br \/>    plt.imshow(mig)<br \/>    return mig \/ 255.<br \/><br \/><br \/>def initcentroids(X, K):<br \/>    <em>\"\"\"<br \/><\/em><em>    \u968f\u673a\u521d\u59cb\u5316\u5206\u7c7b\u4e2d\u5fc3\u70b9<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> X:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> K:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>m, n = np.shape(X)<br \/>    idx = np.random.choice(m, K)<br \/>    return X[idx]<br \/><br \/><br \/>def findClosestCentroids(X, centroids):<br \/>    <em>\"\"\"<br \/><\/em><em>    \u4f9d\u636e\u5206\u7c7b\u4e2d\u5fc3\u70b9\u5212\u5206\u6570\u636e\u70b9<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> X:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> centroids:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>idx = []<br \/>    max_distance = 100000<br \/>    for i in range(len(X)):<br \/>        distance = X[i] - centroids<br \/>        euclid_distance = distance[:, 0] ** 2 + distance[:, 1] ** 2<br \/>        if euclid_distance.min() &lt; max_distance:<br \/>            ci = np.argmin(euclid_distance)<br \/>            idx.append(ci)<br \/>    return np.array(idx)<br \/><br \/><br \/>def computeCentroids(X, idx):<br \/>    <em>\"\"\"<br \/><\/em><em>    \u8ba1\u7b97\u65b0\u7684\u4e2d\u5fc3\u5206\u7c7b\u70b9<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> X:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> centroids:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>centroids = []<br \/>    for i in range(len(np.unique(idx))):<br \/>        u_k = X[idx == i].mean(axis=0)<br \/>        centroids.append(u_k)<br \/>    return np.array(centroids)<br \/><br \/><br \/>def runKMeans(X, K, max_iters):<br \/>    <em>\"\"\"<br \/><\/em><em>    \u6267\u884ck \u5747\u503c\u7b97\u6cd5<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> X:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> K:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> max_iters:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>centroids = initcentroids(X, K)<br \/>    centroids_all = []<br \/>    centroids_all.append(centroids)<br \/>    for i in range(max_iters):<br \/>        idx = findClosestCentroids(X, centroids)<br \/>        centroids_i = computeCentroids(X, idx)<br \/>        centroids_all.append(centroids_i)<br \/>    return idx, centroids_all<br \/><br \/><br \/>if __name__ == '__main__':<br \/>    A = loadData()<br \/>    X = A.reshape(-1, 3)<br \/>    idx, centroids_all = runKMeans(X, 16, 10)<br \/>    img = np.zeros(X.shape)<br \/>    centroids = centroids_all[-1]<br \/>    for i in range(len(centroids)):<br \/>        img[idx == i] = centroids[i]<br \/><br \/>    img = img.reshape((128, 128, 3))<br \/><br \/>    fig, axes = plt.subplots(1, 2, figsize=(12, 6))<br \/>    axes[0].imshow(A)<br \/>    axes[1].imshow(img)<br \/>    plt.show()<br \/><\/pre>\n\n\n<p>\u5728K-means\u4e2d\uff0c\u5bf9\u4e8eK\u5c1d\u5c1d\u4f7f\u7528\u8098\u578b\u56fe\u8fdb\u884c\u5224\u65ad\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"392\" height=\"314\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-67.png\" alt=\"\" class=\"wp-image-1647\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-67.png 392w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-67-300x240.png 300w\" sizes=\"(max-width: 392px) 100vw, 392px\" \/><\/figure><\/div>\n\n\n<p>\u4f46\u662f\u8fd9\u4e2a\u56fe\u4e00\u822c\u60c5\u51b5\u4e0b\u5e76\u4e0d\u4f1a\u6709\u8fd9\u4e48\u6e05\u695a\u5730\u62d0\u70b9\uff0c\u56e0\u6b64\u8fd8\u9700\u8981\u6839\u636e\u5b9e\u9645\u60c5\u51b5\u8fdb\u884c\u5224\u65ad\u3002<\/p>\n\n\n<h2 class=\"wp-block-heading\">3.\u4f7f\u7528PCA\u5c062D\u6570\u636e\u964d\u7ef4\u52301D<\/h2>\n\n\n<p>\u9996\u5148\u5bfc\u5305\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat<\/pre>\n\n\n<p>\u8bfb\u53d6\u6570\u636e\u5e76\u67e5\u770b\u539f\u59cb\u6570\u636e\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">mat = loadmat('data\/ex7data1.mat')<br \/>X = mat['X']<br \/># (50, 2)<br \/>print(X.shape)<br \/>plt.scatter(X[:, 0], X[:, 1], facecolors='none', edgecolors='b')<\/pre>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"543\" height=\"401\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-64.png\" alt=\"\" class=\"wp-image-1644\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-64.png 543w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-64-300x222.png 300w\" sizes=\"(max-width: 543px) 100vw, 543px\" \/><\/figure><\/div>\n\n\n<p>\u7136\u540e\u662f\u6570\u636e\u7684\u6807\u51c6\u5316\uff08\u9632\u6b62\u8fc7\u62df\u5408\uff09\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">def featureNormalize(X):<br \/>    <em>\"\"\"<br \/><\/em><em>    \u6570\u636e\u6807\u51c6\u5316<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> X:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>means = X.mean(axis=0)<br \/><br \/>    stds = X.std(axis=0)<br \/>    X_norm = (X - means) \/ stds<br \/>    return X_norm, means, stds<\/pre>\n\n\n<p>\u8ba1\u7b97\u534f\u65b9\u5dee\u548c\u53bb\u5947\u5f02\u503c\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">def pca(X):<br \/>    <em>\"\"\"<br \/><\/em><em>    pca\u51fd\u6570<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> X:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em># \u8ba1\u7b97\u534f\u65b9\u5dee<br \/>    sigma = (X.T @ X) \/ len(X)<br \/>    # \u8ba1\u7b97\u5947\u5f02\u503c<br \/>    U, S, V = np.linalg.svd(sigma)<br \/><br \/>    return U, S, V<br \/><br \/><br \/>X_norm, means, stds = featureNormalize(X)<br \/>U, S, V = pca(X_norm)<\/pre>\n\n\n<p>\u753b\u51fa\u8ba1\u7b97\u540e\u7684\u5411\u91cf\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">plt.figure(figsize=(7, 5))<br \/>plt.scatter(X[:, 0], X[:, 1], facecolors='none', edgecolors='b')<br \/><br \/>plt.plot([means[0], means[0] + 1.5 * S[0] * U[0, 0]],<br \/>         [means[1], means[1] + 1.5 * S[0] * U[0, 1]],<br \/>         c='r', linewidth=3, label='First Principal Component')<br \/>plt.plot([means[0], means[0] + 1.5 * S[1] * U[1, 0]],<br \/>         [means[1], means[1] + 1.5 * S[1] * U[1, 1]],<br \/>         c='g', linewidth=3, label='Second Principal Component')<br \/>plt.grid()<br \/># changes limits of x or y axis so that equal increments of x and y have the same length<br \/># \u6539\u53d8x\u6216y\u8f74\u7684\u6781\u9650\uff0c\u4f7fx\u548cy\u7684\u589e\u91cf\u76f8\u7b49\uff0c\u957f\u5ea6\u76f8\u540c<br \/># \u4e0d\u7136\u770b\u7740\u4e0d\u5782\u76f4\uff0c\u4e0d\u8212\u670d\u3002\uff1a\uff09<br \/>plt.axis(\"equal\")<br \/>plt.legend()<br \/>plt.show()<\/pre>\n\n\n<p>\u5982\u56fe\u662f\u5728\u4e24\u4e2a\u7ef4\u5ea6\u4e0a\u7684\u5411\u91cf\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"547\" height=\"386\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-65.png\" alt=\"\" class=\"wp-image-1645\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-65.png 547w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-65-300x212.png 300w\" sizes=\"(max-width: 547px) 100vw, 547px\" \/><\/figure><\/div>\n\n\n<p>\u6570\u636e\u6620\u5c04\uff0c\u5c06\u70b9\u6620\u5c04\u5230\u4e00\u7ef4\u5411\u91cf\u4e0a\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">def projectData(X, U, K):<br \/>    <em>\"\"\"<br \/><\/em><em>    \u6620\u5c04\u6570\u636e<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> X:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> U:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> K:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>Z = X @ U[:, :K]<br \/><br \/>    return Z<\/pre>\n\n\n<p>\u6570\u636e\u6062\u590d\uff0c\u5c06\u6620\u5c04\u5230\u5411\u91cf\u4e0a\u7684\u70b9\u6062\u590d\u5230\u4e8c\u7ef4\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">def recoverData(Z, U, K):<br \/>    <em>\"\"\"<br \/><\/em><em>    \u6062\u590d\u6570\u636e<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> Z:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> U:<br \/><\/em><em>    <\/em><strong><em>:param<\/em><\/strong><em> K:<br \/><\/em><em>    <\/em><strong><em>:return<\/em><\/strong><em>:<br \/><\/em><em>    \"\"\"<br \/><\/em><em>    <\/em>X_rec = Z @ U[:, :K].T<br \/><br \/>    return X_rec<\/pre>\n\n\n<p>\u8c03\u7528\u4e00\u4e0b\uff0c\u9996\u5148\u5c06\u4e8c\u7ef4\u7684\u70b9\u6620\u5c04\u5230\u4e00\u7ef4\u5411\u91cf\u4e0a\uff0c\u5f97\u52301.49\u8fd9\u4e2a\u76f8\u5bf9\u5750\u6807\uff0c\u7136\u540e\u75281.49\u4e0e\u8be5\u5411\u91cf\u8fdb\u884c\u6062\u590d\uff0c\u6062\u590d\u52301.05\u5de6\u53f3\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">Z = projectData(X_norm, U, 1)\n# [1.49631261]\nprint(Z[0])\nX_rec = recoverData(Z, U, 1)\n# [-1.05805279 -1.05805279]\nprint(X_rec[0])<\/pre>\n\n\n<p>\u753b\u56fe\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\">plt.figure(figsize=(7, 5))<br \/>plt.axis(\"equal\")<br \/>plot = plt.scatter(X_norm[:, 0], X_norm[:, 1], s=30, facecolors='none',<br \/>                   edgecolors='b', label='Original Data Points')<br \/>plot = plt.scatter(X_rec[:, 0], X_rec[:, 1], s=30, facecolors='none',<br \/>                   edgecolors='r', label='PCA Reduced Data Points')<br \/><br \/>plt.title(\"Example Dataset: Reduced Dimension Points Shown\", fontsize=14)<br \/>plt.xlabel('x1 [Feature Normalized]', fontsize=14)<br \/>plt.ylabel('x2 [Feature Normalized]', fontsize=14)<br \/>plt.grid(True)<br \/><br \/># \u753b\u865a\u7ebf<br \/>for x in range(X_norm.shape[0]):<br \/>    plt.plot([X_norm[x, 0], X_rec[x, 0]], [X_norm[x, 1], X_rec[x, 1]], 'k--')<br \/>    # \u8f93\u5165\u7b2c\u4e00\u9879\u5168\u662fX\u5750\u6807\uff0c\u7b2c\u4e8c\u9879\u90fd\u662fY\u5750\u6807<br \/>plt.legend()<br \/>plt.show()<\/pre>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"549\" height=\"389\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-66.png\" alt=\"\" class=\"wp-image-1646\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-66.png 549w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-66-300x213.png 300w\" sizes=\"(max-width: 549px) 100vw, 549px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">4.\u5728\u4eba\u8138\u56fe\u50cf\u4e0a\u4f7f\u7528PCA<\/h2>\n\n\n<p>\u538b\u7f29\u524d\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"542\" height=\"543\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-68.png\" alt=\"\" class=\"wp-image-1650\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-68.png 542w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-68-300x300.png 300w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-68-150x150.png 150w\" sizes=\"(max-width: 542px) 100vw, 542px\" \/><\/figure><\/div>\n\n\n<p>PCA\u9009\u62e9\u540e\u768436\u79cd\u989c\u8272\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"543\" height=\"544\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-70.png\" alt=\"\" class=\"wp-image-1652\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-70.png 543w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-70-300x300.png 300w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-70-150x150.png 150w\" sizes=\"(max-width: 543px) 100vw, 543px\" \/><\/figure><\/div>\n\n\n<p>\u6570\u636e\u6062\u590d\u540e\uff0c\u53ef\u4ee5\u770b\u51fa\u786e\u5b9e\u6062\u590d\u4e86\u4e00\u90e8\u5206\u6570\u636e\uff1a<\/p>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"546\" height=\"541\" src=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-69.png\" alt=\"\" class=\"wp-image-1651\" srcset=\"http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-69.png 546w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-69-300x297.png 300w, http:\/\/www.sniper97.cn\/wp-content\/uploads\/2019\/09\/\u56fe\u7247-69-150x150.png 150w\" sizes=\"(max-width: 546px) 100vw, 546px\" \/><\/figure><\/div>\n\n\n<p>\u4ee3\u7801\uff1a<\/p>\n\n\n<pre class=\"wp-block-preformatted\"># -*- coding:utf-8 -*-<br \/>import numpy as np<br \/>import matplotlib.pyplot as plt<br \/>from scipy.io import loadmat<br \/><br \/><br \/>def featureNormalize(X):<br \/>    means = X.mean(axis=0)<br \/>    stds = X.std(axis=0, ddof=1)<br \/>    X_norm = (X - means) \/ stds<br \/>    return X_norm, means, stds<br \/><br \/><br \/>def pca(X):<br \/>    sigma = (X.T @ X) \/ len(X)<br \/>    U, S, V = np.linalg.svd(sigma)<br \/><br \/>    return U, S, V<br \/><br \/><br \/>def projectData(X, U, K):<br \/>    Z = X @ U[:, :K]<br \/><br \/>    return Z<br \/><br \/><br \/>def recoverData(Z, U, K):<br \/>    X_rec = Z @ U[:, :K].T<br \/><br \/>    return X_rec<br \/><br \/><br \/>mat = loadmat('data\/ex7faces.mat')<br \/>X = mat['X']<br \/># (5000, 1024)<br \/>print(X.shape)<br \/><br \/><br \/>def displayData(X, row, col):<br \/>    fig, axs = plt.subplots(row, col, figsize=(8, 8))<br \/>    for r in range(row):<br \/>        for c in range(col):<br \/>            axs[r][c].imshow(X[r * col + c].reshape(32, 32).T, cmap='Greys_r')<br \/>            axs[r][c].set_xticks([])<br \/>            axs[r][c].set_yticks([])<br \/>    plt.show()<br \/><br \/><br \/>displayData(X, 10, 10)<br \/><br \/>X_norm, means, stds = featureNormalize(X)<br \/><br \/>U, S, V = pca(X_norm)<br \/># (1024, 1024) (1024,)<br \/>print(U.shape, S.shape)<br \/><br \/>displayData(U[:, :36].T, 6, 6)<br \/><br \/>z = projectData(X_norm, U, K=36)<br \/><br \/>X_rec = recoverData(z, U, K=36)<br \/><br \/>displayData(X_rec, 10, 10)<br \/><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5434\u6069\u8fbe\u673a\u5668\u5b66\u4e60\u7b2c\u516b\u5468\uff1aK-means\u4e0ePCA\uff08K-means and PCA\uff09\u3002 1.\u4f7f\u7528K-mea [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[6,10],"tags":[],"views":4059,"_links":{"self":[{"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/posts\/1627"}],"collection":[{"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/comments?post=1627"}],"version-history":[{"count":0,"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/posts\/1627\/revisions"}],"wp:attachment":[{"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/media?parent=1627"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/categories?post=1627"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.sniper97.cn\/index.php\/wp-json\/wp\/v2\/tags?post=1627"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}