一.多元线性
在上一节中提到了线性回归,不过特征量x只有1个,当特征量大于1个时,如下表:
住房面积x1x_1x1 | 层数x2x_2x2 | 卧室个数x3x_3x3 | 住宅年数x4x_4x4 | 售出价格y |
---|---|---|---|---|
2104 | 5 | 1 | 45 | 460 |
1416 | 3 | 2 | 40 | 232 |
1534 | 3 | 2 | 30 | 315 |
852 | 2 | 1 | 36 | 178 |
… | … | … | … | … |
这时我们的假设函数成为h=θ0+θ1x1+θ2x2+θ3x3+θ4x4h=\theta_0+\theta_1x_1+\theta_2x_2+\theta_3x_3+\theta_4x_4h=θ0+θ1x1+θ2x2+θ3x3+θ4x4,所有的参数组成向量θ\thetaθ,所有特征组成向量x,那么假设函数简化为h=θTxh=\theta^T xh=θTx,这样转化成矩阵相乘运算,而代价函数还是J(θ)=12m∑i=1m(hθ(x(i))−y(i))2J(\theta)=\frac{1}{2m}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2J(θ)=2m1∑i=1m(hθ(x(i))−y(i))2.
二.梯度下降
对代价函数求偏导,使得代价值递减:
θj=θj−α∂J∂θj=θj−α1m∑i=1m(hθ(x(i))−y(i))x(i)\theta_j=\theta_j-\alpha \frac{\partial J}{\partial \theta_j}=\theta_j-\alpha \frac {1}{m}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})x^{(i)}θj=θj−α∂θj∂J=θj−αm1∑i=1m(hθ(x(i))−y(i))x(i)
三.特征归一化
当两个不同特征之间的值范围相差太大(例如上述的住宅面积和层数两个特征量)时,收敛速度太慢,可以从下图(以后加)中直观的看出:
解决方法
特征缩放:即将所有特征量x缩放至−1≤x≤1-1\leq x\leq 1−1≤x≤1的范围,以住宅面积为例,具体方法如下:
- x^1=x1−xminxmax−xmin\hat x_1=\frac{x_1-x_{min}}{x_{max}-x_{min}}x^1=xmax−xminx1−xmin
- x^1=x1−μδ\hat x_1=\frac{x_1-\mu}{\delta}x^1=δx1−μ
代码
在实际的梯度下降过程中,为加速计算,并不会使用for循环来计算代价函数,而是通过矩阵运算来替代。代码如下:
# 正则化,归一化特征
def normalization(data):
for i in range(0, data.shape[-1]):
data[:,i] = (data[:,i]-np.mean(data[:,i]))/np.std(data[:,i])
return data
x = normalization(x)
x = np.hstack(np.ones((x.shape[0],1)), x)
w = np.random.normal(0, 1, size=(x.shape[1], 1))
learning_rate = 0.1
# 划分训练测试集
train_x, train_y, test_x, test_y = split_train_test_data(x, y)
m = train_x.shape[0]
# train
for i in range(100000):
h = np.matmul(train_x,w)
cost = h-train_y
loss = cost.T@cost
w = w - learning_rate*(train_x.T@cost)/m
print("loss:",loss)
# test
test_loss = 0
for i in range(test_x.shape[0]):
h = np.matmul(test_x,w)
cost = h-test_y
test_loss = test_loss + cost.T@cost
print(test_loss/test_x.shape[0])
四.α的取值策略
1.α取值
- α过大,可能导致代价函数震荡甚至无法收敛
- α过小,收敛速度过慢
2.α取值技巧
尝试多个α值,并观察代价函数的收敛,不断调整α值使得收敛速度和准确度达到平衡.
五.拟合非线性函数
当训练数据用线性函数无法较好拟合时,出现非线性函数.例如假设函数变为hθ(x)=θ0+θ1x+θ2x2h_\theta(x)=\theta_0+\theta_1x+\theta_2x^2hθ(x)=θ0+θ1x+θ2x2
这时我们如何继续使用线性回归来解决该问题呢,方法很简单,就是将x2x^2x2当做特征量x2x_2x2,这样假设函数变成了hθ(x)=θ0+θ1x1+θ2x2h_\theta(x)=\theta_0+\theta_1x_1+\theta_2x_2hθ(x)=θ0+θ1x1+θ2x2
但是这样x2x_2x2和x1x_1x1的值相差较大,此时特征缩放就起到了很好的作用.