def linear_plot():
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
data = [[5.06, 5.79], [4.92, 6.61], [4.67, 5.48], [4.54, 6.11], [4.26, 6.39],
[4.07, 4.81], [4.01, 4.16], [4.01, 5.55], [3.66, 5.05], [3.43, 4.34],
[3.12, 3.24], [3.02, 4.80], [2.87, 4.01], [2.64, 3.17], [2.48, 1.61],
[2.48, 2.62], [2.02, 2.50], [1.95, 3.59], [1.79, 1.49], [1.54, 2.10]]
data=np.array(data)
x=np.array(data[:,0])
y=np.array(data[:,1])
fig=plt.figure()
plt.scatter(x,y)
x_mean = np.mean(x)
y_mean = np.mean(y)
up = np.sum((x - x_mean) * (y- y_mean))
down = np.sum((x - x_mean) * (x - x_mean))
w= up / down
w=np.round(w,2)
b= y_mean - w* x_mean
b=np.round(b,2)
plt.plot(x,w*x+b,c='red')
fig.show()
return w,b,fig
def linear_plot1():
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
data = [[5.06, 5.79], [4.92, 6.61], [4.67, 5.48], [4.54, 6.11], [4.26, 6.39],
[4.07, 4.81], [4.01, 4.16], [4.01, 5.55], [3.66, 5.05], [3.43, 4.34],
[3.12, 3.24], [3.02, 4.80], [2.87, 4.01], [2.64, 3.17], [2.48, 1.61],
[2.48, 2.62], [2.02, 2.50], [1.95, 3.59], [1.79, 1.49], [1.54, 2.10]]
data=np.array(data)
x = np.array(data[:, 0])
y=np.array(data[:,1])
l=LinearRegression()
l.fit(x.reshape(-1,1),y.reshape(-1,1))
w=l.coef_
b=l.intercept_
w = np.round(w, 2)
b = np.round(b, 2)
y_predict = l.predict(x.reshape(-1,1))
fig=plt.figure()
plt.scatter(x,y)
plt.plot(x,y_predict,c='r')
plt.axis([0,7,0,8])
plt.show()
return w,b,fig
介紹
線性迴歸是機器學習中最基礎、最重要的方法之一。接下來,你需要根據題目提供的數據點,完成線性擬合,並繪製出圖像。
目標
題目給出一個二維數組如下,共計 20 個數據樣本。
data = [[5.06, 5.79], [4.92, 6.61], [4.67, 5.48], [4.54, 6.11], [4.26, 6.39],
[4.07, 4.81], [4.01, 4.16], [4.01, 5.55], [3.66, 5.05], [3.43, 4.34],
[3.12, 3.24], [3.02, 4.80], [2.87, 4.01], [2.64, 3.17], [2.48, 1.61],
[2.48, 2.62], [2.02, 2.50], [1.95, 3.59], [1.79, 1.49], [1.54, 2.10], ]
你需要根據這 20 個樣本,使用線性迴歸擬合,得到自變量係數及截距項。
\displaystyle y(x, w) = wx + by(x,w)=wx+b
其中,ww 即爲自變量係數,bb 則爲常數項。
最後,需要使用 Matplotlib 將數據樣本繪製成散點圖,並將擬合直線一併繪出。
要求
全部代碼寫在
linear_plot()
函數內部。計算出自變量係數 ww 及截距項 bb 的數值,保留兩位小數(浮點數類型)並返回。
繪製出樣本散點圖,並根據參數將擬合直線繪於圖中,最後返回繪圖對象。
代碼保存在
linear_regression.py
文件中,並將該文件放置在/home/shiyanlou/Code
路徑下方。
提示
你可以使用自行實現的最小二乘法函數計算 ww 和 bb 的值,也可以使用 scikit-learn 提供的線性迴歸類完成。提示代碼如下:
def linear_plot():
"""
參數:無
返回:
w -- 自變量係數, 保留兩位小數
b -- 截距項, 保留兩位小數
fig -- matplotlib 繪圖對象
"""
data = [[5.06, 5.79], [4.92, 6.61], [4.67, 5.48], [4.54, 6.11], [4.26, 6.39],
[4.07, 4.81], [4.01, 4.16], [4.01, 5.55], [3.66, 5.05], [3.43, 4.34],
[3.12, 3.24], [3.02, 4.80], [2.87, 4.01], [2.64, 3.17], [2.48, 1.61],
[2.48, 2.62], [2.02, 2.50], [1.95, 3.59], [1.79, 1.49], [1.54, 2.10], ]
### TODO: 線性擬合計算參數 ###
w = None
b = None
fig = plt.figure() # 務必保留此行,設置繪圖對象
### TODO: 按題目要求繪圖 ###
return w, b, fig # 務必按此順序返回
如需使用 scikit-learn, Pandas 等第三方模塊,可以通過 /home/shiyanlou/anaconda3/bin/python
路徑執行。
圖像示例:
知識點
- 線性迴歸擬合
- Matplotlib 繪圖