Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jxareas
GitHub Repository: jxareas/Machine-Learning-Notebooks
Path: blob/master/1_Supervised_Machine_Learning/Week 3. Classification/utils.py
2826 views
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
5
def load_data(filename):
6
data = np.loadtxt(filename, delimiter=',')
7
X = data[:, :2]
8
y = data[:, 2]
9
return X, y
10
11
12
def sig(z):
13
return 1 / (1 + np.exp(-z))
14
15
16
def map_feature(X1, X2):
17
"""
18
Feature mapping function to polynomial features
19
"""
20
X1 = np.atleast_1d(X1)
21
X2 = np.atleast_1d(X2)
22
degree = 6
23
out = []
24
for i in range(1, degree + 1):
25
for j in range(i + 1):
26
out.append((X1 ** (i - j) * (X2 ** j)))
27
return np.stack(out, axis=1)
28
29
30
def plot_data(X, y, pos_label="y=1", neg_label="y=0"):
31
positive = y == 1
32
negative = y == 0
33
34
# Plot examples
35
plt.plot(X[positive, 0], X[positive, 1], 'k+', label=pos_label)
36
plt.plot(X[negative, 0], X[negative, 1], 'yo', label=neg_label)
37
38
39
def plot_decision_boundary(w, b, X, y):
40
# Credit to dibgerge on Github for this plotting code
41
42
plot_data(X[:, 0:2], y)
43
44
if X.shape[1] <= 2:
45
plot_x = np.array([min(X[:, 0]), max(X[:, 0])])
46
plot_y = (-1. / w[1]) * (w[0] * plot_x + b)
47
48
plt.plot(plot_x, plot_y, c="b")
49
50
else:
51
u = np.linspace(-1, 1.5, 50)
52
v = np.linspace(-1, 1.5, 50)
53
54
z = np.zeros((len(u), len(v)))
55
56
# Evaluate z = theta*x over the grid
57
for i in range(len(u)):
58
for j in range(len(v)):
59
z[i, j] = sig(np.dot(map_feature(u[i], v[j]), w) + b)
60
61
# important to transpose z before calling contour
62
z = z.T
63
64
# Plot z = 0.5
65
plt.contour(u, v, z, levels=[0.5], colors="g")
66
67
68