利用python完成ex7的part one——K-means Clustering,第一部分要求如下:
In this this exercise, you will implement the K-means algorithm and use it for image compression. You will rst start on an example 2D dataset that will help you gain an intuition of how the K-means algorithm works. Afterthat, you wil use the K-means algorithm for image compression by reducingthe number of colors that occur in an image to only those that are most common in that image.
代码如下:
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 12 14:19:55 2020
@author: Lonely_hanhan
"""
import matplotlib.pyplot as plt
import scipy.io as sio
import numpy as np
import findClosestCentroids as fc
import computeCentroids as cc
import runkMeans as rk
import kmeans_init_centroids as kic
from skimage import io
from skimage import img_as_float
'''
%% Machine Learning Online Class
% Exercise 7 | Principle Component Analysis and K-Means Clustering
%
% Instructions
% ------------
%
% This file contains code that helps you get started on the
% exercise. You will need to complete the following functions:
%
% pca.m
% projectData.m
% recoverData.m
% computeCentroids.m
% findClosestCentroids.m
% kMeansInitCentroids.m
%
% For this exercise, you will not need to change any code in this file,
% or any other files other than those mentioned above.
%
'''
'''
%% ================= Part 1: Find Closest Centroids ====================
% To help you implement K-Means, we have divided the learning algorithm
% into two functions -- findClosestCentroids and computeCentroids. In this
% part, you should complete the code in the findClosestCentroids function.
%
'''
print('Finding closest centroids.\n\n')
# Load an example dataset that we will be using
Data = sio.loadmat('D:\exercise\machine-learning-ex7\ex7\ex7data2.mat')
X = Data['X']
# Select an initial set of centroids
K = 3 # 3 Centroids
initial_centroids = np.array([[3,3],[6,2],[8,5]])
# Find the closest centroids for the examples using the
# initial_centroids
idx = fc.findClosestCentroids(X, initial_centroids)
print('Closest centroids for the first 3 examples: \n')
print(idx[0:3])
print('\n(the closest centroids should be 0, 2, 1 respectively)\n')
'''
%% ===================== Part 2: Compute Means =========================
% After implementing the closest centroids function, you should now
% complete the computeCentroids function.
%
'''
print('\nComputing centroids means.\n\n')
# Compute means based on the closest centroids found in the previous part.
centroids = cc.computeCentroids(X, idx, K)
print('Centroids computed after initial finding of closest centroids: \n')
print(centroids)
print('\n(the centroids should be\n')
print(' [ 2.428301 3.157924 ]\n')
print(' [ 5.813503 2.633656 ]\n')
print(' [ 7.119387 3.616684 ]\n\n