Browse Source

Change print option of ex6. Initial commit of ex7.

master
wchen342 6 years ago
parent
commit
0c06cceda1
  1. 2
      ex5/ex5.py
  2. 49
      ex7/ex7.py

2
ex5/ex5.py

@ -144,7 +144,7 @@ def validation_curve(X, y, Xval, yval):
return lambda_vec, error_train, error_val
np.set_printoptions(formatter={'float': '{: 0.64f}'.format, 'longfloat': '{: 0.64f}'.format}, edgeitems=50, linewidth=150)
np.set_printoptions(formatter={'float': '{: 0.5f}'.format}, edgeitems=50, linewidth=150)
## =========== Part 1: Loading and Visualizing Data =============
# Load Training Data
print('Loading and Visualizing Data ...\n')

49
ex7/ex7.py

@ -0,0 +1,49 @@
## Machine Learning Online Class
# Exercise 7 | Principle Component Analysis and K-Means Clustering
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
# FINDCLOSESTCENTROIDS computes the centroid memberships for every example
# idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
# in idx for a dataset X where each row is a single example. idx = m x 1
# vector of centroid assignments (i.e. each entry in range [1..K])
def find_closest_centroids(X, centroids):
# Set K
K = centroids.shape[0]
# Initialize return value
idx = np.zeros((X.shape[0], 1))
# Go over every example, find its closest centroid, and store
# the index inside idx at the appropriate location.
for i in range(0, X.shape[0]):
index = np.argmin(np.sum((X(i, :) .- centroids) .^ 2, 2))
idx[i] = index
return idx
## ================= Part 1: Find Closest Centroids ====================
print('Finding closest centroids.\n\n')
# Load an example dataset that we will be using
data = scipy.io.loadmat('mat/ex7data2.mat', matlab_compatible=True)
X = data['X']
y = data['y']
# 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 = find_closest_centroids(X, initial_centroids)
print('Closest centroids for the first 3 examples: \n')
print(' {0:d}'.format(idx[:3]))
print('\n(the closest centroids should be 1, 3, 2 respectively)\n')
print('Program paused. Press enter to continue.\n')
Loading…
Cancel
Save