zoukankan      html  css  js  c++  java
  • 机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables)

    机器学习(三)--------多变量线性回归(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;

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

    这个是用数学推导出来的

     两者对比: 

  • 相关阅读:
    HDU 1425:sort
    HDU 1021:Fibonacci Again
    HDU 2035:人见人爱A^B
    HDU 1061:Rightmost Digit
    HDU 1005:Number Sequence
    HDU 1008:Elevator
    HDU 1004:Let the Balloon Rise
    HDU 2018:母牛的故事
    java推荐书籍及下载
    VC6.0 快捷键
  • 原文地址:https://www.cnblogs.com/tree1123/p/9996294.html
Copyright © 2011-2022 走看看