简单的torch网络模型记录

  1. 线性dense网络结构,输入(B,W)
    `

    class Model(nn.Module):
    def init(self):
    super().init()
    self.media_type_embed = nn.Embedding(num_media_type, embed_dim)
    self.mid_scroe_embed = nn.Embedding(num_mid_score, embed_dim)
    #self.cat = torch.cat()
    self.model = nn.Sequential(
    nn.Linear(embed_dim*2, 256),
    nn.ReLU(),
    nn.Linear(256, 2),
    #nn.Sigmoid(),
    )

    复制代码
     def forward(self, x,):
         #print("x :",x.shape)
         [media_type,mid_score] = x
         x_media = self.media_type_embed(media_type)
         x_mid = self.mid_scroe_embed(mid_score)
         x = torch.cat((x_media, x_mid), -1)
         x = self.model(x)
         return x

    model = Model()
    model.to(device)`

    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    criterion = nn.CrossEntropyLoss()

2.conv1d卷积网络:输入(B,C,W)

复制代码
import torch
import torch.nn as nn

# 定义一个一维卷积神经网络模型
class CNN1D(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(CNN1D, self).__init__()
        self.conv1 = nn.Conv1d(in_channels=1, out_channels=16, kernel_size=3)
        self.conv2 = nn.Conv1d(in_channels=16, out_channels=32, kernel_size=3)
        self.pool = nn.MaxPool1d(kernel_size=2)
        self.fc1 = nn.Linear(32 * 47, 64)
        self.fc2 = nn.Linear(64, output_dim)

    def forward(self, x):
        x = self.conv1(x)
        x = nn.functional.relu(x)
        x = self.pool(x)
        x = self.conv2(x)
        x = nn.functional.relu(x)
        x = self.pool(x)
        x = x.view(-1, 32 * 47)
        x = self.fc1(x)
        x = nn.functional.relu(x)
        x = self.fc2(x)
        return x

# 实例化模型并定义损失函数和优化器
model = CNN1D(input_dim=100, output_dim=10)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# 定义数据集并训练模型
for epoch in range(100):
    for i, (inputs, labels) in enumerate(data_loader):
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
相关推荐
lxmyzzs5 小时前
基于深度学习CenterPoint的3D目标检测部署实战
人工智能·深度学习·目标检测·自动驾驶·ros·激光雷达·3d目标检测
算法_小学生8 小时前
循环神经网络(RNN, Recurrent Neural Network)
人工智能·rnn·深度学习
努力还债的学术吗喽9 小时前
【速通】深度学习模型调试系统化方法论:从问题定位到性能优化
人工智能·深度学习·学习·调试·模型·方法论
伊织code10 小时前
PyTorch API 6
pytorch·api·ddp
大千AI助手10 小时前
GitHub Copilot:AI编程助手的架构演进与真实世界影响
人工智能·深度学习·大模型·github·copilot·ai编程·codex
学行库小秘12 小时前
基于门控循环单元的数据回归预测 GRU
人工智能·深度学习·神经网络·算法·回归·gru
范男13 小时前
基于Pytochvideo训练自己的的视频分类模型
人工智能·pytorch·python·深度学习·计算机视觉·3d·视频
聚客AI14 小时前
🧠深度解析模型压缩革命:减枝、量化、知识蒸馏
人工智能·深度学习·llm
SHIPKING39314 小时前
【机器学习&深度学习】Ollama、vLLM、LMDeploy对比:选择适合你的 LLM 推理框架
人工智能·深度学习·机器学习
coding者在努力15 小时前
深度学习核心技巧
人工智能·深度学习