梯度下降(二)

上一节中的梯度下降法只能由于单自变量的线性回归任务,梯度下降法可以推广至任意多变量的线性回归任务,公式推导如下如

使用矩阵表达的公式在numpy库下代码非常简洁,其中X以二维ndarray对象输入,每一行代表一个样本,Y和theta以一维ndarray对象输入,以以下这个三变量线性回归为例子

import numpy as np

X = np.array([[425.5, 8.12, 17.5],
              [422.3, 8.32, 22.9],
              [418.0, 8.36, 23.7],
              [419.2, 8.20, 21.1],
              [384.2, 8.86, 23.3],
              [372.5, 7.70, 19.1],
              [372.9, 8.46, 18.2],
              [380.8, 8.88, 22.2],
              [401.7, 9.00, 27.6],
              [406.5, 8.80, 28.8],
              [410.5, 9.26, 27.8]])

Y = np.array([7.450, 7.605, 7.855, 7.805, 6.900,
              7.470, 7.385, 7.225, 8.130, 8.720, 9.145])

Theta = np.array([0.0, 0.0, 0.0, 0.0])


def batch_gradient_descent(x_data, y_data, theta, max_iter=10000, learning_rate=0.03):

    # 数据预处理
    x_data = np.insert(x_data, 0, values=1, axis=1)
    y_data = np.mat(y_data).T
    theta = np.mat(theta).T

    # 常量定义
    sample_size = len(x_data)

    # 梯度下降主体
    for i in range(max_iter):

        # 判断是否到达极值点
        cost = np.sum(np.asarray(x_data * theta - y_data) ** 2) / sample_size
        if cost < 0.0001:
            break

        # 更新theta参数
        theta -= (learning_rate / sample_size) * x_data.T * (x_data * theta - y_data)

    return theta


print(batch_gradient_descent(X, Y, Theta, learning_rate=0.00001))

计算得出结果为[[0.00052653] [0.01435526] [0.01073678] [0.08430573]],此时cost为0.18

posted @ 2020-07-29 16:21  LoongChan  阅读(313)  评论(0编辑  收藏  举报