Skip to main content

ClassiTransformers

ClassiTransformers is an abstract library based on Tensorflow implementation of BERT and ELECTRA, and transformers library of HuggingFace Inc.

Currently implemented models

  • BERT (Tensorflow)
  • ELECTRA (Tensorflow)
  • RoBERTa (PyTorch - transformers library)
  • ALBERT (PyTorch - transformers library)
  • DistilBERT (PyTorch - transformers library)

Task

  • Sequence Classification

Features

  • Works for N-class classification problem where N is any number of classes.
  • Easy to use. Takes away all the complexity of writing tensorflow or pytorch codes for training and testing classification models.
  • It provides an methods to easily train, test and create deployable models in .pb and .bin format in just 5 steps.
  • Hyperparameters can be easily modified without having to change the source code.

Table of contents

Installation

Assuming that anaconda environment is already installed,

  • with requirements.txt
pip install -r requirements.txt
  • with yml file, create conda environment
conda env create -f environment.yml
source activate env

Usage

Example notebooks can be found in the sample_notebooks directory.

Structure

  • classitransformers.pytransformers - Includes all pytorch-based text classification models from transformers library.
  • classitransformers.tfelectra - Includes tensorflow-based Electra model for text classification
  • classitransformers.tfbert - Includes tensorflow-based BERT model for text classification
  • classitransformers.report - Used for reporting performance metrics. (precision, recall, F1, confusion matric)
  • classitransformers.configs - Used for initializing the hyperparameters of the language models. Also checkas and creates the necessary directories.
  • classitransformers.downloader - Used for downloading any of the 5 language models.

Qucik Start

Supports text classification with any number of labels.

from classitransformers.report import metrics
from classitransformers.configs import Configs
from classitransformers.tfelectra import ElectraClassification

config = Configs(pretrained_model_dir = './models/Electra_base/',
              model_name='electra',
              num_train_epochs=3, 
              train_batch_size = 16,
              eval_batch_size = 8, 
              do_train = True, 
              do_eval = True, 
              label_list = ["0", "1", "2", "3", "4"],
              max_seq_length = 256,
              data_dir = "./datasets/bbcsports/", 
              output_dir = "./electra_output_sports/")

model = ElectraClassification(config) 

model.train()
prediction = model.test()

y_pred = [np.argmax(tup) for tup in prediction]
print(y_pred)

Data Preparation

The directory for input files needs to be specified while creating the config object. The files should be named train.csv, dev.csv, test.csv .test.csv may or may not have the labels. Labels would be useful forgenerating the report after testing.

Please check data_preparation_format.txt for details.

Setting Configuration

All the Hyperparameters are listed in the Configs class, and have standard default values. The values can be changed by modifying the parameters passed in the Configs constructor for config object.

class Configs(object):
  """Fine-tuning hyperparameters."""

    def __init__(self, pretrained_model_dir = './Albert',
              data_dir = "./data/", output_dir = "./albert_output/",
              export_dir = None, model_name="albert", 
              model_size ="base", learning_rate = 5e-5, 
              num_train_epochs=3.0, train_batch_size = 16,
              eval_batch_size = 8, predict_batch_size = 8, do_train = True,
              do_eval = True, do_predict = False, label_list = ["0", "1"],
              do_lower_case = True, max_seq_length = 256, use_tpu = False,
              iterations_per_loop = 1000, save_checkpoint_steps = 1000000,
              warmup_proportion = 0.1, export_path ='./exported_bert_model')

These are the parameters to be specified for creating the config object of Configs class.

Args:

  • pretrained_model_dir : The path for pretrained directory.
  • data_dir : The path of the directory for the train,dev and test files.
  • output_dir (optional): The directory where the fine-tuned model will be saved. If not given, model will be saved in the current directory.(checkpoint for TF, .bin for pytorch)
  • export_dir (optional): The directory where the model to be deployed will be saved.(Currently only for BERT)
  • model_name : The name of the model. Either of these: 'albert', 'bert', 'electra', 'roberta', 'distilbert'
  • learning_rate: The learning rate required while training the model. Default is 5e-5.
  • num_training_epochs: The number of iterations for finetuning the pretrained model for classification task.
  • label_list: The list of the labels for text classification task.
  • max_seq_length: Max Sequence Length (multiples of 2) should be ideally just greater than the length of the longest text sentence, to prevent loss of information.
  • export_path: The export path directory where chkpt format is converted to .pb format. Only set for bert.

Class Methods

The class methods do not take any parameters. All the parameters are predefined to improve the clarity of the code.

train() Fine-Tunes(trains) the model and saves the model and config file in the output_dir directory. Validation is done after each epoch.

test() Tests the model for test dataset. Returns the prediction labels.

export_model() Exports checkpoint model to .pb fotmat. Used for tensorflow-serviing while inferencing.(Currently only for BERT)

inference() Inference on any input csv in batches using tensorflow serving for .pb model. (Currently only for BERT)

text_inference() Inference on list of sentences as input.

report() Prints and returns the accuracy and other metrics. Also prints Confusion Matrix (decorated matrix using matplotlib)

Getting Language Models.

from classitransformers import downloader

# pass name of the model ('albert', 'bert', 'electra', 'roberta', 'distilbert')
downloader('roberta') # Downloads to default dir '../models'

Real Dataset Examples

Support and Contributions

Please submit bug reports and feature requests as Issues. Contributions are very welcome.

For additional questions and feedback, please contact us at classitransformers@fmr.com

Acknowledgement

ClassiTransformers is developed by Emerging Tech Team at Fidelity Investments. The part of the package was developed as part of an internship program at Fidelity. We thank Hrushikesh and Mayank for their contribution to the package.

License

ClassiTransformers is licensed under the Apache License 2.0.

Metadata

Release files for classitransformers 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for classitransformers 0.0.1
File Size Uploaded Provenance
classitransformers-0.0.1.tar.gz 44.8 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for classitransformers 0.0.1
File Interpreter ABI Platform
classitransformers-0.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 96.6 kB

Release files / classitransformers-0.0.1.tar.gz

Download URL classitransformers-0.0.1.tar.gz
Size 44.8 kB
Tags Source
SHA-256 checksum
How to use checksums
f6df7fa4c99b4ae559c2d8ed968addaf65097865c11be6bd412e6881e98e52e6
BLAKE2b-256 checksum
How to use checksums
19f00018b1042e119d857d20851419015ff44c3b3664bb20c5b4aeab0f2683c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.48.0 CPython/3.7.4

Release files / classitransformers-0.0.1-py3-none-any.whl

Download URL classitransformers-0.0.1-py3-none-any.whl
Size 51.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
42d38440b5478333cfc325e82b001f4fd4a488ac16616780c4048a7e932521a8
BLAKE2b-256 checksum
How to use checksums
b70de155e863d9b4ab18fc2ae6f1940eb60e08f2b56e2804ea8a3b5b0e532abf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.48.0 CPython/3.7.4

Security for classitransformers 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page