005_wz_ledr_pytorch深度学习实战_第六讲——逻辑回归

该博客介绍了如何使用PyTorch实现逻辑回归模型。通过创建一个简单的线性模型并结合sigmoid激活函数,作者展示了训练过程,包括损失函数(交叉熵)、优化器(SGD)的设置以及模型的训练与预测。最终,绘制了训练结果的预测曲线。
摘要由CSDN通过智能技术生成

一、目的

用pytorch实现逻辑回归,并理解什么是逻辑回归

二、编程

相比于线性模型,逻辑回归在线性模型后面加入了非线性激活函数,使用了不同的损失函数(交叉熵);
在这里插入图片描述
关于逻辑回归可以参考我的这篇文章——001_wz_sf_逻辑回归(Logistic Regression),我们主要看如何使用pytorch实现

import numpy as np
import matplotlib.pyplot as plt
import torch

# 数据集
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])

# 构造模型实现正向传播T
class LogisticRegressionModel(torch.nn.Module):
    # 构造函数
    def __init__(self):
        super(LogisticRegressionModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        y_pred = torch.sigmoid(self.linear(x))
        return y_pred


# 实例化模型
model = LogisticRegressionModel()

# 构造损失函数
criterion = torch.nn.BCELoss(reduction="sum")

# 构造优化器
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# 开始训练
costs = []
for epoch in range(1000):
    # 正向传播
    y_pred = model(x_data)
    # 计算损失
    loss = criterion(y_pred, y_data)
    costs.append(loss.item())

    print("epoch=", epoch, ",cost=", loss.item())

    # 反向传播
    optimizer.zero_grad()
    loss.backward()
    # 更新参数
    optimizer.step()

print("w=", model.linear.weight.item())
print("b=", model.linear.bias.item())

# 预测
x_test = torch.Tensor([[4.0]])
print("x=4,y=", model(x_test).item())

# 生成1-10之间的等差数列,200个数
x = np.linspace(1, 10, 200)
x_t = torch.Tensor(x).reshape(200, 1)
y_t = model(x_t)
y = np.array(y_t.item())

plt.plot(x, y)
plt.plot([0, 10], [0.5, 0.5], c="r")
plt.xlabel("hours")
plt.ylabel("probability of pass")
# 画出网络
plt.grid()
plt.show()
epoch= 1 ,cost= 2.7252180576324463
epoch= 2 ,cost= 2.6986937522888184
epoch= 3 ,cost= 2.673819065093994
...
epoch= 997 ,cost= 1.069270372390747
epoch= 998 ,cost= 1.0687689781188965
epoch= 999 ,cost= 1.068267822265625
w= 1.1604176759719849
b= -2.804975748062134
x=4,y= 0.8625572919845581

训练后的预测图
在这里插入图片描述

三、参考

python深度学习实践
Pytorch学习(五)–逻辑回归
PyTorch 深度学习实践 第6讲

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct; /* GPIO Ports Clock Enable */ //__HAL_RCC_GPIOH_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); //__HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(LEDR_OUT_PD3_GPIO_Port, LEDR_OUT_PD3_Pin, GPIO_PIN_SET); /*Configure GPIO pin Output Level */ //HAL_GPIO_WritePin(GPIOB, RS485_RE_OUT_PB8_Pin|RS485_SE_OUT_PB9_Pin, GPIO_PIN_RESET); /*Configure GPIO pin : LEDR_OUT_PD3_Pin */ GPIO_InitStruct.Pin = LEDR_OUT_PD3_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; HAL_GPIO_Init(LEDR_OUT_PD3_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : RS485_RE_OUT_PB8_Pin RS485_SE_OUT_PB9_Pin */ GPIO_InitStruct.Pin = RS485_RE_OUT_PB8_Pin|RS485_SE_OUT_PB9_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @param file: The file name as string. * @param line: The line in file as a number. * @retval None */ void _Error_Handler(char *file, int line) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ while(1) { } /* USER CODE END Error_Handler_Debug */
07-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值