Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
greyhatguy007
GitHub Repository: greyhatguy007/Machine-Learning-Specialization-Coursera
Path: blob/main/C3 - Unsupervised Learning, Recommenders, Reinforcement Learning/week1/C3W1A/C3W1A2/utils.py
3567 views
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
def load_data():
5
X = np.load("data/X_part1.npy")
6
X_val = np.load("data/X_val_part1.npy")
7
y_val = np.load("data/y_val_part1.npy")
8
return X, X_val, y_val
9
10
def load_data_multi():
11
X = np.load("data/X_part2.npy")
12
X_val = np.load("data/X_val_part2.npy")
13
y_val = np.load("data/y_val_part2.npy")
14
return X, X_val, y_val
15
16
17
def multivariate_gaussian(X, mu, var):
18
"""
19
Computes the probability
20
density function of the examples X under the multivariate gaussian
21
distribution with parameters mu and var. If var is a matrix, it is
22
treated as the covariance matrix. If var is a vector, it is treated
23
as the var values of the variances in each dimension (a diagonal
24
covariance matrix
25
"""
26
27
k = len(mu)
28
29
if var.ndim == 1:
30
var = np.diag(var)
31
32
X = X - mu
33
p = (2* np.pi)**(-k/2) * np.linalg.det(var)**(-0.5) * \
34
np.exp(-0.5 * np.sum(np.matmul(X, np.linalg.pinv(var)) * X, axis=1))
35
36
return p
37
38
def visualize_fit(X, mu, var):
39
"""
40
This visualization shows you the
41
probability density function of the Gaussian distribution. Each example
42
has a location (x1, x2) that depends on its feature values.
43
"""
44
45
X1, X2 = np.meshgrid(np.arange(0, 35.5, 0.5), np.arange(0, 35.5, 0.5))
46
Z = multivariate_gaussian(np.stack([X1.ravel(), X2.ravel()], axis=1), mu, var)
47
Z = Z.reshape(X1.shape)
48
49
plt.plot(X[:, 0], X[:, 1], 'bx')
50
51
if np.sum(np.isinf(Z)) == 0:
52
plt.contour(X1, X2, Z, levels=10**(np.arange(-20., 1, 3)), linewidths=1)
53
54
# Set the title
55
plt.title("The Gaussian contours of the distribution fit to the dataset")
56
# Set the y-axis label
57
plt.ylabel('Throughput (mb/s)')
58
# Set the x-axis label
59
plt.xlabel('Latency (ms)')
60