神经网络基础-神经网络补充概念-09-m个样本的梯度下降

概念

当应用梯度下降算法到具有 m 个训练样本的逻辑回归问题时,我们需要对每个样本计算梯度并进行平均,从而更新模型参数。这个过程通常称为批量梯度下降(Batch Gradient Descent)。

代码实现

python 复制代码
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def compute_loss(X, y, theta):
    m = len(y)
    h = sigmoid(X.dot(theta))
    loss = (-1/m) * np.sum(y * np.log(h) + (1 - y) * np.log(1 - h))
    return loss

def batch_gradient_descent(X, y, theta, learning_rate, num_iterations):
    m = len(y)
    losses = []
    
    for _ in range(num_iterations):
        h = sigmoid(X.dot(theta))
        gradient = X.T.dot(h - y) / m
        theta -= learning_rate * gradient
        
        loss = compute_loss(X, y, theta)
        losses.append(loss)
        
    return theta, losses

# 生成一些模拟数据
np.random.seed(42)
m = 100
n = 2
X = np.random.randn(m, n)
X = np.hstack((np.ones((m, 1)), X))
theta_true = np.array([1, 2, 3])
y = (X.dot(theta_true) + np.random.randn(m) * 0.2) > 0

# 初始化参数和超参数
theta = np.zeros(X.shape[1])
learning_rate = 0.01
num_iterations = 1000

# 执行批量梯度下降
theta_optimized, losses = batch_gradient_descent(X, y, theta, learning_rate, num_iterations)

# 打印优化后的参数
print("优化后的参数:", theta_optimized)

# 绘制损失函数下降曲线
import matplotlib.pyplot as plt
plt.plot(losses)
plt.xlabel('迭代次数')
plt.ylabel('损失')
plt.title('损失函数下降曲线')
plt.show()

使用了 m 个训练样本,而不是一个。我们首先定义了 sigmoid 函数和计算损失的函数 compute_loss,然后实现了 batch_gradient_descent 函数来执行批量梯度下降。

相关推荐
独孤思维2 分钟前
AI能赚钱,但是赚不了用户的心
人工智能·ai写作·副业·独孤思维·赚钱
IT·陈寒3 分钟前
Java 并发这块坑真多,线程池又给我上了一课
人工智能·大模型·api·创业·变现·简历优化
Experience-摆渡10 分钟前
谷歌WikiSkill论文精读:模型可以换经验留下来,9B反超27B
人工智能·深度学习
MIXLLRED11 分钟前
Windows 搭建《动手学深度学习》PyTorch 环境:从安装到踩坑记录
pytorch·windows·深度学习
陈天伟教授13 分钟前
DeepSeek Harness 6个使用技巧
人工智能·具身智能
promanz14 分钟前
llamap.cpp 和 llama-index连接
人工智能·llama
Allen_LVyingbo16 分钟前
信息化部门在AI时代的编程转移路径分析(下)
人工智能·log4j·线性回归·健康医疗·数据库开发·时序数据库·数据库架构
EatFan19 分钟前
Agent Harness 为什么突然成了独立品类?从 pydantic-ai-harness v0.30.0 看编码智能体的可复现工程化
人工智能·ai agent·agent harness
Carl_奕然24 分钟前
【智能体】Loop 的四种设计模式之:Agent Loop(2026 最新版)
人工智能·设计模式·语言模型
Geeys28 分钟前
拼多多店铺怎么运营才能有订单?新手低成本出单攻略
大数据·网络·人工智能