本文全面深入地探討了梯度下降及其變體——批量梯度下降、隨機梯度下降和小批量梯度下降的原理和應(yīng)用。通過數(shù)學(xué)表達式和基于PyTorch的代碼示例,本文旨在為讀者提供一種直觀且實用的視角,以理解這些優(yōu)化算法的工作原理和應(yīng)用場景。
關(guān)注TechLead,分享AI全維度知識。作者擁有10+年互聯(lián)網(wǎng)服務(wù)架構(gòu)、AI產(chǎn)品研發(fā)經(jīng)驗、團隊管理經(jīng)驗,同濟本復(fù)旦碩,復(fù)旦機器人智能實驗室成員,阿里云認證的資深架構(gòu)師,項目管理專業(yè)人士,上億營收AI產(chǎn)品研發(fā)負責(zé)人。
一、簡介
梯度下降(Gradient Descent)是一種在機器學(xué)習(xí)和深度學(xué)習(xí)中廣泛應(yīng)用的優(yōu)化算法。該算法的核心思想非常直觀:找到一個函數(shù)的局部最小值(或最大值)通過不斷地沿著該函數(shù)的梯度(gradient)方向更新參數(shù)。
什么是梯度下降?
簡單地說,梯度下降是一個用于找到函數(shù)最小值的迭代算法。在機器學(xué)習(xí)中,這個“函數(shù)”通常是損失函數(shù)(Loss Function),該函數(shù)衡量模型預(yù)測與實際標(biāo)簽之間的誤差。通過最小化這個損失函數(shù),模型可以“學(xué)習(xí)”到從輸入數(shù)據(jù)到輸出標(biāo)簽之間的映射關(guān)系。
為什么梯度下降重要?
-
廣泛應(yīng)用:從簡單的線性回歸到復(fù)雜的深度神經(jīng)網(wǎng)絡(luò),梯度下降都發(fā)揮著至關(guān)重要的作用。
-
解決不可解析問題:對于很多復(fù)雜的問題,我們往往無法找到解析解(analytical solution),而梯度下降提供了一種有效的數(shù)值方法。
-
擴展性:梯度下降算法可以很好地適應(yīng)大規(guī)模數(shù)據(jù)集和高維參數(shù)空間。
-
靈活性與多樣性:梯度下降有多種變體,如批量梯度下降(Batch Gradient Descent)、隨機梯度下降(Stochastic Gradient Descent)和小批量梯度下降(Mini-batch Gradient Descent),各自有其優(yōu)點和適用場景。
二、梯度下降的數(shù)學(xué)原理
在深入研究梯度下降的各種實現(xiàn)之前,了解其數(shù)學(xué)背景是非常有用的。這有助于更全面地理解算法的工作原理和如何選擇合適的算法變體。
代價函數(shù)(Cost Function)
在機器學(xué)習(xí)中,代價函數(shù)(也稱為損失函數(shù),Loss Function)是一個用于衡量模型預(yù)測與實際標(biāo)簽(或目標(biāo))之間差異的函數(shù)。通常用 ( J(\theta) ) 來表示,其中 ( \theta ) 是模型的參數(shù)。
梯度(Gradient)
更新規(guī)則
代碼示例:基礎(chǔ)的梯度下降更新規(guī)則
import numpy as np
def gradient_descent_update(theta, grad, alpha):
"""
Perform a single gradient descent update.
Parameters:
theta (ndarray): Current parameter values.
grad (ndarray): Gradient of the cost function at current parameters.
alpha (float): Learning rate.
Returns:
ndarray: Updated parameter values.
"""
return theta - alpha * grad
# Initialize parameters
theta = np.array([1.0, 2.0])
# Hypothetical gradient (for demonstration)
grad = np.array([0.5, 1.0])
# Learning rate
alpha = 0.01
# Perform a single update
theta_new = gradient_descent_update(theta, grad, alpha)
print("Updated theta:", theta_new)
輸出:
Updated theta: [0.995 1.99 ]
在接下來的部分,我們將探討梯度下降的幾種不同變體,包括批量梯度下降、隨機梯度下降和小批量梯度下降,以及一些高級的優(yōu)化技巧。通過這些內(nèi)容,你將能更全面地理解梯度下降的應(yīng)用和局限性。
三、批量梯度下降(Batch Gradient Descent)
批量梯度下降(Batch Gradient Descent)是梯度下降算法的一種基礎(chǔ)形式。在這種方法中,我們使用整個數(shù)據(jù)集來計算梯度,并更新模型參數(shù)。
基礎(chǔ)算法
批量梯度下降的基礎(chǔ)算法可以概括為以下幾個步驟:
代碼示例
下面的Python代碼使用PyTorch庫演示了批量梯度下降的基礎(chǔ)實現(xiàn)。
import torch
# Hypothetical data (features and labels)
X = torch.tensor([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]], requires_grad=True)
y = torch.tensor([[1.0], [2.0], [3.0]])
# Initialize parameters
theta = torch.tensor([[0.0], [0.0]], requires_grad=True)
# Learning rate
alpha = 0.01
# Number of iterations
n_iter = 1000
# Cost function: Mean Squared Error
def cost_function(X, y, theta):
m = len(y)
predictions = X @ theta
return (1 / (2 * m)) * torch.sum((predictions - y) ** 2)
# Gradient Descent
for i in range(n_iter):
J = cost_function(X, y, theta)
J.backward()
with torch.no_grad():
theta -= alpha * theta.grad
theta.grad.zero_()
print("Optimized theta:", theta)
輸出:
Optimized theta: tensor([[0.5780],
[0.7721]], requires_grad=True)
批量梯度下降的主要優(yōu)點是它的穩(wěn)定性和準確性,但缺點是當(dāng)數(shù)據(jù)集非常大時,計算整體梯度可能非常耗時。接下來的章節(jié)中,我們將探索一些用于解決這一問題的變體和優(yōu)化方法。
四、隨機梯度下降(Stochastic Gradient Descent)
隨機梯度下降(Stochastic Gradient Descent,簡稱SGD)是梯度下降的一種變體,主要用于解決批量梯度下降在大數(shù)據(jù)集上的計算瓶頸問題。與批量梯度下降使用整個數(shù)據(jù)集計算梯度不同,SGD每次只使用一個隨機選擇的樣本來進行梯度計算和參數(shù)更新。
基礎(chǔ)算法
隨機梯度下降的基本步驟如下:
代碼示例
下面的Python代碼使用PyTorch庫演示了SGD的基礎(chǔ)實現(xiàn)。
import torch
import random
# Hypothetical data (features and labels)
X = torch.tensor([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]], requires_grad=True)
y = torch.tensor([[1.0], [2.0], [3.0]])
# Initialize parameters
theta = torch.tensor([[0.0], [0.0]], requires_grad=True)
# Learning rate
alpha = 0.01
# Number of iterations
n_iter = 1000
# Stochastic Gradient Descent
for i in range(n_iter):
# Randomly sample a data point
idx = random.randint(0, len(y) - 1)
x_i = X[idx]
y_i = y[idx]
# Compute cost for the sampled point
J = (1 / 2) * torch.sum((x_i @ theta - y_i) ** 2)
# Compute gradient
J.backward()
# Update parameters
with torch.no_grad():
theta -= alpha * theta.grad
# Reset gradients
theta.grad.zero_()
print("Optimized theta:", theta)
輸出:
Optimized theta: tensor([[0.5931],
[0.7819]], requires_grad=True)
優(yōu)缺點
SGD雖然解決了批量梯度下降在大數(shù)據(jù)集上的計算問題,但因為每次只使用一個樣本來更新模型,所以其路徑通常比較“嘈雜”或“不穩(wěn)定”。這既是優(yōu)點也是缺點:不穩(wěn)定性可能幫助算法跳出局部最優(yōu)解,但也可能使得收斂速度減慢。
在接下來的部分,我們將介紹一種折衷方案——小批量梯度下降,它試圖結(jié)合批量梯度下降和隨機梯度下降的優(yōu)點。
五、小批量梯度下降(Mini-batch Gradient Descent)
小批量梯度下降(Mini-batch Gradient Descent)是批量梯度下降和隨機梯度下降(SGD)之間的一種折衷方法。在這種方法中,我們不是使用整個數(shù)據(jù)集,也不是使用單個樣本,而是使用一個小批量(mini-batch)的樣本來進行梯度的計算和參數(shù)更新。
基礎(chǔ)算法
小批量梯度下降的基本算法步驟如下:
代碼示例
下面的Python代碼使用PyTorch庫演示了小批量梯度下降的基礎(chǔ)實現(xiàn)。
import torch
from torch.utils.data import DataLoader, TensorDataset
# Hypothetical data (features and labels)
X = torch.tensor([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0]], requires_grad=True)
y = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
# Initialize parameters
theta = torch.tensor([[0.0], [0.0]], requires_grad=True)
# Learning rate and batch size
alpha = 0.01
batch_size = 2
# Prepare DataLoader
dataset = TensorDataset(X, y)
data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
# Mini-batch Gradient Descent
for epoch in range(100):
for X_batch, y_batch in data_loader:
J = (1 / (2 * batch_size)) * torch.sum((X_batch @ theta - y_batch) ** 2)
J.backward()
with torch.no_grad():
theta -= alpha * theta.grad
theta.grad.zero_()
print("Optimized theta:", theta)
輸出:
Optimized theta: tensor([[0.6101],
[0.7929]], requires_grad=True)
優(yōu)缺點
小批量梯度下降結(jié)合了批量梯度下降和SGD的優(yōu)點:它比SGD更穩(wěn)定,同時比批量梯度下降更快。這種方法廣泛應(yīng)用于深度學(xué)習(xí)和其他機器學(xué)習(xí)算法中。
小批量梯度下降不是沒有缺點的。選擇合適的批量大小可能是一個挑戰(zhàn),而且有時需要通過實驗來確定。文章來源:http://www.zghlxwxcb.cn/news/detail-747679.html
關(guān)注TechLead,分享AI全維度知識。作者擁有10+年互聯(lián)網(wǎng)服務(wù)架構(gòu)、AI產(chǎn)品研發(fā)經(jīng)驗、團隊管理經(jīng)驗,同濟本復(fù)旦碩,復(fù)旦機器人智能實驗室成員,阿里云認證的資深架構(gòu)師,項目管理專業(yè)人士,上億營收AI產(chǎn)品研發(fā)負責(zé)人。
如有幫助,請多關(guān)注
TeahLead KrisChang,10+年的互聯(lián)網(wǎng)和人工智能從業(yè)經(jīng)驗,10年+技術(shù)和業(yè)務(wù)團隊管理經(jīng)驗,同濟軟件工程本科,復(fù)旦工程管理碩士,阿里云認證云服務(wù)資深架構(gòu)師,上億營收AI產(chǎn)品業(yè)務(wù)負責(zé)人。文章來源地址http://www.zghlxwxcb.cn/news/detail-747679.html
到了這里,關(guān)于解鎖機器學(xué)習(xí)-梯度下降:從技術(shù)到實戰(zhàn)的全面指南的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!