Python機器學習 學習筆記與實踐
環境:win10 + Anaconda3.8
例子一 源自《Python與機器學習實戰》—何宇健
任務:現有47個房子的面積和價格,需要建立一個模型對房價進行預測,
1、獲取和處理資料
房子的面積與價格對應的資料點擊下面獲得:
點擊此處獲取
匯入庫,并讀取文本檔案的資料:
import numpy as np
import matplotlib.pyplot as plt
#讀取房子面積和對應的價格資料
x,y=[],[]
for sample in open("此處為資料文本檔案路徑","r"):
#文本檔案中資料用“,”隔開,故向_x,_y傳入資料時引入split函式
_x,_y=sample.split(",")
#采用append方法將轉換為float型別的_x,_y賦值給x,y
x.append(float(_x))
y.append(float(_y))
#將x,y轉換為Numpy陣列
x,y=np.array(x),np.array(y)
#將x標準化
x=(x-x.mean())/x.std()
(1)由于x,y的資料型別是List,故在保存簡單的數值型資料時,處理不夠高效,因此將其轉換為Numpy陣列,
(2)保留x的原始值也是可以的,但標準化后可以降低問題的復雜度,x標準化公式為:(x-x平均值)/ x的標準差
(3)在此也可以選擇觀察散點圖,觀察后發現資料很可能有線性關系,因此下面模型采用線性回歸的多項式擬合,
2、多項式擬合
#利用linspace函式,產生-2到4之間的等間隔100個數
x0=np.linspace(-2,4,100)
#定義模型函式
def get_model(deg):
return lambda input_x=x0:np.polyval(np.polyfit(x,y,deg),input_x)
#定義損失函式
def get_cost(deg,calcu_x,data_y):
return 0.5*((get_model(deg)(calcu_x)-data_y)**2).sum()
#定義測驗階數集并分別計算不同階模型的損失
test_set=(1,4,10)
for d in test_set:
print('The loss of degree{} is {}'.format(d,get_cost(d,x,y)))
#畫圖
plt.figure()
plt.title('Easy example of the price of house')
#將原始資料畫為散點圖
plt.scatter(x,y,c="g",s=6)
#限定橫縱坐標
plt.xlim(-2,4)
plt.ylim(1e5,8e5)
#分別畫出不同階模型的擬合曲線
for d in test_set:
plt.plot(x0,get_model(d)(),label='degree={}'.format(d))
plt.legend()
plt.show()
(1)np.linspace簡單用法:
np.linspace(a,b,num),生成a到b的等間隔的num個數
(2)polyfit函式簡單講解:
def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)
Least squares polynomial fit.
Fit a polynomial p(x) = p[0] * x**deg + … + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error in the order deg, deg-1, … 0.
(3)polyval函式簡單講解:
def polyval(p, x)
Evaluate a polynomial at specific values.
If p is of length N, this function returns the value:
`p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]`
If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.
(4)損失函式
損失函式采用常用的平方損失函式,即歐氏距離,
(5)注意:plt.show(),不要忘記括號,
3、運行結果


4、小結
從損失結果中看,階數為1的時候損失最大,階數為10的時候損失最小,但從圖中看到,似乎當階數等于1或4的時候能更好地描述這個模型,這就是過擬合現象,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/234903.html
標籤:python
