import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Cost Iteration Notebook
Interactive tutorial on cost iteration notebook with practical implementations and visualizations
= np.array([1, 2, 3])
X = np.array([1, 2, 3]) y
def y_hat(X, theta_0, theta_1):
return theta_0 + theta_1*X
def cost(X, y, theta_0, theta_1):
= y_hat(X, theta_0, theta_1)
yh return (y-yh).T@(y-yh)
= 4
theta_0 = 0
theta_1 = 0.1
alpha = np.zeros(1000)
costs = np.zeros(1000)
theta_0_list = np.zeros(1000)
theta_1_list
for i in range(1000):
= cost(X, y, theta_0, theta_1)
costs[i] = theta_0 - 2*alpha*((y_hat(X, theta_0, theta_1)-y).mean())
theta_0 = theta_1 - 2*alpha*((y_hat(X, theta_0, theta_1)-y).T@X)/len(X)
theta_1 = theta_0
theta_0_list[i] = theta_1 theta_1_list[i]
import sys
"../")
sys.path.append(from latexify import *
latexify()200], 'k')
plt.plot(costs[:
format_axes(plt.gca())"Cost")
plt.ylabel("Iteration")
plt.xlabel("../gradient-descent/gd-iter-cost.pdf", bbox_inches="tight", transparent=True) plt.savefig(
for i in range(0, 200, 20):
="Fit at iteration {}".format(i))
plt.title(label+theta_1_list[i]*X, color='k')
plt.plot(X, theta_0_list[i]='k')
plt.scatter(X, y, color"x")
plt.xlabel("y")
plt.ylabel(
format_axes(plt.gca())"../gradient-descent/fit-iteration-{}.pdf".format(i), bbox_inches="tight", transparent=True)
plt.savefig( plt.cla()
= 4
theta_0 = 0
theta_1 -y).mean() (y_hat(X, theta_0, theta_1)
2.0
-y_hat(X, theta_0, theta_1)).mean() (y
-2.0
-y_hat(X, theta_0, theta_1))@X (y
-10