Zurück zum Ranking

Dobiasd/frugally-deep

C++

A lightweight header-only library for using Keras (TensorFlow) models in C++.

tensorflowdeep-learningkerascppcpp14header-onlylibraryc-plus-plusc-plus-plus-14convolutional-neural-networkspredictionmachine-learning
Sterne-Wachstum
Sterne
1.1k
Forks
237
Wochenwachstum
Issues
0
5001k
Jan. 2023März 2024Mai 2025Juli 2026
README

logo

CI (License MIT 1.0)

frugally-deep

Use Keras models in C++ with ease

Table of contents

Introduction

Would you like to build/train a model using Keras/Python? And would you like to run the prediction (forward pass) on your model in C++ without linking your application against TensorFlow? Then frugally-deep is exactly for you.

frugally-deep

  • is a small header-only library written in modern and pure C++.
  • is very easy to integrate and use.
  • depends only on FunctionalPlus, Eigen and json - also header-only libraries.
  • supports inference (model.predict) not only for sequential models but also for computational graphs with a more complex topology, created with the functional API.
  • re-implements a (small) subset of TensorFlow, i.e., the operations needed to support prediction.
  • results in a much smaller binary size than linking against TensorFlow.
  • works out-of-the-box also when compiled into a 32-bit executable. (Of course, 64 bit is fine too.)
  • avoids temporarily allocating (potentially large chunks of) additional RAM during convolutions (by not materializing the im2col input matrix).
  • utterly ignores even the most powerful GPU in your system and uses only one CPU core per prediction. ;-)
  • but is quite fast on one CPU core, and you can run multiple predictions in parallel, thus utilizing as many CPUs as you like to improve the overall prediction throughput of your application/pipeline.

Supported layer types

  • Add, Concatenate, Subtract, Multiply, Average, Maximum, Minimum, Dot
  • AveragePooling1D/2D/3D, GlobalAveragePooling1D/2D/3D
  • AdaptiveAveragePooling1D/2D/3D, AdaptiveMaxPooling1D/2D/3D
  • TimeDistributed
  • Conv1D/2D/3D, SeparableConv2D, DepthwiseConv1D, DepthwiseConv2D
  • Conv1DTranspose, Conv2DTranspose, Conv3DTranspose
  • Cropping1D/2D/3D, ZeroPadding1D/2D/3D, CenterCrop
  • BatchNormalization, Dense, EinsumDense, Flatten, Normalization
  • Dropout, AlphaDropout, GaussianDropout, GaussianNoise
  • SpatialDropout1D, SpatialDropout2D, SpatialDropout3D
  • ActivityRegularization, LayerNormalization, RMSNormalization
  • GroupNormalization, UnitNormalization
  • Training-only image augmentation layers (passed through at inference): RandomBrightness, RandomContrast, RandomCrop, RandomFlip, RandomHue, RandomGrayscale, RandomRotation, RandomTranslation, RandomZoom, RandomShear, RandomSaturation, RandomPerspective, AutoContrast, AugMix, CutMix, MixUp, RandAugment, Solarization, Equalization
  • MaxPooling1D/2D/3D, GlobalMaxPooling1D/2D/3D
  • UpSampling1D/2D/3D, Resizing, Rescaling
  • Reshape, Permute, RepeatVector
  • Embedding, CategoryEncoding
  • Discretization, IntegerLookup
  • Masking (passthrough at inference)
  • Attention, AdditiveAttention, MultiHeadAttention, GroupedQueryAttention
  • LSTM, GRU, SimpleRNN, Bidirectional
  • RNN wrapping LSTMCell/GRUCell/SimpleRNNCell/StackedRNNCells
  • ConvLSTM1D, ConvLSTM2D, ConvLSTM3D

Also supported

  • different activiations (celu, elu, exponential, gelu, hard_shrink, hard_sigmoid, hard_tanh, leaky_relu, leakyrelu, linear, log_sigmoid, log_softmax, prelu, relu, relu6, selu, shared_activation, sigmoid, silu, soft_shrink, softmax, softplus, softsign, sparse_plus, squareplus, swish, tanh, tanh_shrink, threshold)
  • multiple inputs and outputs
  • nested models
  • residual connections
  • shared layers
  • variable input shapes
  • arbitrary complex model architectures / computational graphs
  • custom layers (by passing custom factory functions to load_model)

Currently not supported are the following:

Lambda (why), Hashing, HashedCrossing, MelSpectrogram, STFTSpectrogram, StringLookup, TextVectorization, stateful recurrent layers, temporal models

Usage

  1. Use Keras/Python to build (model.compile(...)), train (model.fit(...)) and test (model.evaluate(...)) your model as usual. Then save it to a single file using model.save('....keras'). The image_data_format in your model must be channels_last, which is the default when using the TensorFlow backend. Models created with a different image_data_format and other backends are not supported.

  2. Now convert it to the frugally-deep file format with keras_export/convert_model.py

  3. Finally load it in C++ (fdeep::load_model(...)) and use model.predict(...) to invoke a forward pass with your data.

The following minimal example shows the full workflow:

# create_model.py
import numpy as np
from keras.layers import Input, Dense
from keras.models import Model

inputs = Input(shape=(4,))
x = Dense(5, activation='relu')(inputs)
predictions = Dense(3, activation='softmax')(x)
model = Model(inputs=inputs, outputs=predictions)
model.compile(loss='categorical_crossentropy', optimizer='nadam')

model.fit(
    np.asarray([[1, 2, 3, 4], [2, 3, 4, 5]]),
    np.asarray([[1, 0, 0], [0, 0, 1]]), epochs=10)

model.save('keras_model.keras')
python3 keras_export/convert_model.py keras_model.keras fdeep_model.json
// main.cpp
#include <fdeep/fdeep.hpp>
int main()
{
    const auto model = fdeep::load_model("fdeep_model.json");
    const auto result = model.predict(
        {fdeep::tensor(fdeep::tensor_shape(static_cast<std::size_t>(4)),
        std::vector<float>{1, 2, 3, 4})});
    std::cout << fdeep::show_tensors(result) << std::endl;
}

When using convert_model.py a test case (input and corresponding output values) is generated automatically and saved along with your model. fdeep::load_model runs this test to make sure the results of a forward pass in frugally-deep are the same as in Keras.

For more integration examples please have a look at the FAQ.

Requirements and Installation

  • A C++14-compatible compiler: Compilers from these versions on are fine: GCC 4.9, Clang 3.7 (libc++ 3.7) and Visual C++ 2015
  • Python 3.9 or higher
  • TensorFlow 2.21.0
  • Keras 3.14.0

(These are the tested versions, but somewhat older ones might work too.)

Guides for different ways to install frugally-deep can be found in INSTALL.md.

FAQ

See FAQ.md

Disclaimer

The API of this library still might change in the future. If you have any suggestions, find errors, or want to give general feedback/criticism, I'd love to hear from you. Of course, contributions are also very welcome.

License

Distributed under the MIT License. (See accompanying file LICENSE or at https://opensource.org/licenses/MIT)

Ähnliche Repositories
tensorflow/tensorflow

An Open Source Machine Learning Framework for Everyone

C++Apache License 2.0tensorflowmachine-learning
tensorflow.org
196.5k75.7k
keras-team/keras

Deep Learning for humans

PythonPyPIApache License 2.0deep-learningtensorflow
keras.io
64.2k19.7k
CorentinJ/Real-Time-Voice-Cloning

Clone a voice in 5 seconds to generate arbitrary speech in real-time

PythonPyPIOtherdeep-learningpytorch
60k9.4k
roboflow/supervision

We write your reusable computer vision tools. 💜

PythonPyPIMIT Licensecomputer-visionimage-processing
supervision.roboflow.com
48.3k4.4k
aymericdamien/TensorFlow-Examples

TensorFlow Tutorial and Examples for Beginners (support TF v1 & v2)

Jupyter NotebookOthertensorflowtutorial
43.7k14.7k
ray-project/ray

Ray is an AI compute engine. Ray consists of a core distributed runtime and a set of AI Libraries for accelerating ML workloads.

PythonPyPIApache License 2.0raydistributed
ray.io
43.3k7.8k
google-research/bert

TensorFlow code and pre-trained models for BERT

PythonPyPIApache License 2.0nlpgoogle
arxiv.org/abs/1810.04805
40.1k9.7k
photoprism/photoprism

AI-Powered Photos App 🌈💎✨

GoGo ModulesOthergolangtensorflow
photoprism.app
40k2.3k
blakeblackshear/frigate

NVR with realtime local object detection for IP cameras

TypeScriptnpmMIT Licensertsprealtime
frigate.video
34.5k3.4k
xitu/gold-miner

🥇掘金翻译计划,可能是世界最大最好的英译中技术社区,最懂读者和译者的翻译平台:

androidtranslation
juejin.cn/tag/%E6%8E%98%E9%87%91%E7%BF%BB%E8%AF%91%E8%AE%A1%E5%88%92
34.3k5k
lutzroeder/netron

Visualizer for neural network, deep learning and machine learning models

JavaScriptnpmMIT Licenseneural-networkdeep-learning
netron.app
33.3k3.2k
donnemartin/data-science-ipython-notebooks

Data science Python notebooks: Deep learning (TensorFlow, Theano, Caffe, Keras), scikit-learn, Kaggle, big data (Spark, Hadoop MapReduce, HDFS), matplotlib, pandas, NumPy, SciPy, Python essentials, AWS, and various command lines.

PythonPyPIOtherpythonmachine-learning
29.3k8k