一元線性迴歸模型

清新的改革之風發表於2020-09-28
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))

相關文章