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 13 kB

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