• Stars
    star
    183
  • Rank 210,154 (Top 5 %)
  • Language
    C++
  • License
    MIT License
  • Created about 6 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

it's a small library for running trained Keras 2 models from a native C++ code.

Keras2cpp release lisense Build Status

keras2cpp

Keras2cpp is a small library for running trained Keras models from a C++ application without any dependences.

Design goals:

  • Compatibility with networks generated by Keras using TensorFlow backend.
  • CPU only, no GPU.
  • No external dependencies, standard library, C++17.
  • Model stored on disk in binary format and can be quickly read.
  • Model stored in memory in contiguous block for better cache performance.

Not not layer and activation types are supported yet. Work in progress

Supported Keras layers:

  • Dense
  • Convolution1D
  • Convolution2D
  • Convolution3D
  • Flatten
  • ELU
  • Activation
  • MaxPooling2D
  • Embedding
  • LocallyConnected1D
  • LocallyConnected2D
  • LSTM
  • GRU
  • CNN
  • BatchNormalization

Supported activation:

  • linear
  • relu
  • softplus
  • tanh
  • sigmoid
  • hard_sigmoid
  • elu
  • softsign
  • softmax

Other tasks:

  • Create unit tests
  • Create Makefile
  • Code refactoring (in progress)

The project is compatible with Keras 2.x (all versions) and Python 3.x

Example

python_model.py:

import numpy as np
from keras import Sequential
from keras.layers import Dense

#create random data
test_x = np.random.rand(10, 10).astype('f')
test_y = np.random.rand(10).astype('f')
model = Sequential([
    Dense(1, input_dim=10)
])
model.compile(loss='mse', optimizer='adam')

#train model by 1 iteration
model.fit(test_x, test_y, epochs=1, verbose=False)

#predict
data = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
prediction = model.predict(data)
print(prediction)

#save model
from keras2cpp import export_model
export_model(model, 'example.model')

cpp_model.cc:

#include "src/model.h"

using keras2cpp::Model;
using keras2cpp::Tensor;

int main() {
    // Initialize model.
    auto model = Model::load("example.model");

    // Create a 1D Tensor on length 10 for input data.
    Tensor in{10};
    in.data_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    // Run prediction.
    Tensor out = model(in);
    out.print();
    return 0;
}

How to build and run

Tested with Keras 2.2.1, Python 3.6

$ git clone https://github.com/gosha20777/keras2cpp.git
$ cd keras2cpp
$ mkdir build && cd build
$ python3 ../python_model.py
[[-1.85735667]]

$ cmake ..
$ cmake --build .
$ ./keras2cpp
[ -1.857357 ]

License

MIT

Similar projects

I found another similar projects on Github:

But It works only with Keras 1 and didn’t work for me. That's why I wrote my own implementation.

More Repositories

1

NoteShrink

This script makes scans and handwritten notes more beautiful! The script clears synopses and scans from "dirt", improves their readability and reduces the size of the image.
C#
21
star
2

rawformer

Unpaired Raw-to-Raw Translation for Learnable Camera ISPs
Python
19
star
3

TelegramAspMvcDotNetCoreBotExample

A simpe example of telegramm bot on MVC ASP.NET Core 2.0
C#
11
star
4

Venus.AI

It tis a powerfuul open source AI freamwork like Dialog Flow, LUIS. It contains Web API, Telegram Bot Client and Console Bot client.
C#
7
star
5

yandex2ytmusic

Transfer playlists from yandex.music to youtube music
Python
7
star
6

smev-signer

sign algoritm for smev3
Java
6
star
7

MAI

Конспекты лекций МАИ по некоторым предметам
Jupyter Notebook
4
star
8

ml_course

Курс по машинному обучению и Глубокому обучению с подборкой материалов и конспектов.
Jupyter Notebook
3
star
9

NeuroExploit

A self-learning neural network for automatic pentest
3
star
10

gosha20777.github.io

SCSS
3
star
11

yolo-v3-keras

Keras implimettation of YOLOv3
Python
3
star
12

qr-generator

qr code generator
Python
2
star
13

neuro-inverse-kinematic

A simple inverse kinematic model for UE4
Jupyter Notebook
2
star
14

IFMO

The materials and homeworks for IFMO
Java
2
star
15

ueye-python

A python wrapper for uEye IDS api
Python
2
star
16

bachelor-diploma

Выпускная квалификационная работа (ВКР) бакалавра в LaTeX, оформленная в соответствии с нормоконтролем Московского Авиационного Интитута (МАИ) в 2021 г.
TeX
2
star
17

far_by_gosha20777

far build for win 64
Lua
1
star
18

fastapi-graphql

GraphQL integration on FastAPI
1
star
19

nextcloud-compose

nextcloud-compose
1
star
20

SystemInfoBot

BotWhitchSentSystemInfo
C#
1
star
21

aikek

generate fake news about ML
Jupyter Notebook
1
star
22

python-with-anime

Учим питончику 🐍 с Аниме
1
star
23

CSharpCourse

Образовательный курс по языку C# и парадигмам программирования
C#
1
star
24

EyeDetector

The program for MIPT
1
star
25

ya-profi-2021

Jupyter Notebook
1
star
26

few-shot-isp-domain-adaptation

A new method for few-shot domain adaptation of RAW-to-RGB neural image signal processing (ISP) pipelines.
Jupyter Notebook
1
star