• Stars
    star
    3,118
  • Rank 13,839 (Top 0.3 %)
  • Language
    C#
  • License
    MIT License
  • Created over 7 years ago
  • Updated 4 months ago

Reviews

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

Repository Details

TensorFlow API for .NET languages

Build Status Gitter

When to use TensorFlowSharp

TensorFlowSharp is a good runtime to run your existing models, and is mostly a straight binding to the underlying TensorFlow runtime. Most people will want to use a higher-level library for interfacing with TensorFlow.

The library was designed to blend in the .NET ecosystem and use the .NET naming conventions.

I strongly recommend that you use TensorFlow.NET which takes a different approach than TensorFlowSharp, it uses the Python naming convention and has a much broader support for the higher level operations that you are likely to need - and is also actively maintained.

TensorFlowSharp

TensorFlowSharp are .NET bindings to the TensorFlow library published here:

https://github.com/tensorflow/tensorflow

This surfaces the C API as a strongly-typed .NET API for use from C# and F#.

The API surfaces the entire low-level TensorFlow API, it is on par with other language bindings. But currently does not include a high-level API like the Python binding does, so it is more cumbersome to use for those high level operations.

You can prototype using TensorFlow or Keras in Python, then save your graphs or trained models and then load the result in .NET with TensorFlowSharp and feed your own data to train or run.

The current API documentation is here.

Using TensorFlowSharp

Installation

The easiest way to get started is to use the NuGet package for TensorFlowSharp which contains both the .NET API as well as the native libraries for 64-bit Linux, Mac and Windows using the CPU backend.

You can install using NuGet like this:

nuget install TensorFlowSharp

Or select it from the NuGet packages UI on Visual Studio.

On Visual Studio, make sure that you are targeting .NET 4.6.1 or later, as this package uses some features of newer .NETs. Otherwise, the package will not be added. Once you do this, you can just use the TensorFlowSharp nuget

Alternatively, you can download it directly.

Using TensorFlowSharp

Your best source of information right now are the SampleTest that exercises various APIs of TensorFlowSharp, or the stand-alone samples located in "Examples".

This API binding is closer design-wise to the Java and Go bindings which use explicit TensorFlow graphs and sessions. Your application will typically create a graph (TFGraph) and setup the operations there, then create a session from it (TFSession), then use the session runner to setup inputs and outputs and execute the pipeline.

Something like this:

using (var graph = new TFGraph ())
{
    // Load the model
    graph.Import (File.ReadAllBytes ("MySavedModel"));
    using (var session = new TFSession (graph))
    {
        // Setup the runner
        var runner = session.GetRunner ();
        runner.AddInput (graph ["input"] [0], tensor);
        runner.Fetch (graph ["output"] [0]);

        // Run the model
        var output = runner.Run ();

        // Fetch the results from output:
        TFTensor result = output [0];
    }
}

If your application is sensitive to GC cycles, you can run your model as follows. The Run method will then allocate managed memory only at the first call and reuse it later on. Note that this requires you to reuse the Runner instance and not to change the shape of the input data:

// Some input matrices
var inputs = new float[][,] {
    new float[,] { { 1, 2 }, { 3, 4 } },
    new float[,] { { 2, 4 }, { 6, 8 } }
};

// Assumes all input matrices have identical shape
var shape = new long[] { inputs[0].GetLongLength(0), inputs[0].GetLongLength(1) };
var size = inputs[0].Length * sizeof(float);

// Empty input and output tensors
var input = new TFTensor(TFDataType.Float, shape, size);
var output = new TFTensor[1];

// Result array for a single run
var result = new float[1, 1];

using (var graph = new TFGraph())
{
    // Load the model
    graph.Import(File.ReadAllBytes("MySavedModel"));
    using (var session = new TFSession(graph))
    {
        // Setup the runner
        var runner = session.GetRunner();
        runner.AddInput(graph["input"][0], input);
        runner.Fetch(graph["output"][0]);

        // Run the model on each input matrix
        for (int i = 0; i < inputs.Length; i++)
        {
            // Mutate the input tensor
            input.SetValue(inputs[i]);

            // Run the model
            runner.Run(output);

            // Fetch the result from output into `result`
            output[0].GetValue(result);
        }
    }
}

In scenarios where you do not need to setup the graph independently, the session will create one for you. The following example shows how to abuse TensorFlow to compute the addition of two numbers:

using (var session = new TFSession())
{
    var graph = session.Graph;

    var a = graph.Const(2);
    var b = graph.Const(3);
    Console.WriteLine("a=2 b=3");

    // Add two constants
    var addingResults = session.GetRunner().Run(graph.Add(a, b));
    var addingResultValue = addingResults.GetValue();
    Console.WriteLine("a+b={0}", addingResultValue);

    // Multiply two constants
    var multiplyResults = session.GetRunner().Run(graph.Mul(a, b));
    var multiplyResultValue = multiplyResults.GetValue();
    Console.WriteLine("a*b={0}", multiplyResultValue);
}

Here is an F# scripting version of the same example, you can use this in F# Interactive:

#r @"packages\TensorFlowSharp.1.4.0\lib\net471\TensorFlowSharp.dll"

open System
open System.IO
open TensorFlow

// set the path to find the native DLL
Environment.SetEnvironmentVariable("Path", 
    Environment.GetEnvironmentVariable("Path") + ";" + __SOURCE_DIRECTORY__ + @"/packages/TensorFlowSharp.1.2.2/native")

module AddTwoNumbers = 
    let session = new TFSession()
    let graph = session.Graph

    let a = graph.Const(new TFTensor(2))
    let b = graph.Const(new TFTensor(3))
    Console.WriteLine("a=2 b=3")

    // Add two constants
    let addingResults = session.GetRunner().Run(graph.Add(a, b))
    let addingResultValue = addingResults.GetValue()
    Console.WriteLine("a+b={0}", addingResultValue)

    // Multiply two constants
    let multiplyResults = session.GetRunner().Run(graph.Mul(a, b))
    let multiplyResultValue = multiplyResults.GetValue()
    Console.WriteLine("a*b={0}", multiplyResultValue)

Working on TensorFlowSharp

If you want to work on extending TensorFlowSharp or contribute to its development read the CONTRIBUTING.md file.

Please keep in mind that this requires a modern version of C# as this uses some new capabilities there. So you will want to use Visual Studio 2017.

Possible Contributions

Build More Tests

Would love to have more tests to ensure the proper operation of the framework.

Samples

The binding is pretty much complete, and at this point, I want to improve the API to be easier and more pleasant to use from both C# and F#. Creating samples that use Tensorflow is a good way of finding easy wins on the usability of the API, there are some here:

https://github.com/tensorflow/models

Packaging

Mobile: we need to package the library for consumption on Android and iOS.

Documentation Styling

The API documentation has not been styled, I am using the barebones template for documentation, and it can use some work.

Issues

I have logged some usability problems and bugs in Issues, feel free to take on one of those tasks.

Documentation

Much of the online documentation comes from TensorFlow and is licensed under the terms of Apache 2 License, in particular all the generated documentation for the various operations that is generated by using the tensorflow reflection APIs.

Last API update: Release 1.9

More Repositories

1

SwiftTerm

Xterm/VT100 Terminal emulator in Swift
Swift
854
star
2

SwiftGodot

New Godot bindings for Swift
Swift
758
star
3

mono-wasm

JavaScript
523
star
4

TermKit

Terminal Kit - Console UI toolkit for Swift applications
Swift
444
star
5

MonoTouch.Dialog

Tools to simplify creating dialogs with the user using MonoTouch
C#
432
star
6

WasmerSharp

.NET Bindings for the Wasmer Runtime
C#
318
star
7

SwiftTermApp

Swift
284
star
8

PlaticaBot

MacOS, iOS and watchOS ChatGPT client using your own OpenAI key
Swift
185
star
9

TweetStation

MonoTouch based Twitter client
C#
180
star
10

XtermSharp

XTerm emulator as a .NET library
C#
156
star
11

redis-sharp

A C#/.NET binding for the Redis server.
C#
152
star
12

SwiftGodotKit

Embed Godot into Swift apps
C
146
star
13

SkiaKit

Swift Bindings to the Skia 2D graphics Library
Swift
130
star
14

TextBufferKit

Swift TextBuffer
Swift
103
star
15

CovidGraphs

Covid Graphs app
Swift
93
star
16

SwiftChatGPT

Simple ChatGPT API
Swift
72
star
17

GodotSwift

Swift bindings for the Godot Game Engine
C
56
star
18

mc

C# based curses file manager
C#
45
star
19

FuchsiaSharp

Bindings to Fuchsia
C#
36
star
20

OpenFlowSharp

Sample CoverFlow implementation for MonoTouch, based on OpenFlow
C#
33
star
21

muget

Command line front end to NuGet that is not overengineered
C#
31
star
22

monotouch-libs

Various MonoTouch bindings and libraries
C#
25
star
23

TldExtract

.NET Library to extracts the root domain, subdomain name, and top level domain from a host name using the Public Suffix List
C#
22
star
24

RealityActions

RealityActions
Swift
18
star
25

SwiftGodotBinary

SwiftGodot - binaries for ease of consumption
Swift
17
star
26

mono-wasm-libc

C
15
star
27

TurboSwift

Swift
14
star
28

mono-wasm-mono

C#
14
star
29

FluidInterfaces

Port of Nathan Gitter's Fluid Interfaces code
C#
14
star
30

MaterialSharp

Material design components for iOS applications written in C#
C#
13
star
31

NetCatNetwork

NetCat implementation using the new Apple Network framework, C# port of the C sample
C#
11
star
32

CovidExtractor

My Covid Extractor
Swift
9
star
33

SwiftGodotDocs

9
star
34

CocoaDriver

Xamarin.Mac-based Cocoa driver for Mono's System.Windows.Forms
C#
8
star
35

Darwin.CopyFile

Bindings for Darwin's CopyFile API
C#
8
star
36

MonoTouch.Bindings

Some bindings for third party libraries
6
star
37

migueldeicaza

Repository for my README
6
star
38

gtk

Fork of Gtk branch 2-24 with all Xamarin patches from github.com/mono/bockbuild applied
C
5
star
39

libgodot

Godot modified to be embeddable as a library, for use in SwiftGodotKit
C++
5
star
40

GodotSwiftLink

Binding module, temporary, while I move it to Godot.
C
4
star
41

PhotoPanner

C# version of Facebooks Photo Panner
C#
4
star
42

Mac-SceneKit-Globe-Test

Sample F# Mac app showing SceneKit in action.
F#
4
star
43

Mono.VFS

C# based Virtual File System API.
4
star
44

SimpleCollage

Simple picture collage with SkiaSharp
C#
4
star
45

til

4
star
46

KeyboardButton

Simple keyboard button in SwiftUI eventually for use in the Terminal Emulator
Swift
4
star
47

MapWrapper

SwiftUI wrapper around MapKit
Swift
4
star
48

SwiftApiExtractIssue

Shows a bug with swift-api-extract
Swift
3
star
49

RosettaMaker

Creates the Rosetta HTML page that shows the C#/Objective-C/C mappings
C#
3
star
50

KitCore.NET

.NET bindings to KitCore - the ultimate core application framework
3
star
51

NailedIt

My Google Glasses app to "Capture Moments" and "Nailed it"
Java
3
star
52

SplashView

C# Port of SplashView https://github.com/callumboddy/CBZSplashView
C#
3
star
53

FileProvider-ios-crashing

Swift
2
star
54

monotouch-samples

MonoTouch Sample Programs
2
star
55

SwiftSH.binaries

Binary for the SwiftSH framework
C
2
star
56

SkiaKit.binaries

Precompiled binaries for various platforms of the runtime used by SkiaKit (SkiaSharp)
2
star
57

CovidExtractorPM

SwiftPM version of CovidExtractor
Swift
2
star
58

paint-mono

Automatically exported from code.google.com/p/paint-mono
C#
2
star
59

SkiaKitPayloads

Binary payloads directory for the SkiaKit library
Shell
1
star
60

SwiftOnnxMnist

Mnist sample using OnnxRuntime in Swift
C++
1
star
61

iptoloc

IP to Location Tools
C#
1
star
62

TreemapWeb

C#
1
star
63

mlist

Gtk# Mlist widget - managed implementation of a list view (2005 era)
C#
1
star
64

mono-soc-2007

Automatically exported from code.google.com/p/mono-soc-2007
C#
1
star
65

blog-monomac

MonoMac Blog
1
star
66

SwiftDocCPlusPlusBug

Sample of how Swift Docc fails if you use the new Swift C++ interop
Swift
1
star
67

GodotSnippetEditor

A tool to edit Godot documentation code snippets
Swift
1
star
68

SwiftTermDocs

Placeholder to publish the API docs for SwiftTerm
1
star
69

esctest

Mirror from https://gitlab.freedesktop.org/terminal-wg/esctest.git
Python
1
star
70

CoreKitSharp

Bindings to the Ultimate Framework Platform
1
star