Python筆記2

Huang Luen
5 min readSep 11, 2020

--

scikit-learn 線性回歸&機器學習

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

x=np.linspace(0,5,50) #設定x為50筆資料

y1=1.2*x+0.8 #設定y1為x的應變數

y2=1.2*x+0.8+0.6*np.random.randn(50) #設定y2為x加上亂數的應變數

plt.scatter(x,y2)
plt.plot(x,y1,”r”) #繪圖比較加亂數(y2)與無亂數(y1)

regr=LinearRegression()
X=x.reshape(50,1) #調整x資料reshape成50個list,因要使用fit()必須使用此格式

regr.fit(X,y2) #使用調整的X與y2(有殘差項)fit出回歸式
Y=regr.predict(X)利用X資料的預測值設為Y

plt.scatter(x,y2)
plt.plot(x,Y,”r”)#繪圖比較預測值Y與原始資料y2的差異

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

#資料訓練

x=np.linspace(0,5,100)
y=1.2*x+0.8+0.5*np.random.randn(100) #設定raw data

plt.scatter(x,y) #畫出要訓練的資料(raw data)

from sklearn.model_selection import train_test_split
#import 套件,用途:將raw data分類成training data&testing data

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=87) #20%的raw data設為testing data , 80%為training data

x_train=x_train.reshape(80,1) #改法1,原本資料是1*80 ,將其改成80*1才能使用sklearn

x_test.shape=(20,1) #改法2,將1*20改成20*1

from sklearn.linear_model import LinearRegression #import線性回歸套件

regr=LinearRegression()

regr.fit(x_train,y_train) #使用training data fit出回歸方程式

plt.plot(x_test,regr.predict(x_test),”r”) #機器訓練出的回歸式預測並畫線
plt.scatter(x_test,y_test) #將測試資料畫成散佈圖 觀察訓練效果

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

#用sklearn中的datasets做預測

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_boston #import boston資料

boston=load_boston() #將load_boston data設為boston

X=boston.data #抓出boston資料變數
Y=boston.target #抓出boston資料應變數

#繪製Boston的各features與房價price的關係圖

(使用enumerate小技巧寫出簡短迴圈)

X=boston.data
Y=boston.target
plt.figure(figsize=(8,10)) #figsize設定width , height
for i,feature in enumerate(boston.feature_names):
plt.subplot(5,3,i+1) #格式為5*3, 第i+1張圖
plt.scatter(X[:,i],Y,s=3)#取X中所有rows並取X中的i column #s為調整散佈點大小
plt.ylabel(“Price”)
plt.xlabel(feature) #X軸由feature迭代
plt.tight_layout()

--

--