1. 程式人生 > >線性迴歸(y=ax+b)

線性迴歸(y=ax+b)

線性迴歸主要是擬合一個函式,能預測一個新的樣本:

(1)資料集如下:

(2)預測值:feet=500

# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import linear_model
import os
os.chdir("/Users/xxx/PycharmProjects/dataset/")
filename = "input_data.xlsx"
datafile = pd.read_excel(filename, index_col=u'ID')
# 獲取資料
def get_data(datafile):
    x_paramter = []
    y_paramter = []
    for feet,price in zip(datafile['feet'],datafile['price']):
        x_paramter.append([float(feet)])
        y_paramter.append(float(price))
    return x_paramter,y_paramter
# 線性迴歸模型
def linear_model_main(x_paramter,y_paramter,predict_value):
    # 建立線性迴歸物件
    regr = linear_model.LinearRegression()
    regr.fit(x_paramter,y_paramter) # 建立模型
    predict_outcome = regr.predict(predict_value) # 預測值
    return regr.intercept_,regr.coef_,predict_outcome # 返回截距、斜率、預測結果
# 顯示線性擬合模型的結果
def show_linear_line(x_paramter,y_paramter):
    regr = linear_model.LinearRegression()
    regr.fit(x_paramter,y_paramter)
    plt.scatter(x_paramter,y_paramter,color="blue")
    x_new = [[0],[500]] # x軸長
    plt.plot(x_new,regr.predict(x_new),color="red",linewidth=2)
    plt.xlabel(u'Feet',color="green")
    plt.ylabel(u'Price',color="green")
    # plt.plot(label=u'資料圖')
    # plt.xticks(())
    # plt.yticks(())
    plt.ylim(-2000,20000)
    plt.xlim(0,500)
    plt.show()
def main():
    X,Y = get_data(datafile)
    print('X:',X)
    print('Y:',Y)
    predictvalue = [[500]]
    intercept,coefficient,predict_value = linear_model_main(X,Y,predictvalue)
    print("截距:",intercept) # b ( y=ax+b )
    print("斜率:",coefficient) # a
    print("預測值:",predict_value) # y
    show_linear_line(X,Y)
main()

(3)輸出:

(4)樣本以及擬合的直線