基于最小二乘法的线性回归

import numpy as np


def inverse_matrix(matrix):  # 利用svd分解求逆矩阵
    u, s, vh = np.linalg.svd(matrix, full_matrices=False)
    # print(u, s, vh)
    c = np.linalg.multi_dot([u * s, vh])
    inverse = np.linalg.multi_dot([vh.T * 1 / s, u.T])
    return inverse


test = [15, 12, 1]  # 训练集,注意最后一个维度的元素值一定为1
data = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [1, 5]]  # 训练集
label = [3, 7, 11, 15, 19, 6]  # 标签


def linear_regression(test, data, label):  # 最小而成求参数w,注意此w包含权重w和偏置b两部分
    y = np.array(label)
    x_test = np.array(test)
    x = np.array(data)
    x_1 = np.ones(x.shape[0])
    x = np.c_[x, x_1]
    # print(np.dot(x.T, x).shape, x.T.shape, y.T.shape)
    w = np.linalg.multi_dot([inverse_matrix(np.dot(x.T, x)), x.T, y.T])  # 核心公式,参考《机器学习》p.55的右下角公式
    f_x = np.dot(x_test.T, w)
    return f_x


print(linear_regression(test, data, label))  # 打印预测值

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>