004_wz_ledr_pytorch深度学习实战_第五讲——用pytorch实现线性回归

一、目的

使用pytorch实现线性回归

二、编程

2.1 实现流程

在这里插入图片描述

2.2 编程实现

import matplotlib.pyplot as plt
import torch

# 数据集向量化
# x,y是矩阵,3行1列 也就是说总共有3个数据,每个数据只有1个特征
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0]])

# 设计模型计算正向传播
class LinearModel(torch.nn.Module):
    # 构造函数
    def __init__(self):
        super(LinearModel, self).__init__()
        # (1,1)是指输入x和输出y的特征维度,这里数据集中的x和y的特征都是1维的
        # 该线性层需要学习的参数是w和b  获取w/b的方式分别是linear.weight/linear.bias
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        # 可调用对象linear,计算y=wx+b
        y_pred = self.linear(x)
        return y_pred


# 实例化模型
model = LinearModel()

# 构造损失函数
criterion = torch.nn.MSELoss(reduction="sum")
# 构造优化器
optimizer = torch.optim.SGD(model.parameters(), 0.01)

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

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


print("w=", model.linear.weight.item())
print("b=", model.linear.bias.item())
x = torch.tensor([[4.0]])
print("x=4,y=", model(x).item())

plt.plot(costs)
plt.xlabel("epoch")
plt.ylabel("costs")
plt.show()
1 47.6524543762207
2 21.780231475830078
3 10.254509925842285
...
97 0.2612595856189728
98 0.25750502943992615
99 0.25380414724349976
w= 1.6646168231964111
b= 0.7624048590660095
x=4,y= 7.420872211456299

在这里插入图片描述

三、参考

pytorch深度学习实践
PyTorch 深度学习实践 第5讲
PyTorch学习(四)–用PyTorch实现线性回归

  • 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、付费专栏及课程。

余额充值