Path: blob/master/1_Supervised_Machine_Learning/Week 3. Classification/utils.py
2826 views
import numpy as np1import matplotlib.pyplot as plt234def load_data(filename):5data = np.loadtxt(filename, delimiter=',')6X = data[:, :2]7y = data[:, 2]8return X, y91011def sig(z):12return 1 / (1 + np.exp(-z))131415def map_feature(X1, X2):16"""17Feature mapping function to polynomial features18"""19X1 = np.atleast_1d(X1)20X2 = np.atleast_1d(X2)21degree = 622out = []23for i in range(1, degree + 1):24for j in range(i + 1):25out.append((X1 ** (i - j) * (X2 ** j)))26return np.stack(out, axis=1)272829def plot_data(X, y, pos_label="y=1", neg_label="y=0"):30positive = y == 131negative = y == 03233# Plot examples34plt.plot(X[positive, 0], X[positive, 1], 'k+', label=pos_label)35plt.plot(X[negative, 0], X[negative, 1], 'yo', label=neg_label)363738def plot_decision_boundary(w, b, X, y):39# Credit to dibgerge on Github for this plotting code4041plot_data(X[:, 0:2], y)4243if X.shape[1] <= 2:44plot_x = np.array([min(X[:, 0]), max(X[:, 0])])45plot_y = (-1. / w[1]) * (w[0] * plot_x + b)4647plt.plot(plot_x, plot_y, c="b")4849else:50u = np.linspace(-1, 1.5, 50)51v = np.linspace(-1, 1.5, 50)5253z = np.zeros((len(u), len(v)))5455# Evaluate z = theta*x over the grid56for i in range(len(u)):57for j in range(len(v)):58z[i, j] = sig(np.dot(map_feature(u[i], v[j]), w) + b)5960# important to transpose z before calling contour61z = z.T6263# Plot z = 0.564plt.contour(u, v, z, levels=[0.5], colors="g")65666768