Example of Using Pytorch--2

本文介绍了如何使用Pandas加载covid.train.csv数据,通过预处理提取特征和标签,构建数据集并使用DataLoader。模型采用117维输入,均方误差作为损失函数,SGD优化器进行参数调整。核心内容涉及训练循环和模型预测。
摘要由CSDN通过智能技术生成

1 Task Description

给出了美国某个州的过去四天的调查结果,然后预测接下来第五天的概率。

  • 其中数据在a.csv中
  • 每行代表一个数据样本,包含118个特点
  • 最后一行元素是标签
    在这里插入图片描述

2 解决思路

2.1 Load data/Preprocessing

  • Load data: 可以利用Pandas找到csv文件
train_data = pd.read_csv('./covid.train.csv').drop(columns=['data']).values
  • preprocessing:得到模型输入和标签
x_train, y_train = train_data[:, :-1], train_data[:, -1]

2.2 Dataset
在这里插入图片描述
2.3 Dataloader

train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, pin_memory=True)
  • Group data into batches
  • 如果设置shuffle=True,倒进的数据将自动重新标记
  • 在训练中常设置shuffle=True

2.4 Model

  • 输入维数是117
  • 模型的输出是标量

2.5 Criterion(标准)

  • 做一个回归模型,选择均方误差作为损失函数是一个方案
criterion = torch.nn.MSELoss(reduction='mean')

2.6 Optimizer
选用一个适应调节网络参数的优化方式减小误差
exmple:选用随即梯度下降作为优化算法

optomizer = torch.optiom.SGD(model.parameters(), 1r=1e-5,momentum=0.9)

2.7 循环训练(Training loop)

  • 得到一个预测模型,计算梯度,更新参数,重新设置模型参数的梯度
Sure! Here's an example of how you can implement a PyTorch-based neural network that solves a regression problem using a combination of positively and negatively weighted sub-networks in the output layer: ```python import torch import torch.nn as nn class RegressionNet(nn.Module): def __init__(self, input_size, hidden_size): super(RegressionNet, self).__init__() self.positive_net = nn.Linear(input_size, hidden_size) self.negative_net = nn.Linear(input_size, hidden_size) self.output_layer = nn.Linear(hidden_size, 1) def forward(self, x): positive_out = torch.relu(self.positive_net(x)) negative_out = torch.relu(self.negative_net(x)) output = self.output_layer(positive_out - negative_out) return output # Example usage input_size = 10 hidden_size = 20 batch_size = 32 # Generate random input data x = torch.randn(batch_size, input_size) # Create an instance of the regression network model = RegressionNet(input_size, hidden_size) # Forward pass output = model(x) print(output) ``` In this code, we define a `RegressionNet` class that inherits from `nn.Module`. The network consists of two sub-networks: `positive_net` and `negative_net`, each with a linear layer followed by a ReLU activation function. The output of these sub-networks is then subtracted and passed through the `output_layer`, which is another linear layer that produces the final regression output. You can adjust the `input_size` and `hidden_size` parameters to match your specific problem. The example usage demonstrates how to perform a forward pass through the network using randomly generated input data.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值