pytorch bilstm crf的教程,注意 这里不支持批处理,要支持批处理 用torchcrf这个。

news2025/7/14 2:51:13

### Bi-LSTM Conditional Random Field
### pytorch tutorials https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html
### 模型主要结构:
![title](sources/bilstm.png)

pytorch bilstm crf的教程,注意 这里不支持批处理

Python version: 3.7.4 (default, Aug 13 2019, 20:35:49) [GCC 7.3.0]

Torch version: 1.4.0

# Author: Robert Guthrie

import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim

torch.manual_seed(1)
def argmax(vec):
    # return the argmax as a python int
    # 返回vec的dim为1维度上的最大值索引
    _, idx = torch.max(vec, 1)
    return idx.item()


def prepare_sequence(seq, to_ix):
    # 将句子转化为ID
    idxs = [to_ix[w] for w in seq]
    return torch.tensor(idxs, dtype=torch.long)


# Compute log sum exp in a numerically stable way for the forward algorithm
# 前向算法是不断累积之前的结果,这样就会有个缺点
# 指数和累积到一定程度后,会超过计算机浮点值的最大值,变成inf,这样取log后也是inf
# 为了避免这种情况,用一个合适的值clip去提指数和的公因子,这样就不会使某项变得过大而无法计算
# SUM = log(exp(s1)+exp(s2)+...+exp(s100))
#     = log{exp(clip)*[exp(s1-clip)+exp(s2-clip)+...+exp(s100-clip)]}
#     = clip + log[exp(s1-clip)+exp(s2-clip)+...+exp(s100-clip)]
# where clip=max
def log_sum_exp(vec):
    max_score = vec[0, argmax(vec)]
    max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])
    return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))




class BiLSTM_CRF(nn.Module):

    def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim):
        super(BiLSTM_CRF, self).__init__()
        self.embedding_dim = embedding_dim    # word embedding dim
        self.hidden_dim = hidden_dim          # Bi-LSTM hidden dim
        self.vocab_size = vocab_size          
        self.tag_to_ix = tag_to_ix
        self.tagset_size = len(tag_to_ix)

        self.word_embeds = nn.Embedding(vocab_size, embedding_dim)
        self.lstm = nn.LSTM(embedding_dim, hidden_dim // 2,
                            num_layers=1, bidirectional=True)

        # Maps the output of the LSTM into tag space.
        # 将BiLSTM提取的特征向量映射到特征空间,即经过全连接得到发射分数
        self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size)

        # Matrix of transition parameters.  Entry i,j is the score of transitioning *to* i *from* j.
        # 转移矩阵的参数初始化,transitions[i,j]代表的是从第j个tag转移到第i个tag的转移分数
        self.transitions = nn.Parameter(
            torch.randn(self.tagset_size, self.tagset_size))

        # These two statements enforce the constraint that we never transfer
        # to the start tag and we never transfer from the stop tag
        # 初始化所有其他tag转移到START_TAG的分数非常小,即不可能由其他tag转移到START_TAG
        # 初始化STOP_TAG转移到所有其他tag的分数非常小,即不可能由STOP_TAG转移到其他tag
        self.transitions.data[tag_to_ix[START_TAG], :] = -10000
        self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000

        self.hidden = self.init_hidden()

    def init_hidden(self):
        # 初始化LSTM的参数
        return (torch.randn(2, 1, self.hidden_dim // 2),
                torch.randn(2, 1, self.hidden_dim // 2))
    
    def _get_lstm_features(self, sentence):
        # 通过Bi-LSTM提取特征
        self.hidden = self.init_hidden()
        # 因此,embeds 的最终数据形式是一个三维张量,形状为 (seq_len, 1, embed_dim),其中:
        #     seq_len 是句子的长度(即单词的数量)。
        #    1 表示批次大小,表明当前处理的是单个句子。
        #    embed_dim 是每个单词的嵌入向量维度。
        #    这种形状非常适合直接传递给 PyTorch 的 LSTM 层进行处理,因为 LSTM 层期望输入有三个维度,分别对应序列长度
        #   、批次大小和特征数(或输入大小)。如果你希望模型能够处理多个句子(即更大的批次),你应该相应地调整代码,
        #   使得 sentence 可以同时包含多条序列,并且批次大小不固定为1。
        embeds = self.word_embeds(sentence).view(len(sentence), 1, -1)
        lstm_out, self.hidden = self.lstm(embeds, self.hidden)
        lstm_out = lstm_out.view(len(sentence), self.hidden_dim)
        lstm_feats = self.hidden2tag(lstm_out)
        return lstm_feats
    
    def _score_sentence(self, feats, tags):
        # Gives the score of a provided tag sequence
        # 计算给定tag序列的分数,即一条路径的分数
        score = torch.zeros(1)
        tags = torch.cat([torch.tensor([self.tag_to_ix[START_TAG]], dtype=torch.long), tags])
        for i, feat in enumerate(feats):
            # 递推计算路径分数:转移分数 + 发射分数
            score = score + self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]
        score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]
        return score

    def _forward_alg(self, feats):
        # Do the forward algorithm to compute the partition function
        # 通过前向算法递推计算
        init_alphas = torch.full((1, self.tagset_size), -10000.)
        # START_TAG has all of the score.
        # 初始化step 0即START位置的发射分数,START_TAG取0其他位置取-10000
        init_alphas[0][self.tag_to_ix[START_TAG]] = 0.

        # Wrap in a variable so that we will get automatic backprop
        # 将初始化START位置为0的发射分数赋值给previous
        previous = init_alphas

        # Iterate through the sentence
        # 迭代整个句子
        for obs in feats:
            # The forward tensors at this timestep
            # 当前时间步的前向tensor
            alphas_t = []
            for next_tag in range(self.tagset_size):
                # broadcast the emission score: it is the same regardless of the previous tag
                # 取出当前tag的发射分数,与之前时间步的tag无关
                emit_score = obs[next_tag].view(1, -1).expand(1, self.tagset_size)
                # the ith entry of trans_score is the score of transitioning to next_tag from i
                # 取出当前tag由之前tag转移过来的转移分数
                trans_score = self.transitions[next_tag].view(1, -1)
                # The ith entry of next_tag_var is the value for the edge (i -> next_tag) before we do log-sum-exp
                # 当前路径的分数:之前时间步分数 + 转移分数 + 发射分数
                next_tag_var = previous + trans_score + emit_score
                # The forward variable for this tag is log-sum-exp of all the scores.
                # 对当前分数取log-sum-exp
                alphas_t.append(log_sum_exp(next_tag_var).view(1))
            # 更新previous 递推计算下一个时间步
            previous = torch.cat(alphas_t).view(1, -1)
        # 考虑最终转移到STOP_TAG
        terminal_var = previous + self.transitions[self.tag_to_ix[STOP_TAG]]
        # 计算最终的分数
        scores = log_sum_exp(terminal_var)
        return scores


    def _viterbi_decode(self, feats):
        backpointers = []

        # Initialize the viterbi variables in log space
        # 初始化viterbi的previous变量
        init_vvars = torch.full((1, self.tagset_size), -10000.)
        init_vvars[0][self.tag_to_ix[START_TAG]] = 0

        previous = init_vvars
        for obs in feats:
            # holds the backpointers for this step
            # 保存当前时间步的回溯指针
            bptrs_t = []
            # holds the viterbi variables for this step
            # 保存当前时间步的viterbi变量
            viterbivars_t = []  

            for next_tag in range(self.tagset_size):
                # next_tag_var[i] holds the viterbi variable for tag i at the
                # previous step, plus the score of transitioning
                # from tag i to next_tag.
                # We don't include the emission scores here because the max
                # does not depend on them (we add them in below)
                # 维特比算法记录最优路径时只考虑上一步的分数以及上一步tag转移到当前tag的转移分数
                # 并不取决与当前tag的发射分数
                next_tag_var = previous + self.transitions[next_tag]
                best_tag_id = argmax(next_tag_var)
                bptrs_t.append(best_tag_id)
                viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))
            # Now add in the emission scores, and assign forward_var to the set
            # of viterbi variables we just computed
            # 更新previous,加上当前tag的发射分数obs
            previous = (torch.cat(viterbivars_t) + obs).view(1, -1)
            # 回溯指针记录当前时间步各个tag来源前一步的tag
            backpointers.append(bptrs_t)

        # Transition to STOP_TAG
        # 考虑转移到STOP_TAG的转移分数
        terminal_var = previous + self.transitions[self.tag_to_ix[STOP_TAG]]
        best_tag_id = argmax(terminal_var)
        path_score = terminal_var[0][best_tag_id]

        # Follow the back pointers to decode the best path.
        # 通过回溯指针解码出最优路径
        best_path = [best_tag_id]
        # best_tag_id作为线头,反向遍历backpointers找到最优路径
        for bptrs_t in reversed(backpointers):
            best_tag_id = bptrs_t[best_tag_id]
            best_path.append(best_tag_id)
        # Pop off the start tag (we dont want to return that to the caller)
        # 去除START_TAG
        start = best_path.pop()
        assert start == self.tag_to_ix[START_TAG]  # Sanity check
        best_path.reverse()
        return path_score, best_path

    def neg_log_likelihood(self, sentence, tags):
        # CRF损失函数由两部分组成,真实路径的分数和所有路径的总分数。
        # 真实路径的分数应该是所有路径中分数最高的。
        # log真实路径的分数/log所有可能路径的分数,越大越好,构造crf loss函数取反,loss越小越好
        feats = self._get_lstm_features(sentence)
        forward_score = self._forward_alg(feats)
        gold_score = self._score_sentence(feats, tags)
        return forward_score - gold_score

    def forward(self, sentence):  # dont confuse this with _forward_alg above.
        # Get the emission scores from the BiLSTM
        # 通过BiLSTM提取发射分数
        lstm_feats = self._get_lstm_features(sentence)

        # Find the best path, given the features.
        # 根据发射分数以及转移分数,通过viterbi解码找到一条最优路径
        score, tag_seq = self._viterbi_decode(lstm_feats)
        return score, tag_seq



START_TAG = "<START>"
STOP_TAG = "<STOP>"
EMBEDDING_DIM = 5
HIDDEN_DIM = 4

# Make up some training data
# 构造一些训练数据
training_data = [(
    "the wall street journal reported today that apple corporation made money".split(),
    "B I I I O O O B I O O".split()
), (
    "georgia tech is a university in georgia".split(),
    "B I O O O O B".split()
)]

word_to_ix = {}
for sentence, tags in training_data:
    for word in sentence:
        if word not in word_to_ix:
            word_to_ix[word] = len(word_to_ix)

tag_to_ix = {"B": 0, "I": 1, "O": 2, START_TAG: 3, STOP_TAG: 4}

model = BiLSTM_CRF(len(word_to_ix), tag_to_ix, EMBEDDING_DIM, HIDDEN_DIM)
optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)

# Check predictions before training
# 训练前检查模型预测结果
with torch.no_grad():
    precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)
    precheck_tags = torch.tensor([tag_to_ix[t] for t in training_data[0][1]], dtype=torch.long)
    print(model(precheck_sent))

# Make sure prepare_sequence from earlier in the LSTM section is loaded
for epoch in range(300):  # again, normally you would NOT do 300 epochs, it is toy data
    for sentence, tags in training_data:
        # Step 1. Remember that Pytorch accumulates gradients.
        # We need to clear them out before each instance
        # 第一步,pytorch梯度累积,需要清零梯度
        model.zero_grad()

        # Step 2. Get our inputs ready for the network, that is,
        # turn them into Tensors of word indices.
        # 第二步,将输入转化为tensors
        sentence_in = prepare_sequence(sentence, word_to_ix)
        targets = torch.tensor([tag_to_ix[t] for t in tags], dtype=torch.long)

        # Step 3. Run our forward pass.
        # 进行前向计算,取出crf loss
        loss = model.neg_log_likelihood(sentence_in, targets)

        # Step 4. Compute the loss, gradients, and update the parameters by
        # calling optimizer.step()
        # 第四步,计算loss,梯度,通过optimier更新参数
        loss.backward()
        optimizer.step()

# Check predictions after training
# 训练结束查看模型预测结果,对比观察模型是否学到
with torch.no_grad():
    precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)
    print(model(precheck_sent))
# We got it!



改成批处理关键代码  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 sequence
                 in 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 sequence
    seq_lens = mask.sum(dim=1)
    # In mini batch, prepare the score
    # from the start sequence to the first label
    score = [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.coloradmin.cn/o/2260176.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

docker安装、升级、以及sudo dockerd --debug查看启动失败的问题

1、docker安装包tar下载地址 Index of linux/static/stable/x86_64/ 2、下载tgz文件并解压 tar -zxvf docker-24.0.8.tgz 解压后docker文件夹下位docker相关文件 3、将老版本docker相关文件&#xff0c;备份 将 /usr/bin/docker下docker相关的文件&#xff0c;mv到备份目录…

hive—炸裂函数explode/posexplode

1、Explode炸裂函数 将hive某列一行中复杂的 array 或 map 结构拆分成多行&#xff08;只能输入array或map&#xff09; 语法&#xff1a; select explode(字段) as 字段命名 from 表名; 举例&#xff1a; 1&#xff09;explode(array)使得结果中将array列表里的每个元素生…

【Android学习】RxJava

文章目录 资料连接1. Merge & Zip操作符: 合并数据源2. Map & FlapMap & ConcatMap & Buffer: 变换操作符3. retry & retryUntil & retryWhen : 错误处理操作符4. Transformer & Compose 转换符 资料连接 Android RxJava&#xff1a; 这是一份全面…

浅谈Kubernetes(K8s)之RC控制器与RS控制器

1.RC控制器 1.1RC概述 Replication Controller 控制器会持续监控正在运行的Pod列表&#xff0c;并保证相应类型的Pod的数量与期望相符合&#xff0c;如果Pod数量过少&#xff0c;它会根据Pod模板创建新的副本&#xff0c;反之则会删除多余副本。通过RC可实现了应用服务的高可用…

直流开关电源技术及应用

文章目录 1. 开关电源概论1.1 开关电源稳压原理1.1.1 开关电源稳压原理核心组成部分及其作用工作过程稳压原理 1. 开关电源概论 1.1 开关电源稳压原理 为了提高效率&#xff0c;必须使功率调整器件处于开关工作状态。 作为开关而言&#xff0c;导通时压降很小&#xff0c;几乎…

解决 MyBatis 中空字符串与数字比较引发的条件判断错误

问题复现 假设你在 MyBatis 的 XML 配置中使用了如下代码&#xff1a; <if test"isCollect ! null"><choose><when test"isCollect 1">AND exists(select 1 from file_table imgfile2 where task.IMAGE_SEQimgfile2.IMAGE_SEQ and im…

如何windows命令行使用kali?ssh连接高效又快捷

一、打开虚拟机kali进入cmd中 输入vim /etc/ssh/sshd_config&#xff0c;&#xff08;注意这里需要使用root权限&#xff09; 二、进入编辑文件页面 找到PermitRootLogin prohibit-password和 PasswordAuthentication no两行 将“prohibit-password”修改为“yes”&#xff0…

自动化测试之单元测试框架

单元测试框架 一、单元测试的定义 1&#xff1a;什么是单元测试&#xff1f; 还记不记得我们软件测试学习的时候&#xff0c;按照定义&#xff1a;单元测试就是对单个模块或者是单个函数进行测试&#xff0c;一般是开发做的&#xff0c;按照阶段来分&#xff0c;一般就是单元…

ansible部署nginx:1个简单的playbook脚本

文章目录 hosts--ventoryroles执行命令 使用ansible向3台centos7服务器上安装nginx hosts–ventory [rootstand playhook1]# cat /root/HOSTS # /root/HOSTS [webservers] 192.168.196.111 ansible_ssh_passpassword 192.168.196.112 ansible_ssh_passpassword 192.168.196.1…

SpringBoot左脚进门之Maven管理家

一、概念 Maven 是一个项目管理和整合工具。通过对 目录结构和构建生命周期 的标准化&#xff0c; 使开发团队用极少的时间就能够自动完成工程的基础构建配置。 Maven 简化了工程的构建过程&#xff0c;并对其标准化&#xff0c;提高了重用性。 Maven 本地仓库 (Local Reposi…

最短路----Dijkstra算法详解

简介 迪杰斯特拉&#xff08;Dijkstra&#xff09;算法是一种用于在加权图中找到单个源点到所有其他顶点的最短路径的算法。它是由荷兰计算机科学家艾兹格迪科斯彻&#xff08;Edsger Dijkstra&#xff09;在1956年提出的。Dijkstra算法适用于处理带有非负权重的图。迪杰斯特拉…

论文概览 |《Urban Analytics and City Science》2022.11 Vol.49 Issue.9

本次给大家整理的是《Environment and Planning B: Urban Analytics and City Science》杂志2022年11月第49卷第9期的论文的题目和摘要&#xff0c;一共包括19篇SCI论文&#xff01; 论文1 On economic and urban growth 经济发展与城市增长 【摘要】 The dominant imperativ…

软件安装不成功,一直出现“chrome_elf.dll丢失”问题是什么原因?“chrome_elf.dll丢失”要怎么解决和预防?

软件安装遇阻&#xff1a;“chrome_elf.dll丢失”问题全解析与解决方案 在软件安装与运行的过程中&#xff0c;我们时常会遇到各式各样的错误提示&#xff0c;其中“chrome_elf.dll丢失”便是较为常见的一种。这个错误不仅阻碍了软件的正常安装&#xff0c;也给用户带来了不小…

04面向对象篇(D4_OOT(D1_OOT - 面向对象测试))

目录 一、 面向对象影响测试 1. 封装性影响测试 2. 继承性影响测试 3. 多态性影响测试 二、 面向对象测试模型 三、 面向对象分析测试 1. 对象测试 2. 结构测试 3. 主题测试 4. 属性和实例关联测试 5. 服务和消息关联测试 四、面向对象设计测试 1. 对认定类测试 …

java之静态变量和方法(类变量、类方法)

1 类变量 1.1 简要介绍 由一个简单的程序引出&#xff1a; public class Example1 {int n;static int num 10; //有 static 修饰//此时 num 即为一个类变量&#xff08;静态变量&#xff09;&#xff0c;static 表示静态的//这个变量的最大特点是&#xff0c;它会被 Exampl…

朗致面试---IOS/安卓/Java/架构师

朗致面试---IOS/安卓/Java/架构师 一、面试概况二、总结三、算法题目参考答案 一、面试概况 一共三轮面试&#xff1a; 第一轮是逻辑行测&#xff0c;25道题目&#xff0c;类似于公务员考试题目&#xff0c;要求90分钟内完成。第二轮是技术面试&#xff0c;主要是做一些数据结…

五、网络层:控制平面,《计算机网络(自顶向下方法 第7版,James F.Kurose,Keith W.Ross)》

目录 一、导论 二、路由选择算法 2.1 路由&#xff08;route&#xff09;的概念 2.2 网络的图抽象 2.2.1 边和路由的代价 2.2.2 最优化原则 2.3 路由的原则 2.4 路由选择算法的分类 2.5 link state 算法 2.5.1 LS路由工作过程 2.5.2 链路状态路由选择&#xff08;lin…

音视频入门基础:MPEG2-TS专题(16)——PMT简介

一、引言 PMT&#xff08;Program Map Table&#xff09;与PAT表成对出现&#xff0c;其PID由PAT表给出。通过PMT表可以得到该节目包含的视频和音频信息&#xff0c;从而找到音视频流&#xff1a; 二、PMT表中的属性 根据《T-REC-H.222.0-202106-S!!PDF-E.pdf》第79页&#x…

结构变量的占用多少个字节

1、在linux中&#xff0c;这种写法比较清晰 struct gpio_led_data { u8 can_sleep; //如果定义了结构变量&#xff0c;则该成员占用1个字节 u8 blinking; //如果定义了结构变量&#xff0c;则该成员占用1个字节 }; struct gpio_leds_priv { int num_leds; //如…

网页端web内容批注插件:

感觉平时每天基本上90%左右的时间都在浏览器端度过&#xff0c;按理说很多资料都应该在web端输入并且输出&#xff0c;但是却有很多时间浪费到了各种桌面app中&#xff0c;比如说什么notion、语雀以及各种笔记软件中&#xff0c;以及导入到ipad的gn中&#xff0c;这些其实都是浪…