概念
學習率衰減(Learning Rate Decay)是一種優化算法,在訓練深度學習模型時逐漸減小學習率,以便在訓練的后期更加穩定地收斂到最優解。學習率衰減可以幫助在訓練初期更快地靠近最優解,而在接近最優解時減小學習率可以使模型更精細地調整參數,從而更好地收斂。
實現方式
學習率衰減可以通過以下幾種方式實現:
定期衰減:在訓練的每個固定的迭代步驟,將學習率乘以一個衰減因子(通常小于1)。
指數衰減:使用指數函數來衰減學習率,例如每隔一定迭代步驟,將學習率按指數函數進行衰減。
分段衰減:將訓練過程分成多個階段,每個階段使用不同的學習率。
代碼實現(定期衰減)
import numpy as np
import matplotlib.pyplot as plt# 生成隨機數據
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)# 添加偏置項
X_b = np.c_[np.ones((100, 1)), X]# 初始化參數
theta = np.random.randn(2, 1)# 初始學習率
initial_learning_rate = 0.1# 衰減因子
decay_factor = 0.9# 迭代次數
n_iterations = 1000# 學習率衰減
for iteration in range(n_iterations):learning_rate = initial_learning_rate / (1 + decay_factor * iteration)gradients = 2 / 100 * X_b.T.dot(X_b.dot(theta) - y)theta = theta - learning_rate * gradients# 繪制數據和擬合直線
plt.scatter(X, y)
plt.plot(X, X_b.dot(theta), color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression with Learning Rate Decay')
plt.show()print("Intercept (theta0):", theta[0][0])
print("Slope (theta1):", theta[1][0])