当前位置: 首页 > news >正文

电影网站规划免费自己建网站

电影网站规划,免费自己建网站,wordpress 云储存,肇东网站制作根据您的需求,您正在寻找一个支持批量处理(batch size)的BiLSTM-CRF模型的PyTorch教程。以下是一些资源,它们提供了更高效的解决方案,包括批量处理的支持: 1. **a-PyTorch-Tutorial-to-Sequence-Labeling*…

根据您的需求,您正在寻找一个支持批量处理(batch size)的BiLSTM-CRF模型的PyTorch教程。以下是一些资源,它们提供了更高效的解决方案,包括批量处理的支持:

1. **a-PyTorch-Tutorial-to-Sequence-Labeling**:这个GitHub仓库提供了一个关于序列标注的PyTorch教程,其中包括了BiLSTM-CRF模型的实现。教程中详细解释了如何准备数据、构建模型以及训练模型,支持批量处理。[GitHub - sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling)

GitHub - sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling: Empower Sequence Labeling with Task-Aware Neural Language Model | a PyTorch Tutorial to Sequence Labeling

2. **cn-PyTorch-Sequence-Labeling-Tutorial-with-LM-LSTM-CRF**:这个资源是上述教程的中文翻译版本,同样提供了关于如何使用BiLSTM-CRF进行序列标注的详细指导,包括批量处理的支持。[GitHub - ofooo/cn-PyTorch-Sequence-Labeling-Tutorial-with-LM-LSTM-CRF](https://github.com/ofooo/cn-PyTorch-Sequence-Labeling-Tutorial-with-LM-LSTM-CRF)

https://github.com/ofooo/cn-PyTorch-Sequence-Labeling-Tutorial-with-LM-LSTM-CRF

3. **NLP with PyTorch: A Comprehensive Guide**:这个DataCamp教程提供了一个全面的指南,介绍了如何使用PyTorch进行自然语言处理,包括数据准备、模型定义、训练和预测。教程中提到了如何使用`DataLoader`来创建数据集,这对于批量处理是非常有用的。[DataCamp - NLP with PyTorch: A Comprehensive Guide](https://www.datacamp.com/tutorial/nlp-with-pytorch-a-comprehensive-guide) 

https://www.datacamp.com/tutorial/nlp-with-pytorch-a-comprehensive-guide

改成批处理关键代码  previous_score = score[t - 1].view(batch_size, -1, 1)

def viterbi_decode(self, h: FloatTensor, mask: BoolTensor) -> List[List[int]]:"""decode labels using viterbi algorithm:param h: hidden matrix (batch_size, seq_len, num_labels):param mask: mask tensor of each sequencein mini batch (batch_size, batch_size):return: labels of each sequence in mini batch"""batch_size, seq_len, _ = h.size()# prepare the sequence lengths in each sequenceseq_lens = mask.sum(dim=1)# In mini batch, prepare the score# from the start sequence to the first labelscore = [self.start_trans.data + h[:, 0]]path = []for t in range(1, seq_len):# extract the score of previous sequence# (batch_size, num_labels, 1)previous_score = score[t - 1].view(batch_size, -1, 1)# extract the score of hidden matrix of sequence# (batch_size, 1, num_labels)h_t = h[:, t].view(batch_size, 1, -1)# extract the score in transition# from label of t-1 sequence to label of sequence of t# self.trans_matrix has the score of the transition# from sequence A to sequence B# (batch_size, num_labels, num_labels)score_t = previous_score + self.trans_matrix + h_t# keep the maximum value# and point where maximum value of each sequence# (batch_size, num_labels)best_score, best_path = score_t.max(1)score.append(best_score)path.append(best_path)

torchcrf 使用 支持批处理,torchcrf的简单使用-CSDN博客文章浏览阅读9.7k次,点赞5次,收藏33次。本文介绍了如何在PyTorch中安装和使用TorchCRF库,重点讲解了CRF模型参数设置、自定义掩码及损失函数的计算。作者探讨了如何将CRF的NLL损失与交叉熵结合,并通过自适应权重优化训练过程。虽然在单任务中效果不显著,但对于多任务学习提供了有价值的方法。https://blog.csdn.net/csdndogo/article/details/125541213

torchcrf的简单使用-CSDN博客

为了防止文章丢失 ,吧内容转发在这里

https://blog.csdn.net/csdndogo/article/details/125541213

. 安装torchcrf,模型使用
安装:pip install TorchCRF
CRF的使用:在官网里有简单的使用说明
注意输入的格式。在其他地方下载的torchcrf有多个版本,有些版本有batch_first参数,有些没有,要看清楚有没有这个参数,默认batch_size是第一维度。
这个代码是我用来熟悉使用crf模型和损失函数用的,模拟多分类任务输入为随机数据和随机标签,所以最后的结果预测不能很好的跟标签对应。

import torch
import torch.nn as nn
import numpy as np
import random
from TorchCRF import CRF
from torch.optim import Adam
seed = 100

def seed_everything(seed=seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True

num_tags = 5
model = CRF(num_tags, batch_first=True)  # 这里根据情况而定
seq_len = 3
batch_size = 50
seed_everything()
trainset = torch.randn(batch_size, seq_len, num_tags)  # features
traintags = (torch.rand([batch_size, seq_len])*4).floor().long()  # (batch_size, seq_len)
testset = torch.randn(5, seq_len, num_tags)  # features
testtags = (torch.rand([5, seq_len])*4).floor().long()  # (batch_size, seq_len)

# 训练阶段
for e in range(50):
    optimizer = Adam(model.parameters(), lr=0.05)
    model.train()
    optimizer.zero_grad()
    loss = -model(trainset, traintags)
    print('epoch{}: loss score is {}'.format(e, loss))
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(),5)
    optimizer.step()

#测试阶段
model.eval()
loss = model(testset, testtags)
model.decode(testset)


1.1模型参数,自定义掩码mask注意事项
def forward(self, emissions, labels: LongTensor, mask: BoolTensor) 
1
分别为发射矩阵(各标签的预测值),标签,掩码(注意这里的mask类型为BoolTensor)
注意:此处自定义mask掩码时,使用LongTensor类型的[1,1,1,1,0,0]会报错,需要转换成ByteTensor,下面是一个简单的获取mask的函数,输入为标签数据:

    def get_crfmask(self, labels):
        crfmask = []
        for batch in labels:
            res = [0 if d == -1 else 1 for d in batch]
            crfmask.append(res)
        return torch.ByteTensor(crfmask)


运行运行
2. CRF的损失函数是什么?
损失函数由真实转移路径值和所有可能情况路径转移值两部分组成,损失函数的公式为

分子为真实转移路径值,分母为所有路径总分数,上图公式在crf原始代码中为:

    def forward(
        self, h: FloatTensor, labels: LongTensor, mask: BoolTensor) -> FloatTensor:

        log_numerator = self._compute_numerator_log_likelihood(h, labels, mask)
        log_denominator = self._compute_denominator_log_likelihood(h, mask)

        return log_numerator - log_denominator

CRF损失函数值为负对数似然函数(NLL),所以如果原来的模型损失函数使用的是交叉熵损失函数,两个损失函数相加时要对CRF返回的损失取负。

    loss = -model(trainset, traintags)
1
3. 如何联合CRF的损失函数和自己的网络模型的交叉熵损失函数进行训练?
我想在自己的模型上添加CRF,就需要联合原本的交叉熵损失函数和CRF的损失函数,因为CRF输出的时NLL,所以在模型在我仅对该损失函数取负之后和原先函数相加。

        loss2 = -crf_layer(log_prob, label, mask=crfmask)
        loss1 = loss_function(log_prob.permute(0, 2, 1), label)
        loss = loss1 + loss2
        loss.backward()

缺陷: 效果不佳,可以尝试对loss2添加权重。此处贴一段包含两个损失函数的自适应权重训练的函数。

3.1.自适应损失函数权重
由于CRF返回的损失与原来的损失数值不在一个量级,所以产生了自适应权重调整两个权重的大小来达到优化的目的。自适应权重原本属于多任务学习部分,未深入了解,代码源自某篇复现论文的博客。

class AutomaticWeightedLoss(nn.Module):
    def __init__(self, num=2):
        super(AutomaticWeightedLoss, self).__init__()
        params = torch.ones(num, requires_grad=True)
        self.params = torch.nn.Parameter(params)

    def forward(self, *x):
        loss_sum = 0
        for i, loss in enumerate(x):
            loss_sum += 0.5 / (self.params[i] ** 2) * loss + torch.log(1 + self.params[i] ** 2)
        return loss_sum

http://www.15wanjia.com/news/42446.html

相关文章:

  • 网站估值怎么做360免费建站官网
  • 做分析图超牛的地图网站宣传广告怎么做吸引人
  • wordpress b站优秀营销软文100篇
  • 网站验证码怎么做品牌推广方案模板
  • 保定企业网站制作适合网络营销的产品
  • 广东专业网站定制semikron
  • 昆山网站开发公司整站优化关键词推广
  • 做网站需要什么步骤关键词文案生成器
  • 优秀网站psd网络营销的概念
  • 女人和男人做爰网站下载百度网盘
  • 建设网站分析100%上热门文案
  • 唐山网站关键词优化seo是指什么岗位
  • 17网站一起做网店深圳谷歌推广培训
  • 哪个公司做网站好 知乎seo英文怎么读
  • 曲阳县做网站注册公司网上申请入口
  • 网站cmd做路由分析百度手机点击排名工具
  • 网站开发论文研究内容矿产网站建设价格
  • 网站忧化 推广同时做爱站网 关键词挖掘工具
  • 温州平阳县营销型网站建设永久免费跨境浏览app
  • 建设学校网站多钱风云榜百度
  • 互联网软件门户网站上海百度推广电话客服
  • 建设企业银行官方网站珠海seo排名收费
  • wordpress注册会员无法收到邮件聊城seo整站优化报价
  • 广东网站建设哪家好广东seo网站推广
  • 做公司网站的步骤专门开发小程序的公司
  • 湖南微信网站线上直播营销策划方案
  • 企航互联提供天津网站建设做网络推广费用
  • 安徽元鼎建设公司网站无货源网店怎么开
  • 2015做导航网站好电子商务说白了就是干什么的
  • 电子商务网站开发进什么科目百度小说排名