You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 12 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. ![logo](docs/assets/tf.net.logo.png)
  2. **TensorFlow.NET** (TF.NET) provides a .NET Standard binding for [TensorFlow](https://www.tensorflow.org/). 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](https://www.nuget.org/packages/TensorFlow.Keras/).
  3. ![Discord](https://img.shields.io/discord/1106946823282761851?label=Discord)
  4. [![Join the chat at https://gitter.im/publiclab/publiclab](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sci-sharp/community)
  5. [![CI Status](https://github.com/SciSharp/TensorFlow.NET/actions/workflows/build_and_test.yml/badge.svg)](https://github.com/SciSharp/TensorFlow.NET/actions/workflows/build_and_test.yml)
  6. [![NuGet Badge](https://buildstats.info/nuget/TensorFlow.NET?includePreReleases=true)](https://www.nuget.org/packages/TensorFlow.NET)
  7. [![MyGet Badge](https://img.shields.io/badge/dynamic/json?color=purple&label=nightly%20release&prefix=myget-v&query=items%5B0%5D.lower&url=https%3A%2F%2Fwww.myget.org%2FF%2Fscisharp%2Fapi%2Fv3%2Fregistration1%2Ftensorflow.net%2Findex.json)](https://www.myget.org/feed/scisharp/package/nuget/Tensorflow.NET)
  8. [![Documentation Status](https://readthedocs.org/projects/tensorflownet/badge/?version=latest)](https://tensorflownet.readthedocs.io/en/latest/?badge=latest)
  9. [![Badge](https://img.shields.io/badge/link-996.icu-red.svg)](https://996.icu/#/en_US)
  10. [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/javiercp/BinderTF.NET/master?urlpath=lab)
  11. English | [中文](docs/README-CN.md)
  12. *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.*
  13. ![tensors_flowing](docs/assets/tensors_flowing.gif)
  14. ## Why Tensorflow.NET ?
  15. `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.
  16. ![python vs csharp](docs/assets/syntax-comparision.png)
  17. 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.
  18. In comparison to other projects, like for instance [TensorFlowSharp](https://www.nuget.org/packages/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.
  19. [ML.NET](https://github.com/dotnet/machinelearning) also take Tensorflow.NET as one of the backends to train and infer your model, which provides better integration with .NET.
  20. ## Documention
  21. Introduction and simple examples:[Tensorflow.NET Documents](https://scisharp.github.io/tensorflow-net-docs)
  22. Detailed documention:[The Definitive Guide to Tensorflow.NET](https://tensorflownet.readthedocs.io/en/latest/FrontCover.html)
  23. Examples:[TensorFlow.NET Examples](https://github.com/SciSharp/TensorFlow.NET-Examples)
  24. Troubleshooting of running example or installation:[Tensorflow.NET FAQ](tensorflowlib/README.md)
  25. ## Usage
  26. ### Installation
  27. You can search the package name in NuGet Manager, or use the commands below in package manager console.
  28. The installation contains two parts, the first is the main body:
  29. ```sh
  30. ### Install Tensorflow.NET
  31. PM> Install-Package TensorFlow.NET
  32. ### Install Tensorflow.Keras
  33. PM> Install-Package TensorFlow.Keras
  34. ```
  35. The second part is the computing support part. Only one of the following packages is needed, depending on your device and system.
  36. ```
  37. ### CPU version for Windows, Linux and Mac
  38. PM> Install-Package SciSharp.TensorFlow.Redist
  39. ### GPU version for Windows (CUDA and cuDNN are required)
  40. PM> Install-Package SciSharp.TensorFlow.Redist-Windows-GPU
  41. ### GPU version for Linux (CUDA and cuDNN are required)
  42. PM> Install-Package SciSharp.TensorFlow.Redist-Linux-GPU
  43. ```
  44. 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.
  45. ### Example - Linear Regression in `Eager` mode
  46. ```csharp
  47. using static Tensorflow.Binding;
  48. using static Tensorflow.KerasApi;
  49. using Tensorflow;
  50. using Tensorflow.NumPy;
  51. // Parameters
  52. var training_steps = 1000;
  53. var learning_rate = 0.01f;
  54. var display_step = 100;
  55. // Sample data
  56. var X = np.array(3.3f, 4.4f, 5.5f, 6.71f, 6.93f, 4.168f, 9.779f, 6.182f, 7.59f, 2.167f,
  57. 7.042f, 10.791f, 5.313f, 7.997f, 5.654f, 9.27f, 3.1f);
  58. var Y = np.array(1.7f, 2.76f, 2.09f, 3.19f, 1.694f, 1.573f, 3.366f, 2.596f, 2.53f, 1.221f,
  59. 2.827f, 3.465f, 1.65f, 2.904f, 2.42f, 2.94f, 1.3f);
  60. var n_samples = X.shape[0];
  61. // We can set a fixed init value in order to demo
  62. var W = tf.Variable(-0.06f, name: "weight");
  63. var b = tf.Variable(-0.73f, name: "bias");
  64. var optimizer = keras.optimizers.SGD(learning_rate);
  65. // Run training for the given number of steps.
  66. foreach (var step in range(1, training_steps + 1))
  67. {
  68. // Run the optimization to update W and b values.
  69. // Wrap computation inside a GradientTape for automatic differentiation.
  70. using var g = tf.GradientTape();
  71. // Linear regression (Wx + b).
  72. var pred = W * X + b;
  73. // Mean square error.
  74. var loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
  75. // should stop recording
  76. // Compute gradients.
  77. var gradients = g.gradient(loss, (W, b));
  78. // Update W and b following gradients.
  79. optimizer.apply_gradients(zip(gradients, (W, b)));
  80. if (step % display_step == 0)
  81. {
  82. pred = W * X + b;
  83. loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
  84. print($"step: {step}, loss: {loss.numpy()}, W: {W.numpy()}, b: {b.numpy()}");
  85. }
  86. }
  87. ```
  88. Run this example in [Jupyter Notebook](https://github.com/SciSharp/SciSharpCube).
  89. ### Example - Toy version of `ResNet` in `Keras` functional API
  90. ```csharp
  91. using static Tensorflow.Binding;
  92. using static Tensorflow.KerasApi;
  93. using Tensorflow;
  94. using Tensorflow.NumPy;
  95. var layers = keras.layers;
  96. // input layer
  97. var inputs = keras.Input(shape: (32, 32, 3), name: "img");
  98. // convolutional layer
  99. var x = layers.Conv2D(32, 3, activation: "relu").Apply(inputs);
  100. x = layers.Conv2D(64, 3, activation: "relu").Apply(x);
  101. var block_1_output = layers.MaxPooling2D(3).Apply(x);
  102. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_1_output);
  103. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
  104. var block_2_output = layers.Add().Apply(new Tensors(x, block_1_output));
  105. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_2_output);
  106. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
  107. var block_3_output = layers.Add().Apply(new Tensors(x, block_2_output));
  108. x = layers.Conv2D(64, 3, activation: "relu").Apply(block_3_output);
  109. x = layers.GlobalAveragePooling2D().Apply(x);
  110. x = layers.Dense(256, activation: "relu").Apply(x);
  111. x = layers.Dropout(0.5f).Apply(x);
  112. // output layer
  113. var outputs = layers.Dense(10).Apply(x);
  114. // build keras model
  115. var model = keras.Model(inputs, outputs, name: "toy_resnet");
  116. model.summary();
  117. // compile keras model in tensorflow static graph
  118. model.compile(optimizer: keras.optimizers.RMSprop(1e-3f),
  119. loss: keras.losses.SparseCategoricalCrossentropy(from_logits: true),
  120. metrics: new[] { "acc" });
  121. // prepare dataset
  122. var ((x_train, y_train), (x_test, y_test)) = keras.datasets.cifar10.load_data();
  123. // normalize the input
  124. x_train = x_train / 255.0f;
  125. // training
  126. model.fit(x_train[new Slice(0, 2000)], y_train[new Slice(0, 2000)],
  127. batch_size: 64,
  128. epochs: 10,
  129. validation_split: 0.2f);
  130. // save the model
  131. model.save("./toy_resnet_model");
  132. ```
  133. The F# example for linear regression is available [here](docs/Example-fsharp.md).
  134. More adcanced examples could be found in [TensorFlow.NET Examples](https://github.com/SciSharp/TensorFlow.NET-Examples).
  135. ## Version Relationships
  136. | 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 |
  137. | -------------------------- | ------------- | -------------- | ------------- | ------------- | ------------ | ------------ |
  138. | tf.net 0.10x, tf.keras 0.10 | | | | | | x |
  139. | tf.net 0.7x, tf.keras 0.7 | | | | | x | |
  140. | tf.net 0.4x, tf.keras 0.5 | | | | x | | |
  141. | tf.net 0.3x, tf.keras 0.4 | | | x | | | |
  142. | tf.net 0.2x | | x | x | | | |
  143. | tf.net 0.15 | x | x | | | | |
  144. | tf.net 0.14 | x | | | | | |
  145. ```
  146. tf.net 0.4x -> tf native 2.4
  147. tf.net 0.6x -> tf native 2.6
  148. tf.net 0.7x -> tf native 2.7
  149. tf.net 0.10x -> tf native 2.10
  150. ...
  151. ```
  152. ## Contribution:
  153. Feel like contributing to one of the hottest projects in the Machine Learning field? Want to know how Tensorflow magically creates the computational graph?
  154. 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.
  155. You can:
  156. - Star Tensorflow.NET or share it with others
  157. - Tell us about the missing APIs compared to Tensorflow
  158. - Port Tensorflow unit tests from Python to C# or F#
  159. - Port Tensorflow examples to C# or F# and raise issues if you come accross missing parts of the API or BUG
  160. - Debug one of the unit tests that is marked as Ignored to get it to work
  161. - Debug one of the not yet working examples and get it to work
  162. - Help us to complete the documentions.
  163. #### How to debug unit tests:
  164. 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.
  165. #### Git Knowhow for Contributors
  166. Add SciSharp/TensorFlow.NET as upstream to your local repo ...
  167. ```git
  168. git remote add upstream git@github.com:SciSharp/TensorFlow.NET.git
  169. ```
  170. Please make sure you keep your fork up to date by regularly pulling from upstream.
  171. ```git
  172. git pull upstream master
  173. ```
  174. ### Support
  175. Buy our book to make open source project be sustainable [TensorFlow.NET实战](https://item.jd.com/13441549.html)
  176. <p float="left">
  177. <img src="https://user-images.githubusercontent.com/1705364/198852429-91741881-c196-401e-8e9e-2f8656196613.png" width="250" />
  178. <img src="https://user-images.githubusercontent.com/1705364/198852521-2f842043-3ace-49d2-8533-039c6a043a3f.png" width="260" />
  179. <img src="https://user-images.githubusercontent.com/1705364/198852721-54cd9e7e-9210-4931-a86c-77584b25b8e1.png" width="260" />
  180. </p>
  181. ### Contact
  182. Join our chat on [Discord](https://discord.gg/quBc2jrz) or [Gitter](https://gitter.im/sci-sharp/community).
  183. Follow us on [Twitter](https://twitter.com/ScisharpStack), [Facebook](https://www.facebook.com/scisharp.stack.9), [Medium](https://medium.com/scisharp), [LinkedIn](https://www.linkedin.com/company/scisharp-stack/).
  184. TensorFlow.NET is a part of [SciSharp STACK](https://scisharp.github.io/SciSharp/)
  185. <br>
  186. <a href="http://scisharpstack.org"><img src="https://github.com/SciSharp/SciSharp/blob/master/art/scisharp-stack.png" width="391" height="100" /></a>