Neural network sequence labeling model

Overview

Sequence labeler

This is a neural network sequence labeling system. Given a sequence of tokens, it will learn to assign labels to each token. Can be used for named entity recognition, POS-tagging, error detection, chunking, CCG supertagging, etc.

The main model implements a bidirectional LSTM for sequence tagging. In addition, you can incorporate character-level information -- either by concatenating a character-based representation, or by using an attention/gating mechanism for combining it with a word embedding.

Run with:

python experiment.py config.conf

Preferably with Tensorflow set up to use CUDA, so the process can run on a GPU. The script will train the model on the training data, test it on the test data, and print various evaluation metrics.

Note: The original sequence labeler was implemented in Theano, but since Theano is soon ending support, I have reimplemented it in TensorFlow. I also used the chance to refactor the code a bit, and it should be better in every way. However, if you need the specific code used in previously published papers, you'll need to refer to older commits.

Requirements

  • python (tested with 2.7.12 and 3.5.2)
  • numpy (tested with 1.13.3 and 1.14.0)
  • tensorflow (tested with 1.3.0 and 1.4.1)

Data format

The training and test data is expected in standard CoNLL-type tab-separated format. One word per line, separate column for token and label, empty line between sentences.

For error detection, this would be something like:

I       c
saws    i
the     c
show    c

The first column is assumed to be the token and the last column is the label. There can be other columns in the middle, which are currently not used. For example:

EU      NNP     I-NP    S-ORG
rejects VBZ     I-VP    O
German  JJ      I-NP    S-MISC
call    NN      I-NP    O
to      TO      I-VP    O
boycott VB      I-VP    O
British JJ      I-NP    S-MISC
lamb    NN      I-NP    O
.       .       O       O

Configuration

Edit the values in config.conf as needed:

  • path_train - Path to the training data, in CoNLL tab-separated format. One word per line, first column is the word, last column is the label. Empty lines between sentences.
  • path_dev - Path to the development data, used for choosing the best epoch.
  • path_test - Path to the test file. Can contain multiple files, colon separated.
  • conll_eval - Whether the standard CoNLL NER evaluation should be run.
  • main_label - The output label for which precision/recall/F-measure are calculated. Does not affect accuracy or measures from the CoNLL eval.
  • model_selector - What is measured on the dev set for model selection: "dev_conll_f:high" for NER and chunking, "dev_acc:high" for POS-tagging, "dev_f05:high" for error detection.
  • preload_vectors - Path to the pretrained word embeddings, in word2vec plain text format. If your embeddings are in binary, you can use convertvec to convert them to plain text.
  • word_embedding_size - Size of the word embeddings used in the model.
  • crf_on_top - If True, use a CRF as the output layer. If False, use softmax instead.
  • emb_initial_zero - Whether word embeddings should have zero initialisation by default.
  • train_embeddings - Whether word embeddings should be updated during training.
  • char_embedding_size - Size of the character embeddings.
  • word_recurrent_size - Size of the word-level LSTM hidden layers.
  • char_recurrent_size - Size of the char-level LSTM hidden layers.
  • hidden_layer_size - Size of the extra hidden layer on top of the bi-LSTM.
  • char_hidden_layer_size - Size of the extra hidden layer on top of the character-based component.
  • lowercase - Whether words should be lowercased when mapping to word embeddings.
  • replace_digits - Whether all digits should be replaced by 0.
  • min_word_freq - Minimal frequency of words to be included in the vocabulary. Others will be considered OOV.
  • singletons_prob - The probability of mapping words that appear only once to OOV instead during training.
  • allowed_word_length - Maximum allowed word length, clipping the rest. Can be necessary if the text contains unreasonably long tokens, eg URLs.
  • max_train_sent_length - Discard sentences longer than this limit when training.
  • vocab_include_devtest - Load words from dev and test sets also into the vocabulary. If they don't appear in the training set, they will have the default representations from the preloaded embeddings.
  • vocab_only_embedded - Whether the vocabulary should contain only words in the pretrained embedding set.
  • initializer - The method used to initialize weight matrices in the network.
  • opt_strategy - The method used for weight updates.
  • learningrate - Learning rate.
  • clip - Clip the gradient to a range.
  • batch_equal_size - Create batches of sentences with equal length.
  • epochs - Maximum number of epochs to run.
  • stop_if_no_improvement_for_epochs - Training will be stopped if there has been no improvement for n epochs.
  • learningrate_decay - If performance hasn't improved for 3 epochs, multiply the learning rate with this value.
  • dropout_input - The probability for applying dropout to the word representations. 0.0 means no dropout.
  • dropout_word_lstm - The probability for applying dropout to the LSTM outputs.
  • tf_per_process_gpu_memory_fraction - The fraction of GPU memory that the process can use.
  • tf_allow_growth - Whether the GPU memory usage can grow dynamically.
  • main_cost - Control the weight of the main labeling objective.
  • lmcost_max_vocab_size = Maximum vocabulary size for the language modeling loss. The remaining words are mapped to a single entry.
  • lmcost_hidden_layer_size = Hidden layer size for the language modeling loss.
  • lmcost_gamma - Weight for the language modeling loss.
  • char_integration_method - How character information is integrated. Options are: "none" (not integrated), "concat" (concatenated), "attention" (the method proposed in Rei et al. (2016)).
  • save - Path to save the model.
  • load - Path to load the model.
  • garbage_collection - Whether garbage collection is explicitly called. Makes things slower but can operate with bigger models.
  • lstm_use_peepholes - Whether to use the LSTM implementation with peepholes.
  • random_seed - Random seed for initialisation and data shuffling. This can affect results, so for robust conclusions I recommend running multiple experiments with different seeds and averaging the metrics.

Printing output

There is now a separate script for loading a saved model and using it to print output for a given input file. Use the save option in the config file for saving the model. The input file needs to be in the same format as the training data (one word per line, labels in a separate column). The labels are expected for printing output as well. If you don't know the correct labels, just print any valid label in that field.

To print the output, run:

python print_output.py labels model_file input_file

This will print the input file to standard output, with an extra column at the end that shows the prediction.

You can also use:

python print_output.py probs model_file input_file

This will print the individual probabilities for each of the possible labels. If the model is using CRFs, the probs option will output unnormalised state scores without taking the transitions into account.

References

The main sequence labeling model is described here:

Compositional Sequence Labeling Models for Error Detection in Learner Writing
Marek Rei and Helen Yannakoudakis
In Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (ACL-2016)

The character-level component is described here:

Attending to characters in neural sequence labeling models
Marek Rei, Gamal K.O. Crichton and Sampo Pyysalo
In Proceedings of the 26th International Conference on Computational Linguistics (COLING-2016)

The language modeling objective is described here:

Semi-supervised Multitask Learning for Sequence Labeling
Marek Rei
In Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (ACL-2017)

The CRF implementation is based on:

Neural Architectures for Named Entity Recognition
Guillaume Lample, Miguel Ballesteros, Sandeep Subramanian, Kazuya Kawakami and Chris Dyer
In Proceedings of NAACL-HLT 2016

The conlleval.py script is from: https://github.com/spyysalo/conlleval.py

License

The code is distributed under the Affero General Public License 3 (AGPL-3.0) by default. If you wish to use it under a different license, feel free to get in touch.

Copyright (c) 2018 Marek Rei

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

Owner
Marek Rei
Researcher in machine learning and natural language processing.
Marek Rei
Transformers and related deep network architectures are summarized and implemented here.

Transformers: from NLP to CV This is a practical introduction to Transformers from Natural Language Processing (NLP) to Computer Vision (CV) Introduct

Ibrahim Sobh 138 Dec 27, 2022
Machine Learning Course Project, IMDB movie review sentiment analysis by lstm, cnn, and transformer

IMDB Sentiment Analysis This is the final project of Machine Learning Courses in Huazhong University of Science and Technology, School of Artificial I

Daniel 0 Dec 27, 2021
Chinese Named Entity Recognization (BiLSTM with PyTorch)

BiLSTM-CRF for Name Entity Recognition PyTorch version A PyTorch implemention of Bi-LSTM-CRF model for Chinese Named Entity Recognition. 使用 PyTorch 实现

5 Jun 01, 2022
SimCSE: Simple Contrastive Learning of Sentence Embeddings

SimCSE: Simple Contrastive Learning of Sentence Embeddings This repository contains the code and pre-trained models for our paper SimCSE: Simple Contr

Princeton Natural Language Processing 2.5k Jan 07, 2023
A framework for evaluating Knowledge Graph Embedding Models in a fine-grained manner.

A framework for evaluating Knowledge Graph Embedding Models in a fine-grained manner.

NEC Laboratories Europe 13 Sep 08, 2022
Use Tensorflow2.7.0 Build OpenAI'GPT-2

TF2_GPT-2 Use Tensorflow2.7.0 Build OpenAI'GPT-2 使用最新tensorflow2.7.0构建openai官方的GPT-2 NLP模型 优点 使用无监督技术 拥有大量词汇量 可实现续写(堪比“xx梦续写”) 实现对话后续将应用于FloatTech的Bot

Watermelon 9 Sep 13, 2022
A curated list of efficient attention modules

awesome-fast-attention A curated list of efficient attention modules

Sepehr Sameni 891 Dec 22, 2022
Healthsea is a spaCy pipeline for analyzing user reviews of supplementary products for their effects on health.

Welcome to Healthsea ✨ Create better access to health with spaCy. Healthsea is a pipeline for analyzing user reviews to supplement products by extract

Explosion 75 Dec 19, 2022
Creating a chess engine using GPT-3

GPT3Chess Creating a chess engine using GPT-3 Code for my article : https://towardsdatascience.com/gpt-3-play-chess-d123a96096a9 My game (white) vs GP

19 Dec 17, 2022
This repository contains the code for EMNLP-2021 paper "Word-Level Coreference Resolution"

Word-Level Coreference Resolution This is a repository with the code to reproduce the experiments described in the paper of the same name, which was a

79 Dec 27, 2022
Train and use generative text models in a few lines of code.

blather Train and use generative text models in a few lines of code. To see blather in action check out the colab notebook! Installation Use the packa

Dan Carroll 16 Nov 07, 2022
Yodatranslator is a simple translator English to Yoda-language

yodatranslator Overview yodatranslator is a simple translator English to Yoda-language. Project is created for educational purposes. It is intended to

1 Nov 11, 2021
Official Stanford NLP Python Library for Many Human Languages

Official Stanford NLP Python Library for Many Human Languages

Stanford NLP 6.4k Jan 02, 2023
Library of deep learning models and datasets designed to make deep learning more accessible and accelerate ML research.

Tensor2Tensor Tensor2Tensor, or T2T for short, is a library of deep learning models and datasets designed to make deep learning more accessible and ac

12.9k Jan 07, 2023
Machine learning models from Singapore's NLP research community

SG-NLP Machine learning models from Singapore's natural language processing (NLP) research community. sgnlp is a Python package that allows you to eas

AI Singapore | AI Makerspace 21 Dec 17, 2022
profile tools for pytorch nn models

nnprof Introduction nnprof is a profile tool for pytorch neural networks. Features multi profile mode: nnprof support 4 profile mode: Layer level, Ope

Feng Wang 42 Jul 09, 2022
End-to-end MLOps pipeline of a BERT model for emotion classification.

image source EmoBERT-MLOps The goal of this repository is to build an end-to-end MLOps pipeline based on the MLOps course from Made with ML, but this

Dimitre Oliveira 4 Nov 06, 2022
KoBERT - Korean BERT pre-trained cased (KoBERT)

KoBERT KoBERT Korean BERT pre-trained cased (KoBERT) Why'?' Training Environment Requirements How to install How to use Using with PyTorch Using with

SK T-Brain 1k Jan 02, 2023
An Open-Source Package for Neural Relation Extraction (NRE)

OpenNRE We have a DEMO website (http://opennre.thunlp.ai/). Try it out! OpenNRE is an open-source and extensible toolkit that provides a unified frame

THUNLP 3.9k Jan 03, 2023
Unsupervised Language Modeling at scale for robust sentiment classification

** DEPRECATED ** This repo has been deprecated. Please visit Megatron-LM for our up to date Large-scale unsupervised pretraining and finetuning code.

NVIDIA Corporation 1k Nov 17, 2022