ktrain

ktrain is a Python library that makes deep learning and AI more accessible and easier to apply

https://github.com/amaiya/ktrain

Science Score: 33.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: arxiv.org
  • Committers with academic emails
    1 of 17 committers (5.9%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (13.5%) to scientific vocabulary

Keywords

computer-vision deep-learning graph-neural-networks keras machine-learning nlp python tabular-data tensorflow
Last synced: 6 months ago · JSON representation

Repository

ktrain is a Python library that makes deep learning and AI more accessible and easier to apply

Basic Info
  • Host: GitHub
  • Owner: amaiya
  • License: apache-2.0
  • Language: Jupyter Notebook
  • Default Branch: master
  • Homepage:
  • Size: 108 MB
Statistics
  • Stars: 1,258
  • Watchers: 32
  • Forks: 265
  • Open Issues: 1
  • Releases: 170
Topics
computer-vision deep-learning graph-neural-networks keras machine-learning nlp python tabular-data tensorflow
Created about 7 years ago · Last pushed about 1 year ago
Metadata Files
Readme Changelog Contributing License

README.md

Overview | Tutorials | Examples | Installation | FAQ | API Docs | How to Cite

PyPI Status ktrain python compatibility license Downloads <!--Twitter URL-->

Welcome to ktrain

a "Swiss Army knife" for machine learning

News and Announcements

  • 2024-02-20

    - ktrain 0.41.x is released and removes the ktrain.text.qa.generative_qa module. Our OnPrem.LLM package should be used for Generative Question-Answering tasks. See example notebook.

Overview

ktrain is a lightweight wrapper for the deep learning library TensorFlow Keras (and other libraries) to help build, train, and deploy neural networks and other machine learning models. Inspired by ML framework extensions like fastai and ludwig, ktrain is designed to make deep learning and AI more accessible and easier to apply for both newcomers and experienced practitioners. With only a few lines of code, ktrain allows you to easily and quickly:

  • employ fast, accurate, and easy-to-use pre-canned models for text, vision, graph, and tabular data:

  • estimate an optimal learning rate for your model given your data using a Learning Rate Finder

  • utilize learning rate schedules such as the triangular policy, the 1cycle policy, and SGDR to effectively minimize loss and improve generalization

  • build text classifiers for any language (e.g., Arabic Sentiment Analysis with BERT, Chinese Sentiment Analysis with NBSVM)

  • easily train NER models for any language (e.g., Dutch NER )

  • load and preprocess text and image data from a variety of formats

  • inspect data points that were misclassified and provide explanations to help improve your model

  • leverage a simple prediction API for saving and deploying both models and data-preprocessing steps to make predictions on new raw data

  • built-in support for exporting models to ONNX and TensorFlow Lite (see example notebook for more information)

Tutorials

Please see the following tutorial notebooks for a guide on how to use ktrain on your projects: * Tutorial 1: Introduction * Tutorial 2: Tuning Learning Rates * Tutorial 3: Image Classification * Tutorial 4: Text Classification * Tutorial 5: Learning from Unlabeled Text Data * Tutorial 6: Text Sequence Tagging for Named Entity Recognition * Tutorial 7: Graph Node Classification with Graph Neural Networks * Tutorial 8: Tabular Classification and Regression * Tutorial A1: Additional tricks, which covers topics such as previewing data augmentation schemes, inspecting intermediate output of Keras models for debugging, setting global weight decay, and use of built-in and custom callbacks. * Tutorial A2: Explaining Predictions and Misclassifications * Tutorial A3: Text Classification with Hugging Face Transformers * Tutorial A4: Using Custom Data Formats and Models: Text Regression with Extra Regressors

Some blog tutorials and other guides about ktrain are shown below:

ktrain: A Lightweight Wrapper for Keras to Help Train Neural Networks

BERT Text Classification in 3 Lines of Code

Text Classification with Hugging Face Transformers in TensorFlow 2 (Without Tears)

Build an Open-Domain Question-Answering System With BERT in 3 Lines of Code

Finetuning BERT using ktrain for Disaster Tweets Classification by Hamiz Ahmed

Indonesian NLP Examples with ktrain by Sandy Khosasi

Examples

Using ktrain on Google Colab? See these Colab examples: - text classification: a simple demo of Multiclass Text Classification with BERT - text classification: a simple demo of Multiclass Text Classification with Hugging Face Transformers - sequence-tagging (NER): NER example using transformer word embeddings - question-answering: End-to-End Question-Answering using the 20newsgroups dataset. - image classification: image classification with Cats vs. Dogs

Tasks such as text classification and image classification can be accomplished easily with only a few lines of code.

Example: Text Classification of IMDb Movie Reviews Using BERT [see notebook]

```python import ktrain from ktrain import text as txt

load data

(xtrain, ytrain), (xtest, ytest), preproc = txt.textsfromfolder('data/aclImdb', maxlen=500, preprocessmode='bert', traintest_names=['train', 'test'], classes=['pos', 'neg'])

load model

model = txt.textclassifier('bert', (xtrain, y_train), preproc=preproc)

wrap model and data in ktrain.Learner object

learner = ktrain.getlearner(model, traindata=(xtrain, ytrain), valdata=(xtest, ytest), batchsize=6)

find good learning rate

learner.lrfind() # briefly simulate training to find good learning rate learner.lrplot() # visually identify best learning rate

train using 1cycle learning rate schedule for 3 epochs

learner.fit_onecycle(2e-5, 3) ```

Example: Classifying Images of Dogs and Cats Using a Pretrained ResNet50 model [see notebook]

```python import ktrain from ktrain import vision as vis

load data

(traindata, valdata, preproc) = vis.imagesfromfolder( datadir='data/dogscats', dataaug = vis.getdataaug(horizontalflip=True), traintestnames=['train', 'valid'], targetsize=(224,224), colormode='rgb')

load model

model = vis.imageclassifier('pretrainedresnet50', traindata, valdata, freeze_layers=80)

wrap model and data in ktrain.Learner object

learner = ktrain.getlearner(model=model, traindata=traindata, valdata=valdata, workers=8, usemultiprocessing=False, batch_size=64)

find good learning rate

learner.lrfind() # briefly simulate training to find good learning rate learner.lrplot() # visually identify best learning rate

train using triangular policy with ModelCheckpoint and implicit ReduceLROnPlateau and EarlyStopping

learner.autofit(1e-4, checkpointfolder='/tmp/savedweights') ```

Example: Sequence Labeling for Named Entity Recognition using a randomly initialized Bidirectional LSTM CRF model [see notebook]

```python import ktrain from ktrain import text as txt

load data

(trn, val, preproc) = txt.entitiesfromtxt('data/nerdataset.csv', sentencecolumn='Sentence #', wordcolumn='Word', tagcolumn='Tag', dataformat='gmb', usechar=True) # enable character embeddings

load model

model = txt.sequence_tagger('bilstm-crf', preproc)

wrap model and data in ktrain.Learner object

learner = ktrain.getlearner(model, traindata=trn, val_data=val)

conventional training for 1 epoch using a learning rate of 0.001 (Keras default for Adam optmizer)

learner.fit(1e-3, 1) ```

Example: Node Classification on Cora Citation Graph using a GraphSAGE model [see notbook]

```python import ktrain from ktrain import graph as gr

load data with supervision ratio of 10%

(trn, val, preproc) = gr.graphnodesfromcsv( 'cora.content', # node attributes/labels 'cora.cites', # edge list samplesize=20, holdoutpct=None, holdoutforinductive=False, trainpct=0.1, sep='\t')

load model

model=gr.graphnodeclassifier('graphsage', trn)

wrap model and data in ktrain.Learner object

learner = ktrain.getlearner(model, traindata=trn, valdata=val, batchsize=64)

find good learning rate

learner.lrfind(maxepochs=100) # briefly simulate training to find good learning rate learner.lr_plot() # visually identify best learning rate

train using triangular policy with ModelCheckpoint and implicit ReduceLROnPlateau and EarlyStopping

learner.autofit(0.01, checkpointfolder='/tmp/savedweights') ```

Example: Text Classification with Hugging Face Transformers on 20 Newsgroups Dataset Using DistilBERT [see notebook]

```python

load text data

categories = ['alt.atheism', 'soc.religion.christian','comp.graphics', 'sci.med'] from sklearn.datasets import fetch20newsgroups trainb = fetch20newsgroups(subset='train', categories=categories, shuffle=True) testb = fetch20newsgroups(subset='test',categories=categories, shuffle=True) (xtrain, ytrain) = (trainb.data, trainb.target) (xtest, ytest) = (testb.data, test_b.target)

build, train, and validate model (Transformer is wrapper around transformers library)

import ktrain from ktrain import text MODELNAME = 'distilbert-base-uncased' t = text.Transformer(MODELNAME, maxlen=500, classnames=trainb.targetnames) trn = t.preprocesstrain(xtrain, ytrain) val = t.preprocesstest(xtest, ytest) model = t.getclassifier() learner = ktrain.getlearner(model, traindata=trn, valdata=val, batchsize=6) learner.fitonecycle(5e-5, 4) learner.validate(classnames=t.getclasses()) # classnames must be string values

Output from learner.validate()

precision recall f1-score support

alt.atheism 0.92 0.93 0.93 319

comp.graphics 0.97 0.97 0.97 389

sci.med 0.97 0.95 0.96 396

soc.religion.christian 0.96 0.96 0.96 398

accuracy 0.96 1502

macro avg 0.95 0.96 0.95 1502

weighted avg 0.96 0.96 0.96 1502

```

Example: Tabular Classification for Titanic Survival Prediction Using an MLP [see notebook]

```python import ktrain from ktrain import tabular import pandas as pd traindf = pd.readcsv('train.csv', indexcol=0) traindf = traindf.drop(['Name', 'Ticket', 'Cabin'], 1) trn, val, preproc = tabular.tabularfromdf(traindf, labelcolumns=['Survived'], randomstate=42) learner = ktrain.getlearner(tabular.tabularclassifier('mlp', trn), traindata=trn, valdata=val) learner.lrfind(showplot=True, maxepochs=5) # estimate learning rate learner.fitonecycle(5e-3, 10)

evaluate held-out labeled test set

tst = preproc.preprocesstest(pd.readcsv('heldout.csv', indexcol=0)) learner.evaluate(tst, classnames=preproc.get_classes()) ```

Additional examples can be found here.

Installation

  1. Make sure pip is up-to-date with: pip install -U pip

  2. Install TensorFlow 2 if it is not already installed (e.g., pip install tensorflow).

  3. Install ktrain: pip install ktrain

  4. If using tensorflow>=2.16:

    • Install tf_keras: pip install tf_keras
    • Set the environment variable TF_USE_LEGACY_KERAS to true before importing ktrain

The above should be all you need on Linux systems and cloud computing environments like Google Colab and AWS EC2. If you are using ktrain on a Windows computer, you can follow these more detailed instructions that include some extra steps.

Notes about TensorFlow Versions

  • As of tensorflow>=2.11, you must only use legacy optimizers such as tf.keras.optimizers.legacy.Adam. The newer tf.keras.optimizers.Optimizer base class is not supported at this time. For instance, when using TensorFlow 2.11 and above, please use tf.keras.optimzers.legacy.Adam() instead of the string "adam" in model.compile. ktrain does this automatically when using out-of-the-box models (e.g., models from the transformers library).
  • As mentioned above, due to breaking changes in TensorFlow 2.16, you will need to install the tf_keras package and also set the environment variable TF_USE_LEGACY_KERAS=True before importing ktrain (e.g., add export TF_USE_LEGACY_KERAS=1 in .bashrc or add os.environ['TF_USE_LEGACY_KERAS']="1" at top of your code, etc.).

Additional Notes About Installation

  • Some optional, extra libraries used for some operations can be installed as needed. (Notice that ktrain is using forked versions of the eli5 and stellargraph libraries in order to support TensorFlow2.) python # for graph module: pip install https://github.com/amaiya/stellargraph/archive/refs/heads/no_tf_dep_082.zip # for text.TextPredictor.explain and vision.ImagePredictor.explain: pip install https://github.com/amaiya/eli5-tf/archive/refs/heads/master.zip # for tabular.TabularPredictor.explain: pip install shap # for text.zsl (ZeroShotClassifier), text.summarization, text.translation, text.speech: pip install torch # for text.speech: pip install librosa # for tabular.causal_inference_model: pip install causalnlp # for text.summarization.core.LexRankSummarizer: pip install sumy # for text.kw.KeywordExtractor pip install textblob # for text.generative_ai pip install onprem
  • ktrain purposely pins to a lower version of transformers to include support for older versions of TensorFlow. If you need a newer version of transformers, it is usually safe for you to upgrade transformers, as long as you do it after installing ktrain.

  • As of v0.30.x, TensorFlow installation is optional and only required if training neural networks. Although ktrain uses TensorFlow for neural network training, it also includes a variety of useful pretrained PyTorch models and sklearn models, which can be used out-of-the-box without having TensorFlow installed, as summarized in this table:

| Feature | TensorFlow | PyTorch | Sklearn | --- | :-: | :-: | :-: | | training any neural network (e.g., text or image classification) | ✅ | ❌ | ❌ | | End-to-End Question-Answering (pretrained) | ✅ | ✅ | ❌ | | QA-Based Information Extraction (pretrained) | ✅ | ✅ | ❌ | | Zero-Shot Classification (pretrained) | ❌ | ✅ | ❌ | | Language Translation (pretrained) | ❌ | ✅ | ❌ | | Summarization (pretrained) | ❌ | ✅ | ❌ | | Speech Transcription (pretrained) | ❌ | ✅ |❌ | | Image Captioning (pretrained) | ❌ | ✅ |❌ | | Object Detection (pretrained) | ❌ | ✅ |❌ | | Sentiment Analysis (pretrained) | ❌ | ✅ |❌ | | GenerativeAI (sentence-transformers) | ❌ | ✅ |❌ | | Topic Modeling (sklearn) | ❌ | ❌ | ✅ | | Keyphrase Extraction (textblob/nltk/sklearn) | ❌ | ❌ | ✅ |

As noted above, end-to-end question-answering and information extraction in ktrain can be used with either TensorFlow (using framework='tf') or PyTorch (using framework='pt').

How to Cite

Please cite the following paper when using ktrain: ``` @article{maiya2020ktrain, title={ktrain: A Low-Code Library for Augmented Machine Learning}, author={Arun S. Maiya}, year={2020}, eprint={2004.10703}, archivePrefix={arXiv}, primaryClass={cs.LG}, journal={arXiv preprint arXiv:2004.10703}, }

```


Creator: Arun S. Maiya

Email: arun [at] maiya [dot] net

Owner

  • Name: Arun S. Maiya
  • Login: amaiya
  • Kind: user

computer scientist

GitHub Events

Total
  • Issues event: 7
  • Watch event: 35
  • Issue comment event: 8
  • Push event: 1
  • Fork event: 3
Last Year
  • Issues event: 7
  • Watch event: 35
  • Issue comment event: 8
  • Push event: 1
  • Fork event: 3

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 2,607
  • Total Committers: 17
  • Avg Commits per committer: 153.353
  • Development Distribution Score (DDS): 0.013
Past Year
  • Commits: 21
  • Committers: 2
  • Avg Commits per committer: 10.5
  • Development Distribution Score (DDS): 0.048
Top Committers
Name Email Commits
Arun Maiya a****n@m****t 2,573
Sandy Khosasi 4****l 9
lambdaofgod b****a@g****m 4
Niek van der Plas N****1@g****m 3
TextProbe t****m@g****m 3
Andrey Lutich l****h@g****m 2
Jeff Graham j****9@g****m 2
Xing Zeng 4****g 2
Dan Alberto Rosa De Jesús d****a@m****u 1
00001H P****H@g****m 1
Cong c****v@g****m 1
Dale Visser d****r@i****g 1
Sanidhya Pratap Singh s****5@g****m 1
Timo Mulder t****r@g****m 1
hunaidkhan2000 3****0 1
logeshb l****b@s****m 1
nrhodes n****l@p****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 135
  • Total pull requests: 12
  • Average time to close issues: 15 days
  • Average time to close pull requests: 4 months
  • Total issue authors: 72
  • Total pull request authors: 8
  • Average comments per issue: 2.55
  • Average comments per pull request: 1.42
  • Merged pull requests: 10
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 5
  • Pull requests: 0
  • Average time to close issues: 11 days
  • Average time to close pull requests: N/A
  • Issue authors: 3
  • Pull request authors: 0
  • Average comments per issue: 0.8
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • amaiya (25)
  • dummynov1 (7)
  • Steven-Palayew (5)
  • evilying (5)
  • nburner96 (4)
  • mcormick123 (3)
  • nhansendev (3)
  • daniel-satria (3)
  • semprepisfo (3)
  • realonbebeto (2)
  • amir1m (2)
  • akald (2)
  • Nesarul-Hoque (2)
  • glane2609 (2)
  • WAEDwaed (2)
Pull Request Authors
  • ilos-vigil (4)
  • Niekvdplas (2)
  • dwvisser (2)
  • hunaidkhan2000 (1)
  • WangHexie (1)
  • solalatus (1)
  • 00001H (1)
  • amaiya (1)
Top Labels
Issue Labels
user question (58) bug (17) enhancement (6) invalid (1)
Pull Request Labels

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 2,933 last-month
  • Total docker downloads: 58
  • Total dependent packages: 0
  • Total dependent repositories: 83
  • Total versions: 210
  • Total maintainers: 1
pypi.org: ktrain

ktrain is a wrapper for TensorFlow Keras that makes deep learning and AI more accessible and easier to apply

  • Versions: 210
  • Dependent Packages: 0
  • Dependent Repositories: 83
  • Downloads: 2,933 Last month
  • Docker Downloads: 58
Rankings
Dependent repos count: 1.6%
Stargazers count: 1.9%
Downloads: 2.1%
Forks count: 3.2%
Average: 3.9%
Docker downloads count: 4.3%
Dependent packages count: 10.1%
Maintainers (1)
Last synced: 6 months ago

Dependencies

.github/workflows/ci.yml actions
  • actions/checkout v2 composite
  • actions/setup-python v2 composite
  • psf/black stable composite
setup.py pypi
  • NOTE *
  • cchardet *
  • chardet *
  • fastprogress *
  • jieba *
  • joblib *
  • keras_bert >=0.86.0
  • langdetect *
  • matplotlib *
  • packaging *
  • pandas *
  • requests *
  • scikit-learn *
  • sentencepiece *
  • syntok >1.3.3
  • transformers >=4.17.0
  • whoosh *