
目标
在本实验中,你将:使用梯度下降自动化优化w和b的过程
工具
在本实验中,我们将使用:
- NumPy,一个流行的科学计算库
- Matplotlib,一个用于绘制数据的流行库在本地目录的
- lab_utils.py文件中绘制例程
import math, copy
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('./deeplearning.mplstyle')
from lab_utils_uni import plt_house_x, plt_contour_wgrad, plt_divergence, plt_gradients
当前jupyter note工作目录需要包含:
问题陈述
让我们使用和之前一样的两个数据点——一个1000平方英尺的房子卖了30万美元,一个2000平方英尺的房子卖了50万美元。
# Load our data set
x_train = np.array([1.0, 2.0]) #features
y_train = np.array([300.0, 500.0]) #target value
计算损失
这是上一个实验室开发的。我们这里还会用到它
#Function to calculate the cost
def compute_cost(x, y, w, b):
m = x.shape[0]
cost = 0
for i in range(m):
f_wb = w * x[i] + b
cost = cost + (f_wb - y[i])**2
total_cost = 1 / (2 * m) * cost
return total_cost
梯度下降总结
线性模型:f(x)=wx+b
损失函数:J(w,b)
参数更新:
执行梯度下降
def compute_gradient(x, y, w, b):
"""
Computes the gradient for linear regression
Args:
x (ndarray (m,)): Data, m examples
y (ndarray (m,)): target values
w,b (scalar) : model parameters
Returns
dj_dw (scalar): The gradient of the cost w.r.t. the parameters w
dj_db (scalar): The gradient of the cost w.r.t. the parameter b
"""
# Number of training examples
m = x