Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
greyhatguy007
GitHub Repository: greyhatguy007/Machine-Learning-Specialization-Coursera
Path: blob/main/C2 - Advanced Learning Algorithms/week1/optional-labs/lab_neurons_utils.py
3584 views
1
import numpy as np
2
import matplotlib.pyplot as plt
3
plt.style.use('./deeplearning.mplstyle')
4
from matplotlib import cm
5
import matplotlib.colors as colors
6
from lab_utils_common import dlc
7
8
def plt_prob_1d(ax,fwb):
9
""" plots a decision boundary but include shading to indicate the probability """
10
#setup useful ranges and common linspaces
11
x_space = np.linspace(0, 5 , 50)
12
y_space = np.linspace(0, 1 , 50)
13
14
# get probability for x range, extend to y
15
z = np.zeros((len(x_space),len(y_space)))
16
for i in range(len(x_space)):
17
x = np.array([[x_space[i]]])
18
z[:,i] = fwb(x)
19
20
cmap = plt.get_cmap('Blues')
21
new_cmap = truncate_colormap(cmap, 0.0, 0.5)
22
pcm = ax.pcolormesh(x_space, y_space, z,
23
norm=cm.colors.Normalize(vmin=0, vmax=1),
24
cmap=new_cmap, shading='nearest', alpha = 0.9)
25
ax.figure.colorbar(pcm, ax=ax)
26
27
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
28
""" truncates color map """
29
new_cmap = colors.LinearSegmentedColormap.from_list(
30
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
31
cmap(np.linspace(minval, maxval, n)))
32
return new_cmap
33
34
35
def sigmoidnp(z):
36
"""
37
Compute the sigmoid of z
38
39
Parameters
40
----------
41
z : array_like
42
A scalar or numpy array of any size.
43
44
Returns
45
-------
46
g : array_like
47
sigmoid(z)
48
"""
49
z = np.clip( z, -500, 500 ) # protect against overflow
50
g = 1.0/(1.0+np.exp(-z))
51
52
return g
53
54
def plt_linear(X_train, Y_train, prediction_tf, prediction_np):
55
fig, ax = plt.subplots(1,2, figsize=(16,4))
56
ax[0].scatter(X_train, Y_train, marker='x', c='r', label="Data Points")
57
ax[0].plot(X_train, prediction_tf, c=dlc['dlblue'], label="model output")
58
ax[0].text(1.6,350,r"y=$200 x + 100$", fontsize='xx-large', color=dlc['dlmagenta'])
59
ax[0].legend(fontsize='xx-large')
60
ax[0].set_ylabel('Price (in 1000s of dollars)', fontsize='xx-large')
61
ax[0].set_xlabel('Size (1000 sqft)', fontsize='xx-large')
62
ax[0].set_title("Tensorflow prediction",fontsize='xx-large')
63
64
ax[1].scatter(X_train, Y_train, marker='x', c='r', label="Data Points")
65
ax[1].plot(X_train, prediction_np, c=dlc['dlblue'], label="model output")
66
ax[1].text(1.6,350,r"y=$200 x + 100$", fontsize='xx-large', color=dlc['dlmagenta'])
67
ax[1].legend(fontsize='xx-large')
68
ax[1].set_ylabel('Price (in 1000s of dollars)', fontsize='xx-large')
69
ax[1].set_xlabel('Size (1000 sqft)', fontsize='xx-large')
70
ax[1].set_title("Numpy prediction",fontsize='xx-large')
71
plt.show()
72
73
74
def plt_logistic(X_train, Y_train, model, set_w, set_b, pos, neg):
75
fig,ax = plt.subplots(1,2,figsize=(16,4))
76
77
layerf= lambda x : model.predict(x)
78
plt_prob_1d(ax[0], layerf)
79
80
ax[0].scatter(X_train[pos], Y_train[pos], marker='x', s=80, c = 'red', label="y=1")
81
ax[0].scatter(X_train[neg], Y_train[neg], marker='o', s=100, label="y=0", facecolors='none',
82
edgecolors=dlc["dlblue"],lw=3)
83
84
ax[0].set_ylim(-0.08,1.1)
85
ax[0].set_xlim(-0.5,5.5)
86
ax[0].set_ylabel('y', fontsize=16)
87
ax[0].set_xlabel('x', fontsize=16)
88
ax[0].set_title('Tensorflow Model', fontsize=20)
89
ax[0].legend(fontsize=16)
90
91
layerf= lambda x : sigmoidnp(np.dot(set_w,x.reshape(1,1)) + set_b)
92
plt_prob_1d(ax[1], layerf)
93
94
ax[1].scatter(X_train[pos], Y_train[pos], marker='x', s=80, c = 'red', label="y=1")
95
ax[1].scatter(X_train[neg], Y_train[neg], marker='o', s=100, label="y=0", facecolors='none',
96
edgecolors=dlc["dlblue"],lw=3)
97
98
ax[1].set_ylim(-0.08,1.1)
99
ax[1].set_xlim(-0.5,5.5)
100
ax[1].set_ylabel('y', fontsize=16)
101
ax[1].set_xlabel('x', fontsize=16)
102
ax[1].set_title('Numpy Model', fontsize=20)
103
ax[1].legend(fontsize=16)
104
plt.show()
105
106