使用乙個線性回歸模型來擬合身高 體重的資料

2021-10-23 02:03:44 字數 1722 閱讀 9783

1、建立資料集

#引用sklearn庫,為了使用其中的線性回歸模組

from sklearn.linear_model import linearregression

#引用numpy庫,做科學計算

import numpy as np

#引用matplotlib庫,用來畫圖

import matplotlib.pyplot as plt

#建立資料集,把資料寫入到numpy陣列

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)

2、對資料進行變形

由於在呼叫的sklearn裡封裝好的一些模型來建模時,對訓練資料的輸入x要求是二維陣列,所以需要對資料進行變形。如下所示:

x,y = data[:,

0].reshape(-1

,1),data[:,

1]

reshape(行數,列數)常用來更改資料的行列數目

-1是指未設定行數,程式隨機分配

reshape(-1,1)表示(任意行,1列)

相當於:

x = data[:,

0].reshape(-1

,1)y = data[:,

1]

3、利用線性回歸來擬合資料

#例項化乙個線性回歸的模型

regr = linearregression(

).fit(x,y)

# fit() 用來分析模型引數

#在x,y上訓練乙個線性回歸模型。若訓練順利,則regr會儲存訓練完成後的結果模型

regr.score(x,y)

4、畫出身高與體重之間的關係

# 畫出已訓練好的線條

plt.plot(x, regr.predict(x)

, color=

'blue'

)#畫x,y軸的標題

plt.xlabel(

'height (cm)'

)plt.ylabel(

'weight (kg)'

)plt.show(

)# 展示

5、**體重

利用訓練好的模型輸入身高去**體重

height =

int(

input

("input your height>>>"))

print

("standard weight for person with %d is %.2f"

%(height, regr.predict(

[[height]])

))

貪心學院機器學習課程筆記

3 使用Keras 神經網路來擬合非線性模型

import keras import numpy as np import matplotlib.pyplot as plt sequential按順序構成的模型 from keras.models import sequential dense全連線層 from keras.layers imp...

TensorFlow實現乙個簡單線性回歸的例子

1 author wsx 2import tensorflow as tf 3import numpy as np 4import matplotlib.pyplot as plt 56 x data np.linspace 0.5,0.5,200 np.newaxis 0.5 0.5 之間產生20...

簡單線性回歸(乙個特徵)學習筆記

假設這樣當給出新的 目標 x 和 y 都是已知的 需要求出 a 斜率 b 截距。最小二乘法 最小二乘法 又稱最小平方法 是一種數學優化技術。它通過最小化誤差的平方和尋找資料的最佳函式匹配。誤差的平方 將損失函式。最小二乘法 稱這個損失函式為 對 就是根據推到得到,當 通過傳入 x train y t...