我有以下梯度下降演算法,我從數學上推匯出平方誤差之和。但是,當我實施它時,損失會增加,如下所示。我試圖理解這個錯誤,但似乎無法找到數學謬誤,因為尺寸和推導是一致的,所以我不太確定發生了什么。
我還使用了一個隨機生成的資料集:
import pandas as pd
import numpy as np
testing = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('ABC'))
testing.insert(0, 'W_o', 1) # W initial
testing.insert(-1, 'Y', np.random.randint(0,4,size=(100, 1))) #target
import matplotlib.pyplot as plt
def grad_descent_SSE(X,y,T,lr):
# Shape of dataset
m,n = X.shape
#Initialize parameters
W = np.zeros(n)
# W = OLS[0]
# Track loss over time
f = np.zeros(T)
for i in range(T):
# Loss for the current parameter vector W
f[i] = 0.5*np.linalg.norm(X.dot(W) - y)**2
# Compute steepest ascent at f(W)
W_update = np.matmul(X.T,np.matmul(X,W)-y)
# W_update = np.transpose(X).dot(X.dot(W) - y)
# Calculating the updated weights
W = W - lr * W_update
return W,f, plt.plot(f,'b-o')

uj5u.com熱心網友回復:
簡短回答:您可能正在使用更大的學習率。嘗試降低學習率。
長答案:讓我們抽取 20 個隨機樣本,每個樣本的維度為 5。那么我們的 X 將具有 (20,5) 的維度。讓我們假設W_t是我們想要達到的真實重量。如果我們忽略偏差,則線性方程變為y = W_t*X。
n = 5
m = 20
X = np.random.random((m,n))
W_t = np.random.random(n)
y = np.matmul(X,W_t)
如果我使用你的函式T=10和lr=10
grad_descent_SSE(X,y,10,10)
我得到一個和你相似的圖表。

當我將學習率降低到 0.01 ( lr=0.01) 時,梯度正在下降。

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/520808.html
