文章目錄
- 擬合損失函數
- 一、線性擬合
- 1.1 介紹
- 1.2 代碼可視化
- 1.2.1 生成示例數據
- 1.2.2 損失函數
- 1.2.3 繪制三維圖像
- 1.2.4 繪制等高線
- 1.2.5 損失函數關于斜率的函數
- 二、 多變量擬合
- 2.1 介紹
- 2.2 代碼可視化
- 2.2.1 生成示例數據
- 2.2.2 損失函數
- 2.2.3 繪制等高線
- 三、 多項式擬合
- 3.1 介紹
- 3.2 公式表示
擬合損失函數
下一篇文章有如何通過損失函數來進行梯度下降法。
一、線性擬合
1.1 介紹
使用最小二乘法進行線性擬合,即,
h θ ( x ) = θ 0 + θ 1 x h_{\theta}(x) = \theta_{0}+\theta_{1}x hθ?(x)=θ0?+θ1?x
其中, θ 0 \theta_{0} θ0?和 θ 1 \theta_{1} θ1?是參數,需要通過已經給出的數據進行擬合,這里不進行具體的計算.
損失函數為:
J ( θ 0 , θ 1 ) = 1 2 m ∑ i = 1 m ( h θ ( x ( i ) ) ? y ( i ) ) 2 J(\theta_{0},\theta_{1})=\frac{1}{2m}\sum_{i=1}^{m}(h_{\theta}(x^{(i)})-y^{(i)})^2 J(θ0?,θ1?)=2m1?i=1∑m?(hθ?(x(i))?y(i))2
即線性擬合的目的即是達到 min θ J ( θ 0 , θ 1 ) \text{min}_{\theta} J(\theta_{0},\theta_{1}) minθ?J(θ0?,θ1?)
因此我們可以采取梯度下降法進行擬合。
而,不同的 θ 0 \theta_{0} θ0?和 θ 1 \theta_{1} θ1?獲取到不同的損失,我們可以先繪制損失函數的圖像,進行參數的預估計。
即,使用matplotlib的三維圖像繪制來確定,以及可以使用等高線來進行完成。
1.2 代碼可視化
1.2.1 生成示例數據
import numpy as np
import matplotlib.pyplot as plt# 生成示例數據
x = np.linspace(0, 10, 100)
y = 2 * x + 3 + np.random.normal(0, 2, 100) # y = 2x + 3 + 噪聲
# 繪制散點圖,根據散點圖大致確定參數范圍
plt.scatter(x, y)
plt.title("Data analysis")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
1.2.2 損失函數
def mse_loss(t0, t1, x, y):# 定義損失函數y_pred = t1 * x + t0return np.mean((y - y_pred) ** 2) / 2
1.2.3 繪制三維圖像
t0_, t1_ = np.linspace(0, 6, 100), np.linspace(0, 4, 100) # 定義參數的取值范圍
t0, t1 = np.meshgrid(t0_, t1_) # 生成矩陣網格,即形成三維圖的x軸和y軸,其為秩一陣
loss = np.zeros_like(t0)
for i in range(t0.shape[0]):for j in range(t0.shape[1]):loss[i, j] = mse_loss(t0[i, j],t1[i, j], x, y)# 繪制三維損失曲面
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d') # 創建三維坐標系
ax.plot_surface(t0, t1, loss, cmap='viridis', alpha=0.8)
ax.set_xlabel("Slope (t1)")
ax.set_ylabel("Intercept (t0)")
ax.set_zlabel("Loss (MSE)")
ax.set_title("3D Loss Surface")
plt.show()
1.2.4 繪制等高線
# 繪制等高線圖
plt.figure(figsize=(8, 6))
contour = plt.contour(t0, t1, loss, levels=50, cmap='viridis')
plt.colorbar(contour)
plt.xlabel("Slope (t1)")
plt.ylabel("Intercept (t0)")
plt.title("Contour Plot of Loss Function")
plt.show()
1.2.5 損失函數關于斜率的函數
固定截距,繪制出損失函數關于斜率的圖像,通過等高線得出估計的最佳截距。
t1 = np.linspace(0, 6, 200) # 得出斜率的范圍
loss = np.zeros_like(t1)
for i in range(loss.shape[0]):loss[i] = mse_loss(2.5, t1[i], x, y) # 存儲損失值
plt.plot(t1, loss)
plt.xlabel(r"Slope($\theta_{1}$)")
plt.ylabel("Loss")
plt.title("Loss-Slope")
plt.show()
通過一系列圖像發現,損失值會收斂到一個值
故,可以使用梯度下降法(下一文會介紹)來進行線性擬合求解方程
二、 多變量擬合
2.1 介紹
顯然,一個結果會受到多種因素的影響,這時候,就需要引入多項式來進行擬合。需要一些線性代數的知識,小知識。
即,我們令:
y = ( x 1 ? x n 1 ) ? ( w 1 ? w n b ) = X W + b = w 1 x 1 + ? + w n x n + b \begin{array}{l} y &= \begin{pmatrix} x_1& \cdots& x_n&1 \end{pmatrix}\cdot\begin{pmatrix} w_1\\\vdots\\w_n\\b \end{pmatrix} \\ &= XW+b \\&= w_1x_1+\cdots+w_nx_n+b \end{array} y?=(x1????xn??1?)? ?w1??wn?b? ?=XW+b=w1?x1?+?+wn?xn?+b?
可以看出,使用向量表達,和線性擬合的表達式類似。即,這里使用二項式擬合:
h θ ( x ) ( i ) = θ 0 + θ 1 x 1 ( i ) + θ 2 x 2 ( i ) h θ ( x ) = ( 1 x 1 ( 1 ) x 2 ( 1 ) ? ? ? 1 x 1 ( m ) x 2 ( m ) ) m × 3 ? ( θ 0 θ 1 θ 2 ) 3 × 1 \begin{array}{l} h_{\theta}(x)^{(i)} &=\theta_{0}+\theta_{1}x_{1}^{(i)}+\theta_{2}x_{2}^{(i)}\\ h_{\theta}(x)&=\begin{pmatrix} 1&x_{1}^{(1)}&x_{2}^{(1)}\\ \vdots&\vdots&\vdots\\ 1&x_{1}^{(m)}&x_{2}^{(m)} \end{pmatrix}_{m\times 3}\cdot\begin{pmatrix} \theta_{0}\\\theta_{1}\\\theta_{2} \end{pmatrix}_{3\times1} \end{array} hθ?(x)(i)hθ?(x)?=θ0?+θ1?x1(i)?+θ2?x2(i)?= ?1?1?x1(1)??x1(m)??x2(1)??x2(m)?? ?m×3?? ?θ0?θ1?θ2?? ?3×1??
則,我們的損失函數定義為:
J ( θ 0 , ? , θ n ) = 1 2 m ∑ i = 1 m ( h θ ( x ( i ) ) ? y ( i ) ) 2 J(\theta_{0},\cdots,\theta_{n}) = \frac{1}{2m}\sum_{i=1}^{m}(h_{\theta}(x^{(i)})-y^{(i)}) ^2 J(θ0?,?,θn?)=2m1?i=1∑m?(hθ?(x(i))?y(i))2
2.2 代碼可視化
2.2.1 生成示例數據
import numpy as np
import matplotlib.pyplot as plt# 這里迭代區間最好不要一樣,不然 x1 = x2
x1 = np.linspace(0, 10, 100)
x2 = np.linspace(-10, 0, 100)
y = 2 * x1 + 3 * x2 + 4 + np.random.normal(0, 4, 100) # 生成噪聲數據,即生成正態分布的隨機數# 繪制散點圖,三維散點圖
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')
# 繪制三維散點圖
ax.scatter(x1, x2, y, alpha=0.6)# 設置坐標軸標簽
ax.set_xlabel('X1 Label')
ax.set_ylabel('X2 Label')
ax.set_zlabel('Y Data')# 設置標題
ax.set_title('3D Scatter Plot')
plt.show()
2.2.2 損失函數
使用點積來進行損失函數的編寫:
其實,線性函數也可以用點積來編寫,不過運算較為簡單,就可以不考慮點積
def mse_loss(para, X, y):"""para: nx1 的列向量x: mxn 的數據矩陣y: nx1的列向量"""y_pre = np.dot(X, para) # 使用點積定義擬合函數return np.mean((y_pre-y)**2) / 2
2.2.3 繪制等高線
這里等高線的繪制,先尋找一個大概截距,即固定一個值,而后再進行二維等高線的繪制:
# 對數據進行預處理
one_ = np.ones_like(x1) # 生成一個全為1的列向量
X = np.array([one_, x1, x2]).T # 合成為一個100行三列的數據矩陣x10, x20 = np.linspace(0, 6, 100), np.linspace(0, 6, 100)
x1_, x2_ = np.meshgrid(x10, x20)
loss = np.zeros_like(x1_)
for i in range(x1_.shape[0]): # 批量計算損失函數for j in range(x1_.shape[1]):param = np.array([0, x1_[i][j], x2_[i][j]]) # 假設截距為0loss[i][j] = mse_loss(param, X, y)plt.figure(figsize=(8, 6))
contour = plt.contour(x1_, x2_, loss, levels=50, cmap='viridis')
plt.colorbar(contour)
plt.xlabel(r"$x_1$")
plt.ylabel(r"$x_2$")
plt.title(r"Contour Plot of Loss Function when $x_0$=4")
plt.show()
通過等高線的繪制,可以大致確定 x 1 x_{1} x1?和 x 2 x_{2} x2?的估計值,而后使用梯度下降法進行進一步的求解。
三、 多項式擬合
3.1 介紹
在一些擬合過程中其實單變量影響,但是通過散點圖很容易發現,其并不是線性函數,因此并不能進行線性擬合,而是要進行多項式擬合,即使用x的多次方的加和形式進行擬合:
f ( x ) = ∑ i = 0 n a i x i f(x) = \sum_{i=0}^{n}a_{i}x^{i} f(x)=i=0∑n?ai?xi
同時,也可以使用 y = θ 0 + θ 1 x + θ 2 x y=\theta_{0}+\theta_{1}x+\theta_{2}\sqrt{ x } y=θ0?+θ1?x+θ2?x?來進行擬合。
具體的多項式擬合形式,需要結合其他數據,以及具體情況進行分析。
則,其損失函數為:
min θ J ( θ ) = min θ 1 2 m ∑ i = 0 m ( f ( x ( i ) ) ? y ( i ) ) 2 \text{min}_{\theta} J(\theta)=\text{min}_{\theta}\frac{1}{2m}\sum_{i=0}^{m} (f(x^{(i)})-y^{(i)})^2 minθ?J(θ)=minθ?2m1?i=0∑m?(f(x(i))?y(i))2
3.2 公式表示
擬合方式則是與多變量擬合的過程類似(令 φ ( x ) \varphi(x) φ(x)為x的多次方形式)
即
h θ ( x ) = ( 1 φ 1 ( x ( 1 ) ) ? φ n ( x ( 1 ) ) ? ? ? ? 1 φ 1 ( x ( m ) ) ? φ n ( x ( m ) ) ) m × ( n + 1 ) ? ( θ 0 θ 1 ? θ n ) ( n + 1 ) × 1 \begin{array}{l} h_{\theta}(x)=\begin{pmatrix} 1&\varphi_1(x^{(1)})&\cdots&\varphi_n(x^{(1)})\\ \vdots&\vdots&\ddots &\vdots\\ 1&\varphi_1(x^{(m)})&\cdots&\varphi_n(x^{(m)}) \end{pmatrix}_{m\times (n+1)}\cdot\begin{pmatrix} \theta_{0}\\\theta_{1}\\\vdots\\\theta_n \end{pmatrix}_{(n+1)\times1} \end{array} hθ?(x)= ?1?1?φ1?(x(1))?φ1?(x(m))?????φn?(x(1))?φn?(x(m))? ?m×(n+1)?? ?θ0?θ1??θn?? ?(n+1)×1??
而后進行相似的運算即可繪制出圖像。