简单的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()
相关推荐
墨染点香5 分钟前
第七章 Pytorch构建模型详解【构建CIFAR10模型结构】
人工智能·pytorch·python
兮℡檬,3 小时前
房价预测|Pytorch
人工智能·pytorch·python
宇称不守恒4.010 小时前
2025暑期—06神经网络-常见网络2
网络·人工智能·神经网络
码字的字节11 小时前
深度学习损失函数的设计哲学:从交叉熵到Huber损失的深入探索
深度学习·交叉熵·huber
凪卄121311 小时前
图像预处理 二
人工智能·python·深度学习·计算机视觉·pycharm
碳酸的唐12 小时前
Inception网络架构:深度学习视觉模型的里程碑
网络·深度学习·架构
AI赋能12 小时前
自动驾驶训练-tub详解
人工智能·深度学习·自动驾驶
seasonsyy12 小时前
1.安装anaconda详细步骤(含安装截图)
python·深度学习·环境配置
deephub12 小时前
AI代理性能提升实战:LangChain+LangGraph内存管理与上下文优化完整指南
人工智能·深度学习·神经网络·langchain·大语言模型·rag
go546315846513 小时前
基于深度学习的食管癌右喉返神经旁淋巴结预测系统研究
图像处理·人工智能·深度学习·神经网络·算法