AllenNLP 用法总结

allennlp手动安装教程 公司内网手动安装allennlp,遇到问题及解决方案~ 阅读详情

AllenNLP另外很重要的一点在于,它在torch的model的基础上添加了很多的方法,使得模型更加适用于NLP场景的使用。

AllenNLP设计模型的思想在于:

输出为dict格式,里面必须包含loss,其余则由我们自行决定。因此输出相比传统的pytorch模型,输出更加的丰富,我们可以把我们任何想要的信息都通过这个字典返回~

model.py文件有370多行,

大体上需要注意的是

  • __init__ 里要传入vocab与regularizer
  • get_regularization_penalty 得到类似L1或者L2正则的惩罚值。
  • get_parameters_for_histogram_tensorboard_logging 得到的值用于tensorboard
  • forward 最为关键的前向传播函数
  • forward_on_instance 在一条数据上进行eval
  • forward_on_instances在一堆数据上进行eval
  • decode 对答案进行解码,例如label等
  • get_metrics 返回模型的评估结果,如准确率
  • _get_prediction_device 预测得到GPU设备
  • _load 读取模型
  • load 调用_load函数
  • extend_embedder_vocab fintuning或者迁移学习时,扩充我们的词表与embedding矩阵

具体如下面代码~

# 设定并存储了一个best.th 的模型
# When training a model, many sets of weights are saved. By default we want to
# save/load this set of weights.
_DEFAULT_WEIGHTS = "best.th"


class Model(torch.nn.Module, Registrable):
    """
    This abstract class represents a model to be trained. Rather than relying completely
    on the Pytorch Module, we modify the output spec of ``forward`` to be a dictionary.

    Models built using this API are still compatible with other pytorch models and can
    be used naturally as modules within other models - outputs are dictionaries, which
    can be unpacked and passed into other layers. One caveat to this is that if you
    wish to use an AllenNLP model inside a Container (such as nn.Sequential), you must
    interleave the models with a wrapper module which unpacks the dictionary into
    a list of tensors.

    In order for your model to be trained using the :class:`~allennlp.training.Trainer`
    api, the output dictionary of your Model must include a "loss" key, which will be
    optimised during the training process.

    Finally, you can optionally implement :func:`Model.get_metrics` in order to make use
    of early stopping and best-model serialization based on a validation metric in
    :class:`~allennlp.training.Trainer`. Metrics that begin with "_" will not be logged
    to the progress bar by :class:`~allennlp.training.Trainer`.
    """
    _warn_for_unseparable_batches: Set[str] = set()

    # 必然是要传入一个词表的~
    def __init__(self,
                 vocab: Vocabulary,
                 regularizer: RegularizerApplicator = None) -> None:
        super().__init__()
        self.vocab = vocab
        self._regularizer = regularizer

    # 得到对某些层的参数的惩罚
    def get_regularization_penalty(self) -> Union[float, torch.Tensor]:
        """
        Computes the regularization penalty for the model.
        Returns 0 if the model was not configured to use regularization.
        """
        if self._regularizer is None:
            return 0.0
        else:
            return self._regularizer(self)

    def get_parameters_for_histogram_tensorboard_logging( # pylint: disable=invalid-name
            self) -> List[str]:
        """
        Returns the name of model parameters used for logging histograms to tensorboard.
        """
        return [name for name, _ in self.named_parameters()]

    # 关键的forward函数,看英文注释便可
    def forward(self, *inputs) -> Dict[str, torch.Tensor]:  # pylint: disable=arguments-differ
        """
        Defines the forward pass of the model. In addition, to facilitate easy training,
        this method is designed to compute a loss function defined by a user.

        The input is comprised of everything required to perform a
        training update, `including` labels - you define the signature here!
        It is down to the user to ensure that inference can be performed
        without the presence of these labels. Hence, any inputs not available at
        inference time should only be used inside a conditional block.

        The intended sketch of this method is as follows::

            def forward(self, input1, input2, targets=None):
                ....
                ....
                output1 = self.layer1(input1)
                output2 = self.layer2(input2)
                output_dict = {"output1": output1, "output2": output2}
                if targets is not None:
                    # Function returning a scalar torch.Tensor, defined by the user.
                    loss = self._compute_loss(output1, output2, targets)
                    output_dict["loss"] = loss
                return output_dict

        Parameters
        ----------
        inputs:
            Tensors comprising everything needed to perform a training update, `including` labels,
            which should be optional (i.e have a default value of ``None``).  At inference time,
            simply pass the relevant inputs, not including the labels.

        Returns
        -------
        output_dict: ``Dict[str, torch.Tensor]``
            The outputs from the model. In order to train a model using the
            :class:`~allennlp.training.Trainer` api, you must provide a "loss" key pointing to a
            scalar ``torch.Tensor`` representing the loss to be optimized.
        """
        raise NotImplementedError

    # 很机制,干脆直接调用处理多个输入的方法
    def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]:
        """
        Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it,
        converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays
        through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing)
        and returns the result.  Before returning the result, we convert any
        ``torch.Tensors`` into numpy arrays and remove the batch dimension.
        """
        return self.forward_on_instances([instance])[0]

    # 这里非常重要!!!!!!!!!!
    # 我们自行做DIY完全可以按照这种思路来做!
    # 比如Batch的操作~!
    def forward_on_instances(self,
                             instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]:
        """
        Takes a list of  :class:`~allennlp.data.instance.Instance`s, converts that text into
        arrays using this model's :class:`Vocabulary`, passes those arrays through
        :func:`self.forward()` and :func:`self.decode()` (which by default does nothing)
        and returns the result.  Before returning the result, we convert any
        ``torch.Tensors`` into numpy arrays and separate the
        batched output into a list of individual dicts per instance. Note that typically
        this will be faster on a GPU (and conditionally, on a CPU) than repeated calls to
        :func:`forward_on_instance`.

        Parameters
        ----------
        instances : List[Instance], required
            The instances to run the model on.

        Returns
        -------
        A list of the models output for each instance.
        """

        batch_size = len(instances)
        with torch.no_grad():
            cuda_device = self._get_prediction_device()
            # 将我们的instances原本不等长
            # 变成一个batch,这样 之后 就可以使用padding等操作
            dataset = Batch(instances)
            # 使用index_instances,词表,将我们的instance变成数值化
            dataset.index_instances(self.vocab)
            # 使用as_tensor_dict方法,将数据变成tensor
            model_input = util.move_to_device(dataset.as_tensor_dict(), cuda_device)
            # 调用模型decode方法~,将数值化的结果再反解回 文本
            outputs = self.decode(self(**model_input))

            # 将batch拆解成 一个个单独的实例,并且返回numpy的格式
            instance_separated_output: List[Dict[str, numpy.ndarray]] = [{} for _ in dataset.instances]
            for name, output in list(outputs.items()):
                if isinstance(output, torch.Tensor):
                    # NOTE(markn): This is a hack because 0-dim pytorch tensors are not iterable.
                    # This occurs with batch size 1, because we still want to include the loss in that case.
                    if output.dim() == 0:
                        output = output.unsqueeze(0)

                    if output.size(0) != batch_size:
                        self._maybe_warn_for_unseparable_batches(name)
                        continue
                    output = output.detach().cpu().numpy()
                elif len(output) != batch_size:
                    self._maybe_warn_for_unseparable_batches(name)
                    continue
                for instance_output, batch_element in zip(instance_separated_output, output):
                    instance_output[name] = batch_element
            return instance_separated_output

    # 解码部分
    def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
        """
        Takes the result of :func:`forward` and runs inference / decoding / whatever
        post-processing you need to do your model.  The intent is that ``model.forward()`` should
        produce potentials or probabilities, and then ``model.decode()`` can take those results and
        run some kind of beam search or constrained inference or whatever is necessary.  This does
        not handle all possible decoding use cases, but it at least handles simple kinds of
        decoding.

        This method `modifies` the input dictionary, and also `returns` the same dictionary.

        By default in the base class we do nothing.  If your model has some special decoding step,
        override this method.
        """
        # pylint: disable=no-self-use
        return output_dict

    # 返回模型的评估结果
    def get_metrics(self, reset: bool = False) -> Dict[str, float]:
        """
        Returns a dictionary of metrics. This method will be called by
        :class:`allennlp.training.Trainer` in order to compute and use model metrics for early
        stopping and model serialization.  We return an empty dictionary here rather than raising
        as it is not required to implement metrics for a new model.  A boolean `reset` parameter is
        passed, as frequently a metric accumulator will have some state which should be reset
        between epochs. This is also compatible with :class:`~allennlp.training.Metric`s. Metrics
        should be populated during the call to ``forward``, with the
        :class:`~allennlp.training.Metric` handling the accumulation of the metric until this
        method is called.
        """
        # pylint: disable=unused-argument,no-self-use
        return {}

    def _get_prediction_device(self) -> int:
        """
        This method checks the device of the model parameters to determine the cuda_device
        this model should be run on for predictions.  If there are no parameters, it returns -1.

        Returns
        -------
        The cuda device this model should run on for predictions.
        """
        devices = {util.get_device_of(param) for param in self.parameters()}

        if len(devices) > 1:
            devices_string = ", ".join(str(x) for x in devices)
            raise ConfigurationError(f"Parameters have mismatching cuda_devices: {devices_string}")
        elif len(devices) == 1:
            return devices.pop()
        else:
            return -1

    def _maybe_warn_for_unseparable_batches(self, output_key: str):
        """
        This method warns once if a user implements a model which returns a dictionary with
        values which we are unable to split back up into elements of the batch. This is controlled
        by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose
        otherwise.
        """
        if  output_key not in self._warn_for_unseparable_batches:
            logger.warning(f"Encountered the {output_key} key in the model's return dictionary which "
                           "couldn't be split by the batch size. Key will be ignored.")
            # We only want to warn once for this key,
            # so we set this to false so we don't warn again.
            self._warn_for_unseparable_batches.add(output_key)

    @classmethod
    def _load(cls,
              config: Params,
              serialization_dir: str,
              weights_file: str = None,
              cuda_device: int = -1) -> 'Model':
        """
        Instantiates an already-trained model, based on the experiment
        configuration and some optional overrides.
        """
        weights_file = weights_file or os.path.join(serialization_dir, _DEFAULT_WEIGHTS)

        # Load vocabulary from file
        vocab_dir = os.path.join(serialization_dir, 'vocabulary')
        # If the config specifies a vocabulary subclass, we need to use it.
        vocab_params = config.get("vocabulary", Params({}))
        vocab_choice = vocab_params.pop_choice("type", Vocabulary.list_available(), True)
        vocab = Vocabulary.by_name(vocab_choice).from_files(vocab_dir)

        model_params = config.get('model')

        # The experiment config tells us how to _train_ a model, including where to get pre-trained
        # embeddings from.  We're now _loading_ the model, so those embeddings will already be
        # stored in our weights.  We don't need any pretrained weight file anymore, and we don't
        # want the code to look for it, so we remove it from the parameters here.
        remove_pretrained_embedding_params(model_params)
        model = Model.from_params(vocab=vocab, params=model_params)

        # If vocab+embedding extension was done, the model initialized from from_params
        # and one defined by state dict in weights_file might not have same embedding shapes.
        # Eg. when model embedder module was transferred along with vocab extension, the
        # initialized embedding weight shape would be smaller than one in the state_dict.
        # So calling model embedding extension is required before load_state_dict.
        # If vocab and model embeddings are in sync, following would be just a no-op.
        # 拓展embedding的vocabulary
        model.extend_embedder_vocab()

        model_state = torch.load(weights_file, map_location=util.device_mapping(cuda_device))
        model.load_state_dict(model_state)

        # Force model to cpu or gpu, as appropriate, to make sure that the embeddings are
        # in sync with the weights
        if cuda_device >= 0:
            model.cuda(cuda_device)
        else:
            model.cpu()

        return model

    @classmethod
    def load(cls,
             config: Params,
             serialization_dir: str,
             weights_file: str = None,
             cuda_device: int = -1) -> 'Model':
        """
        Instantiates an already-trained model, based on the experiment
        configuration and some optional overrides.

        Parameters
        ----------
        config: Params
            The configuration that was used to train the model. It should definitely
            have a `model` section, and should probably have a `trainer` section
            as well.
        serialization_dir: str = None
            The directory containing the serialized weights, parameters, and vocabulary
            of the model.
        weights_file: str = None
            By default we load the weights from `best.th` in the serialization
            directory, but you can override that value here.
        cuda_device: int = -1
            By default we load the model on the CPU, but if you want to load it
            for GPU usage you can specify the id of your GPU here


        Returns
        -------
        model: Model
            The model specified in the configuration, loaded with the serialized
            vocabulary and the trained weights.
        """

        # Peak at the class of the model.
        model_type = config["model"] if isinstance(config["model"], str) else config["model"]["type"]

        # Load using an overridable _load method.
        # This allows subclasses of Model to override _load.
        # pylint: disable=protected-access
        return cls.by_name(model_type)._load(config, serialization_dir, weights_file, cuda_device)

    # 扩充词表
    def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None:
        """
        Iterates through all embedding modules in the model and assures it can embed
        with the extended vocab. This is required in fine-tuning or transfer learning
        scenarios where model was trained with original vocabulary but during
        fine-tuning/transfer-learning, it will have it work with extended vocabulary
        (original + new-data vocabulary).

        Parameters
        ----------
        embedding_sources_mapping : Dict[str, str], (optional, default=None)
            Mapping from model_path to pretrained-file path of the embedding
            modules. If pretrained-file used at time of embedding initialization
            isn't available now, user should pass this mapping. Model path is
            path traversing the model attributes upto this embedding module.
            Eg. "_text_field_embedder.token_embedder_tokens".
        """
        # self.named_modules() gives all sub-modules (including nested children)
        # The path nesting is already separated by ".": eg. parent_module_name.child_module_name
        embedding_sources_mapping = embedding_sources_mapping or {}
        for model_path, module in self.named_modules():
            if hasattr(module, 'extend_vocab'):
                pretrained_file = embedding_sources_mapping.get(model_path, None)
                module.extend_vocab(self.vocab,
                                    extension_pretrained_file=pretrained_file,
                                    model_path=model_path)

def remove_pretrained_embedding_params(params: Params):
    if isinstance(params, Params):  # The model could possible be a string, for example.
        keys = params.keys()
        if 'pretrained_file' in keys:
            del params['pretrained_file']
        for value in params.values():
            if isinstance(value, Params):
                remove_pretrained_embedding_params(value)
AllenNLP入门笔记(一) NLP的项目流程比较繁琐,正好现在又AllenNLP这个基于PyTorch的工具可以用于规范数据处理,模型构建、训练和测试,感觉不错。之前看了一篇论文,作者用TensorFlow 1.13版本写的一个NLP项目,感觉实在是复杂。 目录AllenNLP概要AllenNLP官方样例代码导入库读取数据集构建模型训练、测试模型更详细的教程 AllenNLP概要 先看一下AllenNLP(https://a... 阅读详情

相关推荐

数据挖掘工具AllenNLP

1.背景介绍 数据挖掘是一种利用计算机科学技术来从大量数据中发现隐藏的模式、关系和知识的过程。数据挖掘技术广泛应用于各个领域,如金融、医疗、教育、商业等,帮助企业和组织更好地理解数据,提高决策效率。 AllenNLP是一个基于Python的数据挖掘工具,由Facebook AI Research(FAIR)开发。它提供了一系列的自然语言处

AI天才研究院 1290

深入了解Allennlp细

前言 本次将要介绍的是Allennlp框架,这是一个基于Pytorch,面向深度学习中的自然语言处理领域的框架,提供了众多的新兴算法和预训练模型,只需要简单的几行代码就可以完成很棒的功能。 本次教程,通过示例代码来讲解不同模块的使用方法和原理,希望通过本篇博文,大家能够顺利使用上Allennlp,因为相比纯手动撸Pytorch,Allennlp真的能够加速Idea的实现。 参考论文:AllenNLP: A Deep Semantic Natural Language Processing Plat..

张伟的专栏 2856

『NLP学习笔记』AllenNLP的注册机制

AllenNLP的注册机制! 文章目录1. 为什么要使用Registrable2. Registrable 类的使用方法3. Registrable 类的进阶用法 作为正式内容的铺垫,这一讲我们就先来学习一下AllenNLP的注册机制。之所以要先说这个,是因为在AllenNLP当中,所有的类都是可以动态加载的,最简单的理解就是,你在Json里存一个比如 dataset 的类名, 他会根据这个类名自动的去找到这个类的定义,然后创建一个实例。所以很多时候,你在网上搜索别人实现的比如文本分类的算法时,别人可

AI新视界 517

AllenNLP: 强大的自然语言处理开源库

AllenNLP是一个开源的自然语言处理(NLP)研究库,由艾伦人工智能研究所(AI2)开发。它建立在PyTorch深度学习框架之上,旨在为研究人员和开发者提供一个灵活而强大的工具,用于开发各种NLP任务的最先进模型。AllenNLP的设计理念是使NLP研究更加容易和高效。它提供了许多常用NLP组件的高质量实现,如数据加载、词向量、注意力机制等,让研究人员可以专注于模型创新,而不是重复造轮子。同时,AllenNLP还具有很强的可扩展性,允许用户根据需要自定义和扩展各个组件。

helloaiworld的博客 1473

allennlp能实现的功能

对allennlp能实现的功能做了一个总结,还有实例demo的截图。

Unity布娃娃系统 Ragdoll Mecanim Mixer使用

6. 选完之后,左键下面的hip等角色各个部位不松开鼠标,拖拽连接到上面Amature的各个部位,如图,下面所有部位都连接完之后,第二步点击Configure Selected Bones确认你的部位连接选择。要做一个布娃娃和动画混合的项目,这个插件是比较不错的,搜了一圈文章教程也是抄来抄去,抄的没有头没有尾,自己摸索着用了一下,记录使用过程吧。8. 之后就点击步骤7图一中的Create Ragdoll,会发现player结构发生变化,如图。4. 添加完脚本之后会显示你的player结构,如图。

SuShengQuanshiW的博客 1649

allennlp train 参数

allennlp train命令的参数使用: 在命令行运行:allennlp train -h,即可看到详细解释 usage(用法): allennlp train [-h] -s SERIALIZATION_DIR [-r] [-f] [-o OVERRIDES] [--file-friendly-logging] [--cache-directory CACHE_DIRECTORY] .

weixin_39450145的博客 840

H无穷控制学习笔记——加权灵敏度H无穷控制问题

一、加权灵敏度H无穷问题 系统结构如上图所示。被控对象P的状态空间方程为(Ap,Bp,Cp,DpA_p,B_p,C_p,D_pAp​,Bp​,Cp​,Dp​),加权函数W1的状态空间方程为(A1,B1,C1,D1A_1,B_1,C_1,D_1A1​,B1​,C1​,D1​),加权函数W2的状态空间方程为(A2,B2,C2,D2A_2,B_2,C_2,D_2A2​,B2​,C2​,D2​),加权函数W3的状态空间方程为(A3,B3,C3,D3A_3,B_3,C_3,D_3A3​,B3​,C3​,D3​)。

一饮丶一啄的博客 4349

如何在jieba分词中加自定义词典_AllenNLP源码拓展——中文分词

AllenNLP中常使用spacy对英文进行分词,但是spacy不能对中文分词。因此我想尝试加一个中文分词的word_splitter。对比了一些中文分词包,最后在THULAC和jieba中进行选择,据说前者更准确,后者速度更快,为了保证准确,我选择了前者(不知道还有没有更好的)。我参考spacy部分的代码弄了一个THUNLPSplitter。测试代码:(postags指是否标注词性,only_t...

weixin_39969028的博客 264

草莓成熟度与叶片病虫害智能检测数据集应用全解析

本文深入解析草莓成熟度与叶片病虫害智能检测数据集的应用价值,涵盖从绿草莓到红果转色的完整成熟周期及白粉病、炭疽病等7种病害的精准识别。通过实战案例展示如何提升病害识别率至94%,并介绍数据集的科研价值,包括跨品种迁移学习和多模态数据融合技术。

weixin_28366353的博客 275

PLC控制气缸与电磁阀:从原理到实战编程详解

在工业自动化领域,很多工程师都能编写PLC程序控制电机启停,但当涉及到气缸和电磁阀的精确控制时,却常常遇到动作不协调、响应延迟甚至设备损坏的问题。这背后的关键不在于PLC编程本身,而在于对气动元件特性和控制逻辑的深入理解。 本文将从实际工程问题出发,深入解析气缸与电磁阀的工作原理、PLC控制逻辑设计、常见故障排查方法,并通过完整的梯形图实例,帮助读者掌握气动系统自动化编程的核心要点。无论你是刚接触PLC的初学者,还是希望提升气动控制技能的工程师,都能从中获得实用的技术指导。 1. 气缸与电磁阀在自动化控制中

weixin_42522374的博客 337

记录第一次跑Multi-Grained-NER-master代码的成长历程

距离拿到这个代码到写下这篇博客已经过去三周有余了。我因为一样Allennlp版本刚好更新,然后装的最新版的。这个文章的代码总是跑不起来,现在各种搜索,终于跨出了一步。 第一次听到博士师兄说Allennlp文档更新了,我就没想太多,而且之前喜欢什么都安装最新的,所以就在python==3.8,tensorflow==2.3.1,torch==1.7。0,allennlp==1.2.0这几个最新的版本上一直钻研琢磨。 我找了很多查找方式,比如搜索allennlp的用法,elmo embedding,等等,去

zmcadlf的博客 278

DFT实训教程笔记2(bibili版本)- Scan synthesis practice

文章目录Scan synthesis practice 本博文是博主记录DFT实训教程的笔记版本,此笔记并没有对所有的知识进行记录,仅仅以自身的认知水平,来记录了一些部分笔记并加上了自己的理解。 Scan synthesis practice How to design scan clock structure? 假设一块chip里面有好几十个clock domain,如果每一个clock domain都用一个scan clock虽然会非常清晰,但是IO数目肯定不够用。 clock group: 1、no

ciscomonkey的博客 9082

【AllenNLP】: 自定义predictor—输入文本输出中文

说明 我们在使用AllenNLP的时候,当使用自定义predictor的时候,默认的是输入json,我们可以修改为输入以行为单位的文本格式; 另外默认的输出是json,我们也可以自定义修改为文本,特别是在json.dumps的时候中文会默认是ASCII码,我们自定义的时候可以设置为False来输出中文字符; 另外默认的输出只有label,没有input_text作为参考,我们可以在outputs中新增,来方便地查看预测输出: from copy import deepcopy from typing imp

Jack_Kuo的博客 1207

基于 国产USRP B210 的通信+侦测+干扰三合一实验平台,解锁无线攻防全场景!

在当代复杂电磁环境与多样化通信需求并存的背景下,软件定义无线电(SDR)技术正展现出前所未有的系统灵活性与功能可重构性。由两台USRP-LW B210软件无线电设备模拟无线链路通信过程,能够模拟多种无线通信信号传输及图像传输场景,适用于通信协议验证、抗干扰测试及教学实验。,支持"通信-侦测-干扰-优化"的闭环实验流程,为无线通信领域的教学科研与工程应用提供了一套经济高效、功能完备的解决方案。系统可对通信链路信号进行快速、自动化侦测、识别、告警,并支持多种干扰信号生成、模式切换及效果评估功能。

luowave2012的博客 832

柔性电极材料新突破:清华团队实现0.1mV级脑信号采集精度

清华团队的 0.1mV 级柔性电极突破,不仅是材料科学与神经工程的跨界胜利,更标志着脑机接口从 “信号采集” 向 “神经交互” 的范式转变。当电极与脑组织实现 “柔性共生”,人类首次拥有了窥探大脑微观电活动的 “精密探头”,这既是神经疾病诊疗的里程碑,更是人机融合时代的新起点。随着技术标准化与产业生态的完善,这场始于实验室的 “柔性革命”,正加速向临床病房、智能工厂、消费电子等场景渗透,为脑机接口的大规模应用铺设 “柔性跑道”。:当柔性电极实现 “神经信号的无损捕捉”,如何平衡技术创新与伦理边界?

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 2944

AllenNlp使用josn构建Model时 from_params was passed a `params` object that was not a `Params`.

AllenNlp使用josn构建Model时 from_params was passed a `params` object that was not a `Params`

qq_45862617的博客 312

UGUI合批杀手:Mask/RectMask2D为何必断合批?

颜色缓冲负责记录像素颜色;模板缓冲负责记录“这个像素的模板值”(一个小整数);渲染时,你可以设定:只有模板值为 X 的地方才允许画;或者往某些区域写特定的模板值。类似于:先拿一支隐形笔在纸上画出一块区域,给它记一个编号“1”,后面的涂色动作只允许涂在“编号为1”的区域上。合批的前提:渲染状态不变,连续元素能一口气画完。材质、贴图、混合模式、Stencil、裁剪区域……都得一致。Mask / RectMask2D 的本质:在渲染状态上加规则——“只在某个区域内允许写像素”。

本博客聚焦游戏开发技巧、创业实战心得及大学热门课程干货。这里既有技术深度,也有思维广度,无论你是开发者、创业者还是高校学子,都能在这里找到适合自己的成长之路! 119

allennlp使用

https://www.jiqizhixin.com/articles/2019-08-13-3 四种常见NLP框架使用总结(里面有关于allennlp的部分) AllenNLP是一个基于PyTorch的NLP研究库,可为开发者提供语言任务中的各种业内最佳训练模型。官网提供了一个很好的入门教程[2]https://guide.allennlp.org/,能够让初学者在30分钟内就了解AllenNLP的使用方法。 1.https://docs.allennlp.org/master/ 官方alle..

weixin_39450145的博客 1977

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

NLP的强大工具——AllenNLP

学习NLP,推荐一下AllenNLP这个工具。 从学习pytorch到学习处理NLP问题,中间有很长的路要走,其中有很多坑。NLP数据的预处理要比CV的麻烦很多,比如去除停用词,建立词典,加载各种预训练词向量,Sentence -> Word ID -> Word Embedding的过程(文本预处理方法小记)。用到RNN时,还要经过pad,pack,pad的过程。还有数据集的读取,t...

街道口扛把子的博客 1万+

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

安装allennlp库

出现错误: ERROR: Could not find a version that satisfies the requirement torch<1.8.0,>=1.6.0 (from allennlp) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) ERROR: No matching distribution found for torch<1.8.0,>=1.6.0 (from allennlp) ...

weixin_39450145的博客 3991

AllenNLP训练的方式

前几天看到一个群里有人问,AllenNLP在控制台使用命令train时,什么时候建立的词典,于是今天浏览了一下AllenNLP的代码。 在train.py的class Train(Subcommand):类里,这里用parser定义了一些命令行的输入指令。在控制台输入allennlp train XXX -s XXX之后,读取配置文件.json,然后进入到 train_model(params, ...

街道口扛把子的博客 1602

AllenNLP框架学习笔记(入门篇)

最近接触到一个很棒的自然语言处理工具——AllenNLP,解决了很多在自然语言处理过程中遇到的痛点问题,开发这个工具也是鼎鼎大名的A2I实验室,然后就去拜读了他们在github上分享的文档(当然,对于本英语渣来说,如果不是中文资料实在是比较少,是不会开启左百度右谷歌模式的),发觉这个框架!真tm棒!后面在打造自己的工作箱时,越发觉得allennlp的工程思维值得每个nlper学习,因此决定深度去阅读其中优雅的代码以及官方文档,并将其记录下来。 为什么值得研究 工欲善其事,必先利器。在进行自然语言处理的过.

<p>专注挖坑</p> 3678

AllenNLP之入门解读代码

本文解读代码https://github.com/dmesquita/easy-deep-learning-with-AllenNLP,用不到三百行的代码解决一个文本分类的任务,实现了NLP的整个流程。 一、前期准备: 配环境:参见我的上一篇博客https://blog.youkuaiyun.com/Findingxu/article/details/90722995 下代码:在Ubuntu上 git c...

Findingxu的博客 3532

AllenNLP Demo 项目教程

AllenNLP Demo 项目教程 1. 项目介绍 AllenNLP Demo 是一个用于展示 AllenNLP 自然语言处理库功能的 Web 应用程序。AllenNLP 是一个开源的 NLP 研究库,提供了许多先进的 NLP 模型和工具。AllenNLP Demo 通过一个用户友好的界面,让用户能够直观地体验和测试这些模型的功能。 2. 项目快速启动 环境准备 在开始之前,请确保你已经安装了以...

gitblog_00074的博客 593

Conda 下 安装 Allennlp

Conda 下 安装 Allennlp

sunyanbang的博客 5126
上一篇: 评价指标汇总--------汇总
下一篇: 多GPU训练半精度和单精度问题
Carlosi
博客等级 码龄9年 4粉丝 27原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Carlosi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值