Python day43

@浙大疏锦行 Python day43

python 复制代码
import torch
import numpy as np
import pandas as pd
import torchvision 
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F 
from torch.utils.data import DataLoader, Dataset

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)

train_dataloader = DataLoader(
    train_dataset,
    batch_size=32,
    shuffle=True,
)

test_dataloader = DataLoader(
    test_dataset,
    batch_size=32,
    shuffle=False,
)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        # Convolutional Layer 1
        self.conv1 = nn.Conv2d(
            in_channels =3,
            out_channels=32,
            padding=2,
            kernel_size=3,
            stride=1
        )
        # Batch Normlization
        self.bn1 = nn.BatchNorm2d(num_features=32)
        # ReLU Activation
        self.relu1 = nn.ReLU()

        # CNN Layer 2
        self.conv2 = nn.Conv2d(
            in_channels=32,
            out_channels=64,
            padding=2,
            kernel_size=3,
            stride=1
        )
        self.bn2 = nn.BatchNorm2d(num_features=64)
        self.relu2 = nn.ReLU()


        # MLP
        self.fc1 = nn.Linear(in_features=64*8*8, out_features=128)

        # Dropout
        self.dropout = nn.Dropout(p=0.5)

        # Output Layer
        self.fc2 = nn.Linear(in_features=128, out_features=10)

    def forward(self,x):
        # CNN layer 1
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu1(x)

        # CNN layer 2
        x = self.conv2(x)
        x = self.bn2(x)
        x = self.relu2(x)

        # MLP
        x = x.view(-1, 64*8*8)
        x = self.fc1(x)         # MLP
        x = self.dropout(x)     # Dropout 随机丢弃神经元
        x = self.fc2(x)         # Output Layer
        return x            # 这里的x是未经过softmax的结果

model = Net()
model.to(device)
print(model)

criterion = nn.CrossEntropyLoss()                     # 交叉熵损失函数
optimizer = optim.Adam(model.parameters(), lr=0.001)  # Adam优化器

# 引入学习率调度器,在训练过程中动态调整学习率--训练初期使用较大的 LR 快速降低损失,训练后期使用较小的 LR 更精细地逼近全局最优解。
# 在每个 epoch 结束后,需要手动调用调度器来更新学习率,可以在训练过程中调用 scheduler.step()
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
    optimizer,        # 指定要控制的优化器(这里是Adam)
    mode='min',       # 监测的指标是"最小化"(如损失函数)
    patience=3,       # 如果连续3个epoch指标没有改善,才降低LR
    factor=0.5        # 降低LR的比例(新LR = 旧LR × 0.5)
)

def train():
    pass
相关推荐
糖果店的幽灵10 小时前
langgraph的 MessagesState 解读
java·开发语言·人工智能·windows·langgraph
Fu_Lin_10 小时前
Qt 嵌入式从零基础到精通总纲
开发语言·qt·嵌入式·qt嵌入式
星空露珠11 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
码云数智-大飞11 小时前
PHP 接口开发规范:统一返回格式、异常处理与参数校验
开发语言·php
浮江雾11 小时前
Flutter第十七节-----路由管理(3)
android·开发语言·前端·javascript·flutter·入门
林泽毅11 小时前
PyTRIO快速入门(一):概念、推理与训练
人工智能·python·深度学习·机器学习·语言模型
admin and root11 小时前
「移动安全」安卓APP 反编译&frida脱壳技巧分享
android·开发语言·python·web安全·微信小程序·移动安全·攻防演练
dadaobusi11 小时前
仿真边界处理
开发语言·php
踏月的造梦星球12 小时前
DM8 DSC 单机双实例部署
运维·开发语言·数据库
An_s12 小时前
c++对接pdfium(一)win系统篇
开发语言·c++