python實現線性回歸算法
本文用python實現線性回歸算法,供大家參考,具體內容如下
# -*- coding: utf-8 -*-'''Created on Fri Oct 11 19:25:11 2019'''from sklearn import datasets, linear_model # 引用 sklearn庫,主要為了使用其中的線性回歸模塊# 創建數據集,把數據寫入到numpy數組import numpy as np # 引用numpy庫,主要用來做科學計算import matplotlib.pyplot as plt # 引用matplotlib庫,主要用來畫圖data = np.array([[152,51],[156,53],[160,54],[164,55], [168,57],[172,60],[176,62],[180,65], [184,69],[188,72]])# 打印出數組的大小print(data.shape)# TODO 1. 實例化一個線性回歸的模型model=linear_model.LinearRegression()# TODO 2. 在x,y上訓練一個線性回歸模型。 如果訓練順利,則regr會存儲訓練完成之后的結果模型x,y=data[:,0].reshape(-1,1),data[:,1]regr=model.fit(x,y)# TODO 3. 畫出身高與體重之間的關系plt.scatter(x,y,color='red')# 畫出已訓練好的線條plt.plot(x, regr.predict(x), color=’blue’)# 畫x,y軸的標題plt.xlabel(’height (cm)’)plt.ylabel(’weight (kg)’)plt.show() # 展示# 利用已經訓練好的模型去預測身高為163的人的體重print ('Standard weight for person with 163 is %.2f'% regr.predict([[163]]))
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: