sklearn 线性回归_使用sklearn库做线性回归拟合
生活随笔
收集整理的這篇文章主要介紹了
sklearn 线性回归_使用sklearn库做线性回归拟合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景資料
隨著海拔高度的上升,溫度越來越低,經過氣象專家的研究,在一定的海拔高度范圍內,高度和溫度呈線性關系?,F有一組實測資料,我們需要對這些數據進行處理擬合,獲得此線性關系。
解決思路
采用sklearn庫中的LinearRegression線性回歸類進行擬合。
代碼
# 導入所需的模塊 import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression# 已有數據 height = [0.0, 500.0, 1000.0, 1500.0, 2000.0, 2500.0, 3000.0, 3500.0, 4000.0] temperature = [12.834044009405147, 10.190648986884316, 5.50022874963469, 2.8546651452636795, -0.7064882183657739, -4.065322810462405, -7.1274795772446575, -10.058878545913904, -13.206465051538661]# 數據處理 # sklearn 擬合輸入輸出一般都是二維數組,這里將一維轉換為二維。 height = np.array(height).reshape(-1, 1) temp = np.array(temperature).reshape(-1, 1)# 擬合 reg = LinearRegression() reg.fit(height, temp) a = reg.coef_[0][0] # 系數 b = reg.intercept_[0] # 截距 print('擬合的方程為:Y = %.6fX + %.6f' % (a, b)) # out: 擬合的方程為:Y = -0.006570X + 12.718507# 可視化 prediction = reg.predict(height) # 根據高度,按照擬合的曲線預測溫度值 plt.figure('海拔高度~溫度關系曲線擬合結果', figsize=(12,8)) plt.rcParams['font.family'] = ['sans-serif'] # 設置matplotlib 顯示中文 plt.rcParams['font.sans-serif'] = ['SimHei'] # 設置matplotlib 顯示中文 plt.xlabel('溫度') plt.ylabel('高度') plt.scatter(temp, height, c='black') plt.plot(prediction, height, c='r') plt.show()海拔高度~溫度曲線擬合結果總結
以上是生活随笔為你收集整理的sklearn 线性回归_使用sklearn库做线性回归拟合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 围棋经典棋谱_秀秀老师:茶艺师也要学好围
- 下一篇: loadrunner发送json_Loa