吴恩达Coursera, 机器学习专项课enders, Reinforcement Learning第一周编程作业1
原创
©著作权归作者所有:来自51CTO博客作者楚千羽的原创作品,请联系作者获取转载授权,否则将追究法律责任
吴恩达Coursera, 机器学习专项课程, Machine Learning:Unsupervised Learning, Recommenders, Reinforcement Learning第一周所有jupyter notebook文件1:
吴恩达Coursera, 机器学习专项课程, Machine Learning:Unsupervised Learning, Recommenders, Reinforcement Learning第一周所有jupyter notebook文件(包括实验室练习文件)1
本次作业
Exercise 1
# UNQ_C1
# GRADED FUNCTION: find_closest_centroids
def find_closest_centroids(X, centroids):
"""
Computes the centroid memberships for every example
Args:
X (ndarray): (m, n) Input values
centroids (ndarray): k centroids
Returns:
idx (array_like): (m,) closest centroids
"""
# Set K
K = centroids.shape[0]
# You need to return the following variables correctly
idx = np.zeros(X.shape[0], dtype=int)
### START CODE HERE ###
dis = []
for i in range(len(X)):
for j in range(len(centroids)):
dis.append(((X[i][0] - centroids[j][0]) **2 + (X[i][1] - centroids[j][1]) **2 ) ** (1/2))
idx[i] = np.argmin(dis)
dis = []
### END CODE HERE ###
return idx
Exercise 2
# UNQ_C2
# GRADED FUNCTION: compute_centpods
def compute_centroids(X, idx, K):
"""
Returns the new centroids by computing the means of the
data points assigned to each centroid.
Args:
X (ndarray): (m, n) Data points
idx (ndarray): (m,) Array containing index of closest centroid for each
example in X. Concretely, idx[i] contains the index of
the centroid closest to example i
K (int): number of centroids
Returns:
centroids (ndarray): (K, n) New centroids computed
"""
# Useful variables
m, n = X.shape
# You need to return the following variables correctly
centroids = np.zeros((K, n))
### START CODE HERE ###
for i in range(K):
indices = np.where(idx == i)
centroids[i, :] = (np.sum(X[indices, :], axis=1) / len(indices[0])).ravel()
### END CODE HERE ##
return centroids
作者:楚千羽