Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
greyhatguy007
GitHub Repository: greyhatguy007/Machine-Learning-Specialization-Coursera
Path: blob/main/C2 - Advanced Learning Algorithms/week2/optional-labs/lab_utils_multiclass.py
3587 views
1
# C2_W1 Utilities
2
import numpy as np
3
import matplotlib.pyplot as plt
4
from sklearn.datasets import make_blobs
5
6
def sigmoid(x):
7
return 1 / (1 + np.exp(-x))
8
9
# Plot multi-class training points
10
def plot_mc_data(X, y, class_labels=None, legend=False,size=40):
11
classes = np.unique(y)
12
for i in classes:
13
label = class_labels[i] if class_labels else "class {}".format(i)
14
idx = np.where(y == i)
15
plt.scatter(X[idx, 0], X[idx, 1], cmap=plt.cm.Paired,
16
edgecolor='black', s=size, label=label)
17
if legend: plt.legend()
18
19
20
#Plot a multi-class categorical decision boundary
21
# This version handles a non-vector prediction (adds a for-loop over points)
22
def plot_cat_decision_boundary(X,predict , class_labels=None, legend=False, vector=True):
23
24
# create a mesh to points to plot
25
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
26
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
27
h = max(x_max-x_min, y_max-y_min)/200
28
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
29
np.arange(y_min, y_max, h))
30
points = np.c_[xx.ravel(), yy.ravel()]
31
print("points", points.shape)
32
print("xx.shape", xx.shape)
33
34
#make predictions for each point in mesh
35
if vector:
36
Z = predict(points)
37
else:
38
Z = np.zeros((len(points),))
39
for i in range(len(points)):
40
Z[i] = predict(points[i].reshape(1,2))
41
Z = Z.reshape(xx.shape)
42
43
#contour plot highlights boundaries between values - classes in this case
44
plt.figure()
45
plt.contour(xx, yy, Z, colors='g')
46
plt.axis('tight')
47