第1章 統計學習方法概論
- 高斯於1823年在誤差e1 ,… , en獨立同分布的假定下,證明了最小二乘方法的一個最優性質: 在所有無偏的線性估計類中,最小二乘方法是其中方差最小的!
- 無偏估計是用樣本統計量來估計總體參數時的一種無偏推斷。 估計量的數學期望等於被估計參數的真實值,則稱此此估計量爲被估計參數的無偏估計,即具有無偏性,是一種用於評價估計量優良性的準則。 無偏估計的意義是:在多次重複下,它們的平均數接近所估計的參數真值。
使用最小二乘法擬和曲線
對於數據
擬合出函數
有誤差,即殘差:
此時L2範數(殘差平方和)最小時,h(x) 和 y 相似度最高,更適合擬合
一般的H(x)爲n次的多項式,
爲參數
最小二乘法就是要找到一組 使得 (殘差平方和) 最小
即,求
例如書本P11,例1.1中,我們用目標函數, 加上一個正太分佈的噪音干擾,用多項式去擬合
代碼:
import numpy as np
import scipy as sp
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
%matplotlib inline
ps: numpy.poly1d([1,2,3]) 生成
# 目標函數
def real_func(x):
return np.sin(2*np.pi*x)
# 多項式
def fit_func(p, x):
f = np.poly1d(p)
return f(x)
# 殘差
def residuals_func(p, x, y):
ret = fit_func(p, x) - y
return ret
# 十個點
x = np.linspace(0, 1, 10)
x_points = np.linspace(0, 1, 1000)
# 加上正態分佈噪音的目標函數的值
y_ = real_func(x)
y = [np.random.normal(0, 0.1)+y1 for y1 in y_]
def fitting(M=0):
"""
n 爲 多項式的次數
"""
# 隨機初始化多項式參數
p_init = np.random.rand(M+1)
# 最小二乘法
p_lsq = leastsq(residuals_func, p_init, args=(x, y))
print('Fitting Parameters:', p_lsq[0])
# 可視化
plt.plot(x_points, real_func(x_points), label='real')
plt.plot(x_points, fit_func(p_lsq[0], x_points), label='fitted curve')
plt.plot(x, y, 'bo', label='noise')
plt.legend()
return p_lsq
# M=0
p_lsq_0 = fitting(M=0)
# M=1
p_lsq_1 = fitting(M=1)
# M=9
p_lsq_9 = fitting(M=9)
當M=9時,多項式曲線通過了每個數據點,但是造成了過擬合
1.0.2 正則化
結果顯示過擬合, 引入正則化項(regularizer),降低過擬合。
模型選擇的典型方法是正則化,正則化是結構風險最小化策略的實現,是在經驗風險上加一個正則化向或懲罰項。正則化項一般是模型複雜度的單調遞減函數,模型月複雜,正則化值越大。
正則化一般具有如下形式:
。並使得Q(x)取得最小
$Q(x)
迴歸問題中,損失函數是平方損失,正則化可以是參數向量的L2範數,也可以是L1範數。
-
L1: regularization*abs§
-
L2: 0.5 * regularization * np.square§
regularization = 0.0001
def residuals_func_regularization(p, x, y):
ret = fit_func(p, x) - y
ret = np.append(ret, np.sqrt(0.5*regularization*np.square(p))) # L2範數作爲正則化項
return ret
# 最小二乘法,加正則化項
p_init = np.random.rand(9+1)
p_lsq_regularization = leastsq(residuals_func_regularization, p_init, args=(x, y))
plt.plot(x_points, real_func(x_points), label='real')
plt.plot(x_points, fit_func(p_lsq_9[0], x_points), label='fitted curve')
plt.plot(x_points, fit_func(p_lsq_regularization[0], x_points), label='regularization')
plt.plot(x, y, 'bo', label='noise')
plt.legend()