擬合

醉閣夢春雨發表於2020-10-09

擬合

一元線性擬合

在這裡插入圖片描述

在這裡插入圖片描述

python畫圖程式碼

import matplotlib.pyplot as plt
import pandas as pd


def Unary_linear_fitting(arr_x, arr_y):
    x_average = 0
    y_average = 0
    for i in range(len(arr_x)):
        x_average = x_average + arr_x[i]
        y_average = y_average + arr_y[i]
    x_average = x_average / len(arr_x)
    y_average = y_average / len(arr_y)
    temp1 = 0
    temp2 = 0
    for i in range(len(arr_x)):
        temp1 = temp1 + (arr_x[i] - x_average) * (arr_y[i] - y_average)
        temp2 = temp2 + (arr_x[i] - x_average) * (arr_x[i] - x_average)
    b = temp1 / temp2
    a = y_average - b * x_average
    return a, b


data = pd.read_csv("大學男生身高體重資料.csv")
height = data["身高"]
weight = data["體重"]
a, b = Unary_linear_fitting(height, weight)
print(a, b)
plt.plot([160, 195], [160 * b + a, 195 * b + a], label='Unary_linear_fitting')
plt.title("Unary_linear_fitting")
plt.scatter(height, weight, label='The original data')
plt.legend(loc="upper left")
plt.xlabel("height")
plt.ylabel("weight")
plt.show()


未完待續

相關文章