与单变量线性回归类似,在多变量线性回归中,我们也构建一个代价函数,则这个代价函数是所有建模误差的平方和
我们的目标和单变量线性回归问题中一样,是要找出使得代价函数最小的一系列参数。 多变量线性回归的批量梯度下降算法为:
即
求导数后得到:
当n>=1时
我们开始随机选择一系列的参数值,计算所有的预测结果后,再给所有的参数一个新的值,如此循环直到收敛。
-
梯度下降法实践1-特征缩放
在我们面对多维特征问题的时候,我们要保证这些特征都具有相近的尺度,这将帮助梯度下降算法更快地收敛。
以房价问题为例,假设我们使用两个特征,房屋的尺寸和房间的数量,尺寸的值为 0-2000平方英尺,而房间数量的值则是0-5,以两个参数分别为横纵坐标,绘制代价函数的等高线图能,看出图像会显得很扁,梯度下降算法需要非常多次的迭代才能收敛
解决的方法是尝试将所有特征的尺度都尽量缩放到-1到1之间。如图
最简单的方法是令:
-
梯度下降法实践2-学习率
通常可以考虑尝试些学习率:
- 特征和多项式回归
线性回归并不适用于所有数据,有时我们需要曲线来适应我们的数据,比如一个二次方模型:
或者三次方模型:
注:如果我们采用多项式回归模型,在运行梯度下降算法前,特征缩放非常有必要。
-
正规方程
到目前为止,我们都在使用梯度下降算法,但是对于某些线性回归问题,正规方程方法是更好的解决方案。如
正规方程是通过求解下面的方程来找出使得代价函数最小的参数的
假设我们的训练集特征矩阵为 X(包含了x0=1 )并且我们的训练集结果为向量y ,则利用正规方程解出向量
即
运用正规方程方法求解参数:
如何选择?
总结一下,只要特征变量的数目并不大,标准方程是一个很好的计算参数θ的替代方法。具体地说,只要特征变量数量小于一万,我通常使用标准方程法,而不使用梯度下降法。
吴恩达课后作业ex1 的多变量线性回归
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
#同一量级后运算更加方便
path="E:\machine studdy\Coursera-ML-AndrewNg-Notes-master\code\ex1-linear regression\ex1data2.txt"
data=pd.read_csv(path,header=None,names=['Size','Bedrooms','Price'])
#特征归一化,-平均值 /标准差 如果两个两特征值之间的差距过大 目的是加快梯度下降
data = (data - data.mean()) / data.std()
def costfunction(X,y,theta):
inner=np.power((X* theta.T)-y,2)
cost=np.sum(inner)/(2*len(X))
return cost
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
parameters = int(theta.ravel().shape[1])
cost = np.zeros(iters)
for i in range(iters):
error = (X * theta.T) - y
for j in range(parameters):
term = np.multiply(error, X[:, j])
temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(term))
theta = temp
cost[i] = costfunction(X, y, theta)
return theta, cost
#向量化后的梯度下降算法
def gradientdescent(theta,X,y,alpha,iters):
theta=np.matrix(theta)
X=np.matrix(X)
y=np.matrix(y)
temp = np.matrix(np.zeros(theta.shape))
for i in range(iters):
error = (X * theta.T) - y
term=(error.T) *X *(alpha/len(X))
temp=theta-term
theta=temp
return theta
data.insert(0,'ones',1)
col=data.shape[1] #获取数组第二个维度的长度
X=data.iloc[:,0:col-1] #获得X
y=data.iloc[:,col-1:col]
X = np.matrix(X.values)
y = np.matrix(y.values) #矩阵化 X y
theta=np.matrix(np.array([0,0,0])) #设置参数为三个0 三个0都在数组中的第一个,调用的时候把第一个参数设置为0,以此增加就行
alpha = 0.01
iters = 1500
print(X.shape)
print(y.shape)
print(theta.shape)
print(costfunction(X,y,theta))
g2, cost2 = gradientDescent(X, y, theta, alpha, iters)
print(g2)
print(gradientdescent(theta,X,y,alpha,iters))