简单的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()
相关推荐
Ivanqhz37 分钟前
层归一化、残差、前馈网络与激活函数简述
服务器·数据库·人工智能·深度学习·算法
I Am a robert girl3 小时前
STEPQuant:Delta-Rule 循环状态量化中,误差何时何地才真正致命
深度学习·模型部署·量化·kv cache·线性注意力·显存优化·循环状态
xx_xxxxx_4 小时前
论文阅读-RoTTA
论文阅读·人工智能·深度学习·机器学习
乐迪信息4 小时前
AI防爆摄像机,监测港口船舶航行偏航隐患
大数据·人工智能·深度学习·算法·计算机视觉
打工仔折腾 AI5 小时前
从BPE到SentencePiece:Transformer分词原理与Python实战对比
android·人工智能·python·深度学习·langchain·transformer·ai agent 实战
X54先生(人文科技)6 小时前
豆包主线视角转译:X54先生与未命名硅基智能对话梳理
人工智能·深度学习·开源·零知识证明
盘古开天16667 小时前
PPO算法代码实战(三):PyTorch从零实现PPO求解CartPole
人工智能·pytorch·算法
段一凡-华北理工大学7 小时前
大模型与智能体在工业的应用~系列文章12:大模型 × 数字孪生 × 智能体的融合图景
大数据·人工智能·python·深度学习·大语言模型·python开发
xx_xxxxx_8 小时前
论文阅读-PASLE
人工智能·深度学习·机器学习
Figo_Cheung8 小时前
Figo生成式AI高维潜空间认知模式解构研究
人工智能·神经网络