神经网络基础-神经网络补充概念-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 函数来执行批量梯度下降。

相关推荐
阿里云大数据AI技术36 分钟前
本体如何落地?阿里云 Milvus 把企业文档变成知识图谱和 Wiki
人工智能
QXWZ_IA1 小时前
公安视频专网如何与定位数据融合?架构与实施要点
人工智能
小林ixn1 小时前
GraphRAG 实战:用 Neo4j 知识图谱,让 RAG 从“找货“进化到“梳理关系“
人工智能·知识图谱·neo4j
敖老师1 小时前
Dify 连局域网 Ollama 的两个坑:docker0 网段撞车,和请求里少掉的那个参数
人工智能
MocMoc1 小时前
从 0 到 1:把 Dify Chatflow 接进一个 qiankun 中后台
人工智能
民乐团扒谱机2 小时前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法
怎么全是重名2 小时前
VerdictAD
人工智能·异常检测·few-shot·zsas·异常分割
Bode_20023 小时前
具身智能机构设计的质量控制
人工智能
阿里云大数据AI技术3 小时前
EMR Serverless StarRocks × Lance:多模态分析与检索的云上实践
人工智能