深度学习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)
相关推荐
波动几何8 分钟前
因果动力学架构技能cda
人工智能
Lucas_coding11 分钟前
【Claude Code Router】 Claude Code 兼容 OpenAI 格式 API, Claude code 接入本地部署模型
人工智能·python
jinanwuhuaguo13 分钟前
(第二十七篇)OpenClaw四月的演化风暴:OpenClaw 2026年4月全版本更新的文明级解读
大数据·人工智能·架构·kotlin·openclaw
测试员周周15 分钟前
【AI测试系统】第5篇:从 Archon 看 AI 工程化落地:为什么"确定性编排+AI 弹性智能"是终局?
人工智能·python·测试
RxGc21 分钟前
微软AI Agent框架深度测评:Microsoft Agent Framework 1.0 vs OpenClaw/Claude企业级能力对比
人工智能·agent
随便写写21 分钟前
第四章 智能体经典范式构建
人工智能
穿过生命散发芬芳22 分钟前
基于CodeBuddy Agent智能体平台构建自己第一个SKILL——相机推荐
人工智能
格林威26 分钟前
工业视觉项目:如何与客户有效沟通验收标准?
人工智能·数码相机·计算机视觉·视觉检测·机器视觉·工业相机·视觉项目
zhuiyisuifeng26 分钟前
AI新闻配图革命:GPTimage2镜像官网重塑时效与成本
人工智能·gpt
码云数智-大飞30 分钟前
本地部署大模型:隐私安全与多元优势一站式解读
运维·网络·人工智能