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