• Stars
    star
    594
  • Rank 75,329 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Keras.NET is a high-level neural networks API for C# and F#, with Python Binding and capable of running on top of TensorFlow, CNTK, or Theano.

Logo

Keras.NET is a high-level neural networks API for C# and F# via a Python binding and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation. Being able to go from idea to result with the least possible delay is key to doing good research.

Use Keras if you need a deep learning library that:

  • Allows for easy and fast prototyping (through user friendliness, modularity, and extensibility).

  • Supports both convolutional networks and recurrent networks, as well as combinations of the two.

  • Runs seamlessly on CPU and GPU.

Keras.NET is using:

Prerequisite

  • Python 3.7 or 3.8, Link: https://www.python.org/downloads/

  • Install keras, numpy and one of the backends (Tensorflow/CNTK/Theano). Keras is now bundled with Tensorflow 2.0, so the easiest way to install Keras and Tensorflow at the same time is to simply install Tensorflow 2.0.

Nuget

Install from nuget: https://www.nuget.org/packages/Keras.NET

dotnet add package Keras.NET

Example with XOR sample (C#)

//Load train data
NDarray x = np.array(new float[,] { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } });
NDarray y = np.array(new float[] { 0, 1, 1, 0 });

//Build sequential model
var model = new Sequential();
model.Add(new Dense(32, activation: "relu", input_shape: new Shape(2)));
model.Add(new Dense(64, activation: "relu"));
model.Add(new Dense(1, activation: "sigmoid"));

//Compile and train
model.Compile(optimizer:"sgd", loss:"binary_crossentropy", metrics: new string[] { "accuracy" });
model.Fit(x, y, batch_size: 2, epochs: 1000, verbose: 1);

//Save model and weights
string json = model.ToJson();
File.WriteAllText("model.json", json);
model.SaveWeight("model.h5");

//Load model and weight
var loaded_model = Sequential.ModelFromJson(File.ReadAllText("model.json"));
loaded_model.LoadWeight("model.h5");

Output:

MNIST CNN Example (C#)

Python example taken from: https://keras.io/examples/mnist_cnn/

int batch_size = 128;
int num_classes = 10;
int epochs = 12;

// input image dimensions
int img_rows = 28, img_cols = 28;

Shape input_shape = null;

// the data, split between train and test sets
var ((x_train, y_train), (x_test, y_test)) = MNIST.LoadData();

if(Backend.ImageDataFormat() == "channels_first")
{
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols);
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols);
    input_shape = (1, img_rows, img_cols);
}
else
{
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1);
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1);
    input_shape = (img_rows, img_cols, 1);
}

x_train = x_train.astype(np.float32);
x_test = x_test.astype(np.float32);
x_train /= 255;
x_test /= 255;
Console.WriteLine($"x_train shape: {x_train.shape}");
Console.WriteLine($"{x_train.shape[0]} train samples");
Console.WriteLine($"{x_test.shape[0]} test samples");

// convert class vectors to binary class matrices
y_train = Util.ToCategorical(y_train, num_classes);
y_test = Util.ToCategorical(y_test, num_classes);

// Build CNN model
var model = new Sequential();
model.Add(new Conv2D(32, kernel_size: (3, 3).ToTuple(),
                        activation: "relu",
                        input_shape: input_shape));
model.Add(new Conv2D(64, (3, 3).ToTuple(), activation: "relu"));
model.Add(new MaxPooling2D(pool_size: (2, 2).ToTuple()));
model.Add(new Dropout(0.25));
model.Add(new Flatten());
model.Add(new Dense(128, activation: "relu"));
model.Add(new Dropout(0.5));
model.Add(new Dense(num_classes, activation: "softmax"));

model.Compile(loss: "categorical_crossentropy",
    optimizer: new Adadelta(), metrics: new string[] { "accuracy" });

model.Fit(x_train, y_train,
            batch_size: batch_size,
            epochs: epochs,
            verbose: 1,
            validation_data: new NDarray[] { x_test, y_test });
var score = model.Evaluate(x_test, y_test, verbose: 0);
Console.WriteLine($"Test loss: {score[0]}");
Console.WriteLine($"Test accuracy: {score[1]}");

Output

Reached 98% accuracy within 3 epoches.

Documentation

https://scisharp.github.io/Keras.NET/

SciSharp

More Repositories

1

TensorFlow.NET

.NET Standard bindings for Google's TensorFlow for developing, training and deploying Machine Learning models in C# and F#.
C#
3,224
star
2

LLamaSharp

A C#/.NET library to run LLM (πŸ¦™LLaMA/LLaVA) on your local device efficiently.
C#
2,508
star
3

BotSharp

The AI Agent Framework in .NET
C#
2,166
star
4

NumSharp

High Performance Computation for N-D Tensors in .NET, similar API to NumPy.
C#
1,362
star
5

Numpy.NET

C#/F# bindings for NumPy - a fundamental library for scientific computing, machine learning and AI
C#
685
star
6

Pandas.NET

Pandas port for C# and F#, data analysis tool, process multi-dim array in DataFrame.
C#
569
star
7

SiaNet

An easy to use C# deep learning library with CUDA/OpenCL support
C#
380
star
8

SciSharp-Stack-Examples

Practical examples written in SciSharp's machine learning libraries
C#
318
star
9

SharpCV

A Computer Vision library for C# and F# that combines OpenCV and NDArray together in .NET Standard.
C#
292
star
10

Torch.NET

.NET bindings for PyTorch. Machine Learning with C# / F# with Multi-GPU/CPU support
C#
276
star
11

Gym.NET

openai/gym's popular toolkit for developing and comparing reinforcement learning algorithms port to C#.
C#
120
star
12

CherubNLP

Natural Language Processing in .NET Core
C#
114
star
13

SciSharp

SciSharp STACK is focused on building tools for Machine Learning development.
Vue
105
star
14

SciSharpCube

Quickly experience all the latest features of SciSharp Machine Learning tools in docker container.
Jupyter Notebook
95
star
15

BotSharp-UI

Build, test and manage your AI Agents in the central place.
SCSS
82
star
16

ICSharpCore

Jupyter kernel in C# .NET Core which is the standard interface for SciSharp STACK.
C#
76
star
17

Plot.NET

.NET wrapper of plotly.js for ICSharpCore
C#
63
star
18

Bigtree.Algorithm

Machine Learning algorithm library in .NET Core
C#
62
star
19

Tensor.NET

A lightweight and high-performance tensor library which provides numpy-like operations but .NET style interfaces. It supports generic tensor, Linq, C# native slices and so on. (Qushui student project))
C#
59
star
20

Matplotlib.Net

.NET wrapper for the Python plotting library Matplotlib
C#
53
star
21

dotnet-mysql-replication

C# Implementation of MySQL replication client
C#
49
star
22

scikit-learn.net

Machine Learning in .NET Core.
C#
39
star
23

CodeMinion

A code generator framework capable of auto-generating the APIs of several SciSharp libraries.
C#
34
star
24

OpenAIGym.NET

A toolkit for developing and comparing reinforcement learning algorithms.
C#
27
star
25

Ludwig.NET

Ludwig is a toolbox that allows to train and test deep learning models without the need to write code.
C#
26
star
26

SciSharp.Models

Image Classification, Time Series, Transformer, Object Detection
Jupyter Notebook
25
star
27

Microcharts.Matplotlib

Microcharts.Matplotlib is a wrapper of Microcharts for Data Science and Machine Learning
C#
22
star
28

protobuf.Text

Text format support for protobuf
C#
21
star
29

GGMLSharp

Use GGML with C#/.NET
C#
19
star
30

SharpPythonCompiler

A compiler which can transform the convention of C# code to the convention of Python
C#
19
star
31

SpaCy.NET

.NET wrapper of spaCy (Industrial-strength NLP)
18
star
32

tensorflow-net-docs

Tensorflow.NET documentation
C#
16
star
33

unity-ml-agents.net

C#
15
star
34

NumSharp.Lite

NumSharp compact version without full datatype supported.
C#
11
star
35

TensorFlow.NET.OpencvAdapter

A library which enables using tensorflow.net with opencvsharp. It reuses the memory to provide a good performance.
C#
9
star
36

PillowSharp

The friendly PIL fork (Python Imaging Library) in C#.
9
star
37

SciSharpStudio

SciSharp Studio is a web based AI/ ML development tool.
HTML
6
star
38

qdrant-csharp

Qdrant .NET Client
C#
6
star
39

TensorDebuggerVisualizers

The Sheet Viewer, which provides instant view of the contents of the sheet when debugging.
C#
5
star
40

ChillXML

2
star