一元线性回归模型

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))
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页