线性回归(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) # aprint("預測值:",predict_value) # yshow_linear_line(X,Y) main()(3)輸出:
(4)樣本以及擬合的直線
總結
以上是生活随笔為你收集整理的线性回归(y=ax+b)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pl/sql过程(一)
- 下一篇: oracle游标遍历的三种方式