Code Monkey home page Code Monkey logo

scisharp / tensorflow.net Goto Github PK

View Code? Open in Web Editor NEW
3.1K 118.0 498.0 371.83 MB

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

Home Page: https://scisharp.github.io/tensorflow-net-docs

License: Apache License 2.0

C# 99.27% Python 0.44% C++ 0.01% PowerShell 0.05% Starlark 0.01% Batchfile 0.04% PureBasic 0.18%
tensorflow machine-learning scisharp deep-learning dotnetcore chatbot csharp keras

tensorflow.net's Introduction

logo

TensorFlow.NET (TF.NET) provides a .NET Standard binding for TensorFlow. It aims to implement the complete Tensorflow API in C# which allows .NET developers to develop, train and deploy Machine Learning models with the cross-platform .NET Standard framework. TensorFlow.NET has built-in Keras high-level interface and is released as an independent package TensorFlow.Keras.

Discord QQ群聊 Join the chat at https://gitter.im/publiclab/publiclab CI Status Documentation Status TensorFlow.NET Badge TensorFlow.Keras Badge MyGet Badge Badge Binder

English | 中文

Important

We're happy that our work on tensorflow.net has attracted many users. However, at this time, none of the main maintainers of this repo is available for new features and bug fix. We won't refuse PRs and will help to review them.

If you would like to be a contributor or maintainer of tensorflow.net, we'd like to help you to start up.

We feel sorry for that and we'll resume the maintaining for this project once one of us has bandwidth for it.

master branch and v0.100.x is corresponding to tensorflow v2.10, v0.6x branch is from tensorflow v2.6, v0.15-tensorflow1.15 is from tensorflow1.15. Please add https://www.myget.org/F/scisharp/api/v3/index.json to nuget source to use nightly release.

tensors_flowing

Why Tensorflow.NET ?

SciSharp STACK's mission is to bring popular data science technology into the .NET world and to provide .NET developers with a powerful Machine Learning tool set without reinventing the wheel. Since the APIs are kept as similar as possible you can immediately adapt any existing TensorFlow code in C# or F# with a zero learning curve. Take a look at a comparison picture and see how comfortably a TensorFlow/Python script translates into a C# program with TensorFlow.NET.

python vs csharp

SciSharp's philosophy allows a large number of machine learning code written in Python to be quickly migrated to .NET, enabling .NET developers to use cutting edge machine learning models and access a vast number of TensorFlow resources which would not be possible without this project.

In comparison to other projects, like for instance TensorFlowSharp which only provide TensorFlow's low-level C++ API and can only run models that were built using Python, Tensorflow.NET makes it possible to build the pipeline of training and inference with pure C# and F#. Besides, Tensorflow.NET provides binding of Tensorflow.Keras to make it easy to transfer your code from python to .NET.

ML.NET also take Tensorflow.NET as one of the backends to train and infer your model, which provides better integration with .NET.

Documention

Introduction and simple examples:Tensorflow.NET Documents

Detailed documention:The Definitive Guide to Tensorflow.NET

Examples:TensorFlow.NET Examples

Troubleshooting of running example or installation:Tensorflow.NET FAQ

Usage

Installation

You can search the package name in NuGet Manager, or use the commands below in package manager console.

The installation contains two parts, the first is the main body:

### Install Tensorflow.NET
PM> Install-Package TensorFlow.NET

### Install Tensorflow.Keras
PM> Install-Package TensorFlow.Keras

The second part is the computing support part. Only one of the following packages is needed, depending on your device and system.

### CPU version for Windows and Linux
PM> Install-Package SciSharp.TensorFlow.Redist

### CPU version for MacOS
PM> Install-Package SciSharp.TensorFlow.Redist-OSX

### GPU version for Windows (CUDA and cuDNN are required)
PM> Install-Package SciSharp.TensorFlow.Redist-Windows-GPU

### GPU version for Linux (CUDA and cuDNN are required)
PM> Install-Package SciSharp.TensorFlow.Redist-Linux-GPU

Two simple examples are given here to introduce the basic usage of Tensorflow.NET. As you can see, it's easy to write C# code just like that in Python.

Example - Linear Regression in Eager mode

using static Tensorflow.Binding;
using static Tensorflow.KerasApi;
using Tensorflow;
using Tensorflow.NumPy;

// Parameters        
var training_steps = 1000;
var learning_rate = 0.01f;
var display_step = 100;

// Sample data
var X = np.array(3.3f, 4.4f, 5.5f, 6.71f, 6.93f, 4.168f, 9.779f, 6.182f, 7.59f, 2.167f,
             7.042f, 10.791f, 5.313f, 7.997f, 5.654f, 9.27f, 3.1f);
var Y = np.array(1.7f, 2.76f, 2.09f, 3.19f, 1.694f, 1.573f, 3.366f, 2.596f, 2.53f, 1.221f,
             2.827f, 3.465f, 1.65f, 2.904f, 2.42f, 2.94f, 1.3f);
var n_samples = X.shape[0];

// We can set a fixed init value in order to demo
var W = tf.Variable(-0.06f, name: "weight");
var b = tf.Variable(-0.73f, name: "bias");
var optimizer = keras.optimizers.SGD(learning_rate);

// Run training for the given number of steps.
foreach (var step in range(1, training_steps + 1))
{
    // Run the optimization to update W and b values.
    // Wrap computation inside a GradientTape for automatic differentiation.
    using var g = tf.GradientTape();
    // Linear regression (Wx + b).
    var pred = W * X + b;
    // Mean square error.
    var loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
    // should stop recording
    // Compute gradients.
    var gradients = g.gradient(loss, (W, b));

    // Update W and b following gradients.
    optimizer.apply_gradients(zip(gradients, (W, b)));

    if (step % display_step == 0)
    {
        pred = W * X + b;
        loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
        print($"step: {step}, loss: {loss.numpy()}, W: {W.numpy()}, b: {b.numpy()}");
    }
}

Run this example in Jupyter Notebook.

Example - Toy version of ResNet in Keras functional API

using static Tensorflow.Binding;
using static Tensorflow.KerasApi;
using Tensorflow;
using Tensorflow.NumPy;

var layers = keras.layers;
// input layer
var inputs = keras.Input(shape: (32, 32, 3), name: "img");
// convolutional layer
var x = layers.Conv2D(32, 3, activation: "relu").Apply(inputs);
x = layers.Conv2D(64, 3, activation: "relu").Apply(x);
var block_1_output = layers.MaxPooling2D(3).Apply(x);
x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_1_output);
x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
var block_2_output = layers.Add().Apply(new Tensors(x, block_1_output));
x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_2_output);
x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
var block_3_output = layers.Add().Apply(new Tensors(x, block_2_output));
x = layers.Conv2D(64, 3, activation: "relu").Apply(block_3_output);
x = layers.GlobalAveragePooling2D().Apply(x);
x = layers.Dense(256, activation: "relu").Apply(x);
x = layers.Dropout(0.5f).Apply(x);
// output layer
var outputs = layers.Dense(10).Apply(x);
// build keras model
var model = keras.Model(inputs, outputs, name: "toy_resnet");
model.summary();
// compile keras model in tensorflow static graph
model.compile(optimizer: keras.optimizers.RMSprop(1e-3f),
    loss: keras.losses.SparseCategoricalCrossentropy(from_logits: true),
    metrics: new[] { "acc" });
// prepare dataset
var ((x_train, y_train), (x_test, y_test)) = keras.datasets.cifar10.load_data();
// normalize the input
x_train = x_train / 255.0f;
// training
model.fit(x_train[new Slice(0, 2000)], y_train[new Slice(0, 2000)],
            batch_size: 64,
            epochs: 10,
            validation_split: 0.2f);
// save the model
model.save("./toy_resnet_model");

The F# example for linear regression is available here.

More adcanced examples could be found in TensorFlow.NET Examples.

Version Relationships

TensorFlow.NET Versions tensorflow 1.14, cuda 10.0 tensorflow 1.15, cuda 10.0 tensorflow 2.3, cuda 10.1 tensorflow 2.4, cuda 11 tensorflow 2.7, cuda 11 tensorflow 2.10, cuda 11
tf.net 0.10x, tf.keras 0.10 x
tf.net 0.7x, tf.keras 0.7 x
tf.net 0.4x, tf.keras 0.5 x
tf.net 0.3x, tf.keras 0.4 x
tf.net 0.2x x x
tf.net 0.15 x x
tf.net 0.14 x
tf.net 0.4x -> tf native 2.4 
tf.net 0.6x -> tf native 2.6      
tf.net 0.7x -> tf native 2.7
tf.net 0.10x -> tf native 2.10
...

Contribution:

Feel like contributing to one of the hottest projects in the Machine Learning field? Want to know how Tensorflow magically creates the computational graph?

We appreciate every contribution however small! There are tasks for novices to experts alike, if everyone tackles only a small task the sum of contributions will be huge.

You can:

  • Star Tensorflow.NET or share it with others
  • Tell us about the missing APIs compared to Tensorflow
  • Port Tensorflow unit tests from Python to C# or F#
  • Port Tensorflow examples to C# or F# and raise issues if you come accross missing parts of the API or BUG
  • Debug one of the unit tests that is marked as Ignored to get it to work
  • Debug one of the not yet working examples and get it to work
  • Help us to complete the documentions.

How to debug unit tests:

The best way to find out why a unit test is failing is to single step it in C# or F# and its corresponding Python at the same time to see where the flow of execution digresses or where variables exhibit different values. Good Python IDEs like PyCharm let you single step into the tensorflow library code.

Git Knowhow for Contributors

Add SciSharp/TensorFlow.NET as upstream to your local repo ...

git remote add upstream [email protected]:SciSharp/TensorFlow.NET.git

Please make sure you keep your fork up to date by regularly pulling from upstream.

git pull upstream master

Support

Buy our book to make open source project be sustainable TensorFlow.NET实战

Contact

Join our chat on Discord or Gitter.

Follow us on Twitter, Facebook, Medium, LinkedIn.

TensorFlow.NET is a part of SciSharp STACK

tensorflow.net's People

Contributors

acifonelli avatar andy-elizabeth-mouse avatar arnavdas88 avatar asakusarinne avatar balashovk avatar banyc avatar brendanmulcahy avatar dataangel avatar deepakkumar1984 avatar devnullx64 avatar dogvane avatar esther2013 avatar harishsk avatar hcur avatar henon avatar kerryjiang avatar lingbai-kong avatar lsylusiyao avatar mpnoy avatar niklasgustafsson avatar novikov-alexander avatar nucs avatar oceania2018 avatar pepure avatar pppbr avatar samuelcaldas avatar scievan avatar sebastian-roko avatar sharwell avatar wanglongzhi2001 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tensorflow.net's Issues

c_api.TF_TensorMaybeMove

Deletes tensor and returns a new TF_Tensor with the same content if possible. Returns nullptr and leaves tensor untouched if not.
TF_CAPI_EXPORT extern TF_Tensor* TF_TensorMaybeMove(TF_Tensor* tensor);

c_api.TF_TensorData

Return a pointer to the underlying data buffer.
TF_CAPI_EXPORT extern void* TF_TensorData(const TF_Tensor*);

c_api.TF_GetCode

Return the code record in *s.
TF_CAPI_EXPORT extern TF_Code TF_GetCode(const TF_Status* s);

c_api.TF_GraphGetTensorNumDims

Returns the number of dimensions of the Tensor referenced by output in graph.
TF_CAPI_EXPORT extern int TF_GraphGetTensorNumDims(TF_Graph* graph, TF_Output output, TF_Status* status);

c_api.TF_GraphGetTensorShape

Returns the shape of the Tensor referenced by output in graph into dims. dims must be an array large enough to hold num_dims entries (e.g., the return value of TF_GraphGetTensorNumDims).
TF_CAPI_EXPORT extern void TF_GraphGetTensorShape(TF_Graph* graph, TF_Output output, int64_t* dims, int num_dims, TF_Status* status);

c_api.TF_SetAttrShape

Set num_dims to -1 to represent "unknown rank". Otherwise, dims points to an array of length num_dims. dims[i] must be >= -1, with -1 meaning "unknown dimension".
TF_CAPI_EXPORT extern void TF_SetAttrShape(TF_OperationDescription* desc, const char* attr_name, const int64_t* dims, int num_dims);

Implement Status class

Status holds error information. It either has an OK code, or else an error code with an associated error message.

c_api.TF_NewGraph

Return a new graph object.
TF_CAPI_EXPORT extern TF_Graph* TF_NewGraph(void);

c_api.TF_NewStatus

Return a new status object.
TF_CAPI_EXPORT extern TF_Status* TF_NewStatus(void);

add _REGISTERED_EXPANSIONS

List of extensions supported to convert run arguments into actual fetches and feeds.
Each element in the list is a tuple of (Type, fetch_fn, feed_fn1, feed_fn2).

_REGISTERED_EXPANSIONS is located in session.py.
public _ElementFetchMapper for_fetch(Tensor fetch)

c_api.TF_TensorByteSize

Return the size of the underlying data in bytes.
TF_CAPI_EXPORT extern size_t TF_TensorByteSize(const TF_Tensor*);

c_api.TF_AllocateTensor

Allocate and return a new Tensor.
This function is an alternative to TF_NewTensor and should be used when memory is allocated to pass the Tensor to the C API. The allocated memory satisfies TensorFlow's memory alignment preferences and should be preferred over calling malloc and free.
The caller must set the Tensor values by writing them to the pointer returned by TF_TensorData with length TF_TensorByteSize.
TF_CAPI_EXPORT extern TF_Tensor* TF_AllocateTensor(TF_DataType, const int64_t* dims, int num_dims, size_t len);

c_api.TF_SetConfig

Set the config in TF_SessionOptions.options.
TF_CAPI_EXPORT extern void TF_SetConfig(TF_SessionOptions* options, const void* proto, size_t proto_len, TF_Status* status);

c_api.TF_SetTarget

Set the target in TF_SessionOptions.options.
TF_CAPI_EXPORT extern void TF_SetTarget(TF_SessionOptions* options, const char* target);

c_api.TF_GraphSetTensorShape

Sets the shape of the Tensor referenced by output in graph to the shape described by dims and num_dims.
TF_CAPI_EXPORT extern void TF_GraphSetTensorShape(TF_Graph* graph, TF_Output output, const int64_t* dims, const int num_dims, TF_Status* status);

c_api.TF_StringDecode

Decode a string encoded using TF_StringEncode.
TF_CAPI_EXPORT extern size_t TF_StringDecode(const char* src, size_t src_len, const char** dst, size_t* dst_len, TF_Status* status);

c_api.TF_NewTensor

Return a new tensor that holds the bytes data[0,len-1].
The data will be deallocated by a subsequent call to TF_DeleteTensor via: (*deallocator)(data, len, deallocator_arg)
Clients must provide a custom deallocator function so they can pass in memory managed by something like numpy.
TF_CAPI_EXPORT extern TF_Tensor* TF_NewTensor( TF_DataType, const int64_t* dims, int num_dims, void* data, size_t len, void (*deallocator)(void* data, size_t len, void* arg), void* deallocator_arg);

c_api.TF_DeleteStatus

Delete a previously created status object.
TF_CAPI_EXPORT extern void TF_DeleteStatus(TF_Status*);

c_api.TF_NewBufferFromString

Makes a copy of the input and sets an appropriate deallocator. Useful for passing in read-only, input protobufs.
TF_CAPI_EXPORT extern TF_Buffer* TF_NewBufferFromString(const void* proto, size_t proto_len);

c_api.TF_Message

Return a pointer to the (null-terminated) error message in *s.
The return value points to memory that is only usable until the next mutation to *s. Always returns an empty string if TF_GetCode(s) is TF_OK.
TF_CAPI_EXPORT extern const char* TF_Message(const TF_Status* s);

Implement Buffer class

TF_Buffer holds a pointer to a block of data and its associated length. Typically, the data consists of a serialized protocol buffer, but other data may also be held in a buffer.

Complete BaseSession._update_with_movers

If a tensor handle that is fed to a device incompatible placeholder, we move the tensor to the right device, generate a new tensor handle, and update feed_dict to use the new handle.

c_api.TF_SetStatus

Record <code, msg> in *s. Any previous information is lost.
A common use is to clear a status: TF_SetStatus(s, TF_OK, "");
TF_CAPI_EXPORT extern void TF_SetStatus(TF_Status* s, TF_Code code, const char* msg);

c_api.TF_DataTypeSize

returns the sizeof() for the underlying type corresponding to the given TF_DataType enum value. Returns 0 for variable length types (eg. TF_STRING) or on failure..
TF_CAPI_EXPORT extern size_t TF_DataTypeSize(TF_DataType dt);

The Definitive Guide to Tensorflow.NET

When I started writing this project, I was also sorting out the idea of the coding process. Tensorflow is a huge and complicated project, and it is easy to go beyond the scope of personal ability. Therefore, I want to record the thoughts at the time as much as possible. The process of recording and sorting clears the way of thinking. So I decided to write a book: The Definitive Guide to Tensorflow.NET

c_api.TF_StringEncodedSize

Return the size in bytes required to encode a string len bytes long into a TF_STRING tensor.
TF_CAPI_EXPORT extern size_t TF_StringEncodedSize(size_t len);

c_api.TF_NewBuffer

Useful for passing out a protobuf.
TF_CAPI_EXPORT extern TF_Buffer* TF_NewBuffer(void);

c_api.TF_Dim

Return the length of the tensor in the "dim_index" dimension.
TF_CAPI_EXPORT extern int64_t TF_Dim(const TF_Tensor* tensor, int dim_index);

Add _FetchHandler to handle structured fetches

tf.Session.run requires to specify a list of fetches, which determine the return values, and may be a tf.Operation, a tf.Tensor or a tensor-like type such as tf.Variable. These fetches determine what subgraph of the overall tf.Graph must be executed to produce the result: this is the subgraph that contains all operations named in the fetch lish, plus all operations whose outputs are used to compute the value of the fetches.

Given a graph, a user-provided structure for fetches, and a feed dict, this
class takes care of generating a list of tensor names to fetch and op names
to run for a low level run() call.

Refer the official docs here.

c_api.TF_StringEncode

Encode the string src (src_len bytes long) into dst in the format
required by TF_STRING tensors. Does not write to memory more than dst_len
bytes beyond *dst. dst_len should be at least
TF_CAPI_EXPORT extern size_t TF_StringEncode(const char* src, size_t src_len, char* dst, size_t dst_len, TF_Status* status);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.