神经网络基础-神经网络补充概念-08-逻辑回归中的梯度下降算法

概念

逻辑回归是一种用于分类问题的机器学习算法,而梯度下降是优化算法,用于更新模型参数以最小化损失函数。在逻辑回归中,我们使用梯度下降算法来找到最优的模型参数,使得逻辑回归模型能够更好地拟合训练数据。

逻辑回归中的梯度下降算法的步骤:

在这里插入图片描述

伪代码

初始化参数向量 theta
重复迭代直到收敛或达到最大迭代次数:
    计算模型预测值 h_theta(x)
    计算损失函数 J(theta)
    计算梯度 ∂J(theta)/∂theta
    更新参数 theta: theta := theta - learning_rate * gradient

代码实现

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 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)
X = np.random.randn(100, 2)
X = np.hstack((np.ones((X.shape[0], 1)), X))
theta_true = np.array([1, 2, 3])
y = (X.dot(theta_true) + np.random.randn(100) * 0.2) > 0

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

# 执行梯度下降
theta_optimized, losses = 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丰。。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值