一元线性回归模型

按西瓜书公式写的,比较简陋,但可以运行帮助理解

import math
D = [(65, 6), (50, 5), (120, 15), (98, 12), (51, 6), (66, 8), (70, 10), (78, 11), (75, 10), (120, 8), (45, 7)]
# 该数据集表示(体重,血糖值) 体重为x 血糖值为标记
# 一元线性回归试图求得g=ax+b使g拟合f  输入一个新的x,得g(x)来预测f(x)

#求w
def getW(D):
    w = 0
    x_mean = 0
    total = 0
    i = 0
    for element in D:
        total = total+element[0]
        i = i+1
    x_mean = total/i
    #定义分子
    fenzi = 0
    fenmu = 0
    #计算分子
    total_fenzi = 0
    for element in D:
        total_fenzi=total_fenzi+(element[1]*(element[0]-x_mean))
    #分母第一项和分母第二项
    fenzi = total_fenzi
    fenmu_1 = 0
    fenmu_2 = 0
    fenmu_2_total = 0
    for element in D:
        fenmu_1 = fenmu_1+element[0]*element[0]
    j = 0
    for element in D:
        fenmu_2_total = fenmu_2_total+element[0]
        j = j+1
    fenmu_2 = (fenmu_2_total*fenmu_2_total)/j
    fenmu = fenmu_1-fenmu_2
    w = fenzi/fenmu
    return w


#计算b
w = getW(D)
def getB(D, w):
    i = 0   #计数器
    b = 0
    b_element = 0
    for element in D:
        b_element = b_element+(element[1]-w*element[0])
        i = i+1
    b = b_element/i
    return b
b = getB(D,w)

test = 0
def g(test, D):
    z = 0
    z = w*test+b
    return z
print("输出学得模型w值为:")
print(w)
print("输出学得模型B值为:")
print(b)
print("测试输入3所得g(x)为多少:")
print(g(45, D))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值