线性回归代码实现

本文介绍了线性回归的三种形式:单变量、多变量和多项式回归。通过数学公式展示了模型结构,并提供了手工构造数据的运行结果链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 单变量线性回归: h(x)=theta0 + theta1* x 1
  • 多变量线性回归: h(x)=theta0 + theta1* x 1 + theta2* x 2 + theta3* x 3
  • 多项式回归: h(x)=theta0 + theta1* x 1 + theta2* (x2^2) + theta3* (x3^3)
import numpy as np
from pylab import *

def train_wb(X, y):
    """
    :param X:N*D的数据
    :param y:X对应的y值
    :return: 返回(w,b)的向量
    """
    if np.linalg.det(X.T * X) != 0:
        wb = ((X.T.dot(X).I).dot(X.T)).dot(y)
        return wb

def test(x, wb):
    return x.T.dot(wb)

def getdata():
    x = []; y = []
    file = open("ex0.txt", 'r')
    for line in file.readlines():
        temp = line.strip().split("\t")
        x.append([float(temp[0]),float(temp[1])])
        y.append(float(temp[2]))
    return (np.mat(x), np.mat(y).T)

def draw(x, y, wb):

    #画回归直线y = wx+b
    a = np.linspace(0, np.max(x)) #横坐标的取值范围
    b = wb[0] + a * wb[1]
    plot(x, y, '.')
    plot(a, b)
    show()

X, y = getdata()
wb = train_wb(X, y)
draw(X[:, 1], y, wb.tolist())


  • 运行结果
    在这里插入图片描述

  • 手工造的数据

在这里插入图片描述

https://blog.youkuaiyun.com/u014028027/article/details/72667733
https://blog.youkuaiyun.com/weixin_40683253/article/details/81109129

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值