深度学习pytorch整体流程

一、数据处理

复制代码
from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
import pandas as pd
import os

class custom_dataset(Dataset):
    def __init__(self, root_path, file_path, transform, target_transform):
        self.data = pd.read_csv(os.path.join(root_path, file_path))
        self.transform = transform
        self.target_transform = target_transform
    def __len__(self):
        return len(self.data)
    def __getitem__(self, idx):
        row = self.data.iloc[idx]
        data = row['data']
        target = row['target']
        if self.transform:
            data = self.transform(data)
        if self.target_transform:
            target = self.target_transform(target)
        return data, target

train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)

二、模型建立、训练、测试

复制代码
import torch
from torch import nn

class network(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super().__init__()
        self.linear = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, output_dim),
            nn.ReLU()
        )
    def forward(self, x):
        x = self.linear(x)
        return x

if torch.cuda.is_available():
    device = torch.device('cuda')
else:
    device = torch.device('cpu')

model = network(input_dim=8, hidden_dim=16, output_dim=8).to(torch.device('cpu'))

learning_rate = 1e-3
batch_size = 64
epochs = 5

loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

def train(dataloader, model, loss_fn, optimizer, device):
    model.train()
    for batch, (x, y) in enumerate(dataloader):
        x, y = x.to(device), y.to(device)
        pred = model(x)
        loss = loss_fn(pred, y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if batch % 100 == 0:
            loss = loss.item()
            print(f'train_loss:{loss}')


def test(dataloader, model, loss_fn):
    num_batches = len(dataloader)
    model.eval()
    with torch.no_grad():
        for x, y in dataloader:
            pred = model(x)
            test_loss += loss_fn(pred, y).item()
    test_loss /= num_batches
    print(f'test_loss:{test_loss}')

for t in range(epochs):
    print(f'epoch {t+1}\n---------------------------')
    train(train_dataloader, model, loss_fn, optimizer, device)
    test(test_dataloader, model, loss_fn)
相关推荐
此处不留情1 小时前
基于pytorch的垃圾分类识别项目实战
人工智能·pytorch
mit6.8241 小时前
[AI人脸替换] docs | 环境部署指南 | 用户界面解析
人工智能·python
fantasy_arch1 小时前
Pytorch超分辨率模型实现与详细解释
人工智能·pytorch·python
爱读源码的大都督3 小时前
小白LLM教程:不训练模型,如何进行微调?
java·人工智能·后端
大千AI助手3 小时前
接吻数问题:从球体堆叠到高维空间的数学奥秘
人工智能·agi·deepmind·接吻数·kissingnumber·牛顿·alphaevolve
程序猿小D3 小时前
【完整源码+数据集+部署教程】硬币分类与识别系统源码和数据集:改进yolo11-SWC
人工智能·yolo·计算机视觉·数据挖掘·数据集·yolo11·硬币分类与识别系统
西猫雷婶5 小时前
神经网络|(十六)概率论基础知识-伽马函数·中
人工智能·深度学习·神经网络·学习·机器学习·概率论
Y|5 小时前
XGBoost(eXtreme Gradient Boosting,优化分布式梯度提升库)总结梳理
人工智能·算法·机器学习
空白到白5 小时前
机器学习-线性回归
人工智能·机器学习·线性回归
武汉格发Gofartlic5 小时前
HFSS许可证状态查询与管理
大数据·运维·人工智能·数据分析·自动化