前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables)

机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables)

作者头像
大数据流动
发布2019-08-08 11:52:16
4550
发布2019-08-08 11:52:16
举报
文章被收录于专栏:实时计算

机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables)

同样是预测房价问题 如果有多个特征值

那么这种情况下 假设h表示为

公式可以简化为

两个矩阵相乘 其实就是所有参数和变量相乘再相加 所以矩阵的乘法才会是那样

那么他的代价函数就是

同样是寻找使J最小的一系列参数

python代码为

比如这种 那么X是[1,2,3] y也是[1,2,3] 那么令theta0 = 0 theta1 = 1 这个函数返回值为0最小 theta0 = 0 theta1=0的话 返回值是2.333

要考虑是否需要特征缩放,特征缩放就是特征分配不均时 会导致梯度下降耗费更多 为了让梯度下降更快

所以

如何选择学习率α呢

梯度下降算法的每次迭代受到学习率的影响,如果学习率 过小,则达到收敛所需的迭代次数会非常高,如果学习率过大,每次迭代可能不会减小代价函数,可能会越过局部最小值导致无法收敛。

通常可以考虑尝试些学习率:0.01,0.03,0.3,1,3,10

而有的时候线性回归并不适用于所有的模型,这个时候我们要考虑用多项式模型

这个时候特征缩放就很重要

梯度下降 线性回归的python代码

# -*- coding=utf8 -*-

import math;

def sum_of_gradient(x, y, thetas): """计算梯度向量,参数分别是x和y轴点坐标数据以及方程参数""" m = len(x); grad0 = 1.0 / m * sum([(thetas[0] + thetas[1] * x[i] - y[i]) for i in range(m)]) grad1 = 1.0 / m * sum([(thetas[0] + thetas[1] * x[i] - y[i]) * x[i] for i in range(m)]) return [grad0, grad1];

def step(thetas, direction, step_size): """move step_size in the direction from thetas""" return [thetas_i + step_size * direction_i for thetas_i, direction_i in zip(thetas, direction)]

def distance(v, w): """两点的距离""" return math.sqrt(squared_distance(v, w))

def squared_distance(v, w): vector_subtract = [v_i - w_i for v_i, w_i in zip(v, w)] return sum(vector_subtract_i * vector_subtract_i for vector_subtract_i, vector_subtract_i in zip(vector_subtract, vector_subtract))

def gradient_descent(stepSize, x, y, tolerance=0.000000001, max_iter=100000): """梯度下降""" iter = 0 # initial theta thetas = [0, 0]; # Iterate Loop while True: gradient = sum_of_gradient(x, y, thetas);

next_thetas = step(thetas, gradient, stepSize);

if distance(next_thetas, thetas) < tolerance: # stop if we're converging break thetas = next_thetas # continue if we're not

iter += 1 # update iter

if iter == max_iter: print 'Max iteractions exceeded!' break;

return thetas

x = [1, 2, 3]; y = [5, 9, 13]; stepSize = 0.001; t0, t1 = gradient_descent(-stepSize, x, y); print t0, " ", t1;

线性回归还有一种更简单的 就是正规方程

这个是用数学推导出来的

两者对比:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-11-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档