Top Related Projects
Useful extra functionality for TensorFlow 2.x maintained by SIG-addons
Deep Learning for humans
Tensors and Dynamic neural networks in Python with strong GPU acceleration
scikit-learn: machine learning in Python
The fastai deep learning library
🤗 Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.
Quick Overview
Keras-contrib is a community-driven extension to the Keras deep learning library. It provides additional layers, optimizers, and other components that are not part of the core Keras package but are useful for various deep learning tasks. This repository serves as a testing ground for new features before they potentially get integrated into the main Keras library.
Pros
- Offers additional functionality not found in the core Keras library
- Community-driven, allowing for rapid development and experimentation
- Provides a platform for testing new features before integration into Keras
- Compatible with both TensorFlow and Theano backends
Cons
- May have less stability compared to the core Keras library
- Documentation can be less comprehensive than the main Keras documentation
- Some components may become outdated or incompatible as Keras evolves
- Requires separate installation and maintenance from the main Keras package
Code Examples
- Using a custom layer from keras-contrib:
from keras_contrib.layers import CRF
model = Sequential()
model.add(Embedding(max_features, 128, input_length=maxlen))
model.add(Bidirectional(LSTM(64, return_sequences=True)))
model.add(CRF(num_classes))
- Implementing a custom loss function:
from keras_contrib.losses import crf_loss
model.compile(optimizer='adam', loss=crf_loss, metrics=['accuracy'])
- Using a custom optimizer:
from keras_contrib.optimizers import FTML
model.compile(optimizer=FTML(), loss='categorical_crossentropy', metrics=['accuracy'])
Getting Started
To get started with keras-contrib, follow these steps:
- Install keras-contrib:
pip install git+https://www.github.com/keras-team/keras-contrib.git
- Import and use keras-contrib components in your Keras projects:
from keras_contrib.layers import CRF
from keras_contrib.losses import crf_loss
from keras_contrib.optimizers import FTML
# Use these components in your Keras model as needed
Remember to check the keras-contrib documentation and GitHub repository for the most up-to-date information on available components and usage instructions.
Competitor Comparisons
Useful extra functionality for TensorFlow 2.x maintained by SIG-addons
Pros of TensorFlow Addons
- More actively maintained with frequent updates
- Broader scope, covering various TensorFlow extensions beyond just Keras
- Better integration with TensorFlow ecosystem
Cons of TensorFlow Addons
- Steeper learning curve due to lower-level TensorFlow API
- May require more code to achieve the same functionality as Keras-Contrib
Code Comparison
Keras-Contrib (CRF layer):
from keras_contrib.layers import CRF
model.add(CRF(num_tags))
TensorFlow Addons (CRF layer):
import tensorflow_addons as tfa
crf = tfa.text.crf_layer.CRF(num_tags)
outputs = crf(inputs)
Summary
TensorFlow Addons offers a wider range of features and better integration with the TensorFlow ecosystem, making it suitable for advanced users and complex projects. Keras-Contrib, on the other hand, provides a simpler API that's easier to use for those familiar with Keras. The choice between the two depends on the specific project requirements and the developer's familiarity with TensorFlow and Keras.
Deep Learning for humans
Pros of Keras
- Official, stable, and well-maintained repository
- Comprehensive documentation and extensive community support
- Seamless integration with TensorFlow backend
Cons of Keras
- Limited to core functionality and standard layers
- Slower to incorporate experimental or cutting-edge features
- Stricter contribution guidelines and longer review process
Code Comparison
Keras:
from keras.layers import Dense, LSTM
from keras.models import Sequential
model = Sequential([
LSTM(64, input_shape=(None, 28)),
Dense(10, activation='softmax')
])
Keras-contrib:
from keras.models import Sequential
from keras_contrib.layers import CRF
model = Sequential([
# ... other layers ...
CRF(10, sparse_target=True)
])
Key Differences
- Keras focuses on stable, widely-used components
- Keras-contrib allows for experimental features and community contributions
- Keras-contrib provides additional layers and functionalities not found in core Keras
- Keras has stricter testing and documentation requirements
- Keras-contrib offers faster integration of new ideas but may have less stability
Tensors and Dynamic neural networks in Python with strong GPU acceleration
Pros of PyTorch
- More flexible and dynamic computational graph
- Better support for debugging and introspection
- Stronger community and ecosystem for research and production
Cons of PyTorch
- Steeper learning curve for beginners
- Less built-in high-level APIs compared to Keras
- Slightly more verbose code for simple models
Code Comparison
Keras-contrib (using Keras backend):
from keras.models import Sequential
from keras.layers import Dense
model = Sequential([
Dense(64, activation='relu', input_shape=(32,)),
Dense(10, activation='softmax')
])
PyTorch:
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(32, 64),
nn.ReLU(),
nn.Linear(64, 10),
nn.Softmax(dim=1)
)
def forward(self, x):
return self.layers(x)
model = SimpleModel()
The PyTorch code is slightly more verbose but offers more flexibility in defining custom architectures and behavior.
scikit-learn: machine learning in Python
Pros of scikit-learn
- Comprehensive library for traditional machine learning algorithms
- Extensive documentation and community support
- Seamless integration with other scientific Python libraries
Cons of scikit-learn
- Limited support for deep learning and neural networks
- Less flexibility for custom model architectures
Code Comparison
scikit-learn:
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
keras-contrib:
from keras.models import Sequential
from keras.layers import Dense
from keras_contrib.layers import CRF
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(100,)))
model.add(CRF(10))
model.compile(optimizer='adam', loss=crf_loss, metrics=[crf_accuracy])
scikit-learn focuses on traditional machine learning algorithms with a simple API, while keras-contrib extends Keras for deep learning with additional layers and functionalities. scikit-learn is more suitable for classical ML tasks, whereas keras-contrib is better for complex neural network architectures and custom deep learning models.
The fastai deep learning library
Pros of fastai
- More comprehensive library with end-to-end deep learning capabilities
- Includes high-level APIs and built-in best practices for rapid development
- Active community and regular updates
Cons of fastai
- Steeper learning curve for beginners
- Less flexibility compared to lower-level frameworks
- Primarily focused on PyTorch, limiting integration with other backends
Code Comparison
fastai:
from fastai.vision.all import *
path = untar_data(URLs.PETS)
dls = ImageDataLoaders.from_folder(path, valid_pct=0.2, size=224)
learn = cnn_learner(dls, resnet34, metrics=error_rate)
learn.fine_tune(1)
keras-contrib:
from keras.models import Sequential
from keras.layers import Dense
from keras_contrib.layers import CRF
model = Sequential()
model.add(Dense(100, input_shape=(10,)))
model.add(CRF(10, sparse_target=True))
The fastai example demonstrates a complete workflow for image classification, while the keras-contrib example shows the addition of a custom layer to a Keras model.
🤗 Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.
Pros of transformers
- Extensive library of pre-trained models for various NLP tasks
- Active development and frequent updates
- Comprehensive documentation and community support
Cons of transformers
- Steeper learning curve for beginners
- Larger library size and potential overhead
- More focused on NLP tasks, less versatile for general deep learning
Code comparison
transformers:
from transformers import BertTokenizer, BertModel
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
outputs = model(**inputs)
keras-contrib:
from keras_contrib.layers import CRF
from keras.models import Sequential
model = Sequential()
model.add(CRF(10, sparse_target=True))
model.compile(optimizer='rmsprop', loss=crf_loss, metrics=[crf_accuracy])
The transformers library provides easy access to pre-trained models and tokenizers, while keras-contrib focuses on additional layers and utilities for Keras. transformers is more specialized for NLP tasks, whereas keras-contrib offers a broader range of components for various deep learning applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
keras-contrib : Keras community contributions
Keras-contrib is deprecated. Use TensorFlow Addons.
The future of Keras-contrib:
We're migrating to tensorflow/addons. See the announcement here.
This library is the official extension repository for the python deep learning library Keras. It contains additional layers, activations, loss functions, optimizers, etc. which are not yet available within Keras itself. All of these additional modules can be used in conjunction with core Keras models and modules.
As the community contributions in Keras-Contrib are tested, used, validated, and their utility proven, they may be integrated into the Keras core repository. In the interest of keeping Keras succinct, clean, and powerfully simple, only the most useful contributions make it into Keras. This contribution repository is both the proving ground for new functionality, and the archive for functionality that (while useful) may not fit well into the Keras paradigm.
Installation
Install keras_contrib for keras-team/keras
For instructions on how to install Keras, see the Keras installation page.
git clone https://www.github.com/keras-team/keras-contrib.git
cd keras-contrib
python setup.py install
Alternatively, using pip:
sudo pip install git+https://www.github.com/keras-team/keras-contrib.git
to uninstall:
pip uninstall keras_contrib
Install keras_contrib for tensorflow.keras
git clone https://www.github.com/keras-team/keras-contrib.git
cd keras-contrib
python convert_to_tf_keras.py
USE_TF_KERAS=1 python setup.py install
to uninstall:
pip uninstall tf_keras_contrib
For contributor guidelines see CONTRIBUTING.md
Example Usage
Modules from the Keras-Contrib library are used in the same way as modules within Keras itself.
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
# I wish Keras had the Parametric Exponential Linear activation..
# Oh, wait..!
from keras_contrib.layers.advanced_activations import PELU
# Create the Keras model, including the PELU advanced activation
model = Sequential()
model.add(Dense(100, input_shape=(10,)))
model.add(PELU())
# Compile and fit on random data
model.compile(loss='mse', optimizer='adam')
model.fit(x=np.random.random((100, 10)), y=np.random.random((100, 100)), epochs=5, verbose=0)
# Save our model
model.save('example.h5')
A Common "Gotcha"
As Keras-Contrib is external to the Keras core, loading a model requires a bit more work. While a pure Keras model is loadable with nothing more than an import of keras.models.load_model
, a model which contains a contributed module requires an additional import of keras_contrib
:
# Required, as usual
from keras.models import load_model
# Recommended method; requires knowledge of the underlying architecture of the model
from keras_contrib.layers import PELU
from keras_contrib.layers import GroupNormalization
# Load our model
custom_objects = {'PELU': PELU, 'GroupNormalization': GroupNormalization}
model = load_model('example.h5', custom_objects)
Top Related Projects
Useful extra functionality for TensorFlow 2.x maintained by SIG-addons
Deep Learning for humans
Tensors and Dynamic neural networks in Python with strong GPU acceleration
scikit-learn: machine learning in Python
The fastai deep learning library
🤗 Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot