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
7 years ago
4 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
5 years ago
7 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. [![Tensorflow.NET](https://ci.appveyor.com/api/projects/status/wx4td43v2d3f2xj6?svg=true)](https://ci.appveyor.com/project/Haiping-Chen/tensorflow-net)
  5. [![NuGet](https://img.shields.io/nuget/dt/TensorFlow.NET.svg)](https://www.nuget.org/packages/TensorFlow.NET)
  6. [![Documentation Status](https://readthedocs.org/projects/tensorflownet/badge/?version=latest)](https://tensorflownet.readthedocs.io/en/latest/?badge=latest)
  7. [![Badge](https://img.shields.io/badge/link-996.icu-red.svg)](https://996.icu/#/en_US)
  8. [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/javiercp/BinderTF.NET/master?urlpath=lab)
  9. English | [中文](docs/Readme-CN.md)
  10. *master branch is based on tensorflow v2.x, v0.6x branch is based on tensorflow v2.6, v0.15-tensorflow1.15 is from tensorflow1.15.*
  11. ![tensors_flowing](docs/assets/tensors_flowing.gif)
  12. ### Why TensorFlow.NET ?
  13. `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.
  14. ![pythn vs csharp](docs/assets/syntax-comparision.png)
  15. 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.
  16. 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.
  17. [ML.NET](https://github.com/dotnet/machinelearning) also support using tensorflow as backend to train and infer your model, which provides better integration with .NET.
  18. Go through the online docs [TensorFlow for .NET](https://scisharp.github.io/tensorflow-net-docs) before you get started with Machine Learning in .NET.
  19. ### How to use
  20. | TensorFlow | tf native1.14, cuda 10.0 | tf native 1.15, cuda 10.0 | tf native 2.3, cuda 10.1 | tf native 2.4, cuda 11 |
  21. | -------------------------- | ------------- | -------------- | ------------- | ------------- |
  22. | tf.net 0.4x, tf.keras 0.5 | | | | x |
  23. | tf.net 0.3x, tf.keras 0.4 | | | x | |
  24. | tf.net 0.2x | | x | x | |
  25. | tf.net 0.15 | x | x | | |
  26. | tf.net 0.14 | x | | | |
  27. Troubleshooting of running example or installation, please refer [here](tensorflowlib/README.md).
  28. There are many examples reside at [TensorFlow.NET Examples](https://github.com/SciSharp/TensorFlow.NET-Examples) written in C# and F#.
  29. #### TensorFlow.net Version
  30. ` tf.net 0.4x -> tf native 2.4`
  31. `tf.net 0.6x -> tf native 2.6`
  32. `tf.net 0.7x -> tf native 2.7`
  33. `tf.net 0.10x -> tf native 2.10`
  34. `...`
  35. #### C# Example
  36. Install TF.NET and TensorFlow binary through NuGet.
  37. ```sh
  38. ### install tensorflow C#/F# binding
  39. PM> Install-Package TensorFlow.NET
  40. ### install keras for tensorflow
  41. PM> Install-Package TensorFlow.Keras
  42. ### Install tensorflow binary
  43. ### For CPU version
  44. PM> Install-Package SciSharp.TensorFlow.Redist
  45. ### For GPU version (CUDA and cuDNN are required)
  46. PM> Install-Package SciSharp.TensorFlow.Redist-Windows-GPU
  47. ```
  48. Import TF.NET and Keras API in your project.
  49. ```csharp
  50. using static Tensorflow.Binding;
  51. using static Tensorflow.KerasApi;
  52. using Tensorflow;
  53. using Tensorflow.NumPy;
  54. ```
  55. Linear Regression in `Eager` mode:
  56. ```csharp
  57. // Parameters
  58. var training_steps = 1000;
  59. var learning_rate = 0.01f;
  60. var display_step = 100;
  61. // Sample data
  62. var X = np.array(3.3f, 4.4f, 5.5f, 6.71f, 6.93f, 4.168f, 9.779f, 6.182f, 7.59f, 2.167f,
  63. 7.042f, 10.791f, 5.313f, 7.997f, 5.654f, 9.27f, 3.1f);
  64. var Y = np.array(1.7f, 2.76f, 2.09f, 3.19f, 1.694f, 1.573f, 3.366f, 2.596f, 2.53f, 1.221f,
  65. 2.827f, 3.465f, 1.65f, 2.904f, 2.42f, 2.94f, 1.3f);
  66. var n_samples = X.shape[0];
  67. // We can set a fixed init value in order to demo
  68. var W = tf.Variable(-0.06f, name: "weight");
  69. var b = tf.Variable(-0.73f, name: "bias");
  70. var optimizer = keras.optimizers.SGD(learning_rate);
  71. // Run training for the given number of steps.
  72. foreach (var step in range(1, training_steps + 1))
  73. {
  74. // Run the optimization to update W and b values.
  75. // Wrap computation inside a GradientTape for automatic differentiation.
  76. using var g = tf.GradientTape();
  77. // Linear regression (Wx + b).
  78. var pred = W * X + b;
  79. // Mean square error.
  80. var loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
  81. // should stop recording
  82. // Compute gradients.
  83. var gradients = g.gradient(loss, (W, b));
  84. // Update W and b following gradients.
  85. optimizer.apply_gradients(zip(gradients, (W, b)));
  86. if (step % display_step == 0)
  87. {
  88. pred = W * X + b;
  89. loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
  90. print($"step: {step}, loss: {loss.numpy()}, W: {W.numpy()}, b: {b.numpy()}");
  91. }
  92. }
  93. ```
  94. Run this example in [Jupyter Notebook](https://github.com/SciSharp/SciSharpCube).
  95. Toy version of `ResNet` in `Keras` functional API:
  96. ```csharp
  97. var layers = new LayersApi();
  98. // input layer
  99. var inputs = keras.Input(shape: (32, 32, 3), name: "img");
  100. // convolutional layer
  101. var x = layers.Conv2D(32, 3, activation: "relu").Apply(inputs);
  102. x = layers.Conv2D(64, 3, activation: "relu").Apply(x);
  103. var block_1_output = layers.MaxPooling2D(3).Apply(x);
  104. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_1_output);
  105. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
  106. var block_2_output = layers.Add().Apply(new Tensors(x, block_1_output));
  107. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_2_output);
  108. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
  109. var block_3_output = layers.Add().Apply(new Tensors(x, block_2_output));
  110. x = layers.Conv2D(64, 3, activation: "relu").Apply(block_3_output);
  111. x = layers.GlobalAveragePooling2D().Apply(x);
  112. x = layers.Dense(256, activation: "relu").Apply(x);
  113. x = layers.Dropout(0.5f).Apply(x);
  114. // output layer
  115. var outputs = layers.Dense(10).Apply(x);
  116. // build keras model
  117. var model = keras.Model(inputs, outputs, name: "toy_resnet");
  118. model.summary();
  119. // compile keras model in tensorflow static graph
  120. model.compile(optimizer: keras.optimizers.RMSprop(1e-3f),
  121. loss: keras.losses.CategoricalCrossentropy(from_logits: true),
  122. metrics: new[] { "acc" });
  123. // prepare dataset
  124. var ((x_train, y_train), (x_test, y_test)) = keras.datasets.cifar10.load_data();
  125. x_train = x_train / 255.0f;
  126. y_train = np_utils.to_categorical(y_train, 10);
  127. // training
  128. model.fit(x_train[new Slice(0, 2000)], y_train[new Slice(0, 2000)],
  129. batch_size: 64,
  130. epochs: 10,
  131. validation_split: 0.2f);
  132. ```
  133. #### F# Example
  134. Linear Regression in `Eager` mode:
  135. ```fsharp
  136. #r "nuget: TensorFlow.Net"
  137. #r "nuget: TensorFlow.Keras"
  138. #r "nuget: SciSharp.TensorFlow.Redist"
  139. open Tensorflow
  140. open Tensorflow.NumPy
  141. open type Tensorflow.Binding
  142. open type Tensorflow.KerasApi
  143. let tf = New<tensorflow>()
  144. tf.enable_eager_execution()
  145. // Parameters
  146. let training_steps = 1000
  147. let learning_rate = 0.01f
  148. let display_step = 100
  149. // Sample data
  150. let train_X =
  151. np.array(3.3f, 4.4f, 5.5f, 6.71f, 6.93f, 4.168f, 9.779f, 6.182f, 7.59f, 2.167f,
  152. 7.042f, 10.791f, 5.313f, 7.997f, 5.654f, 9.27f, 3.1f)
  153. let train_Y =
  154. np.array(1.7f, 2.76f, 2.09f, 3.19f, 1.694f, 1.573f, 3.366f, 2.596f, 2.53f, 1.221f,
  155. 2.827f, 3.465f, 1.65f, 2.904f, 2.42f, 2.94f, 1.3f)
  156. let n_samples = train_X.shape.[0]
  157. // We can set a fixed init value in order to demo
  158. let W = tf.Variable(-0.06f,name = "weight")
  159. let b = tf.Variable(-0.73f, name = "bias")
  160. let optimizer = keras.optimizers.SGD(learning_rate)
  161. // Run training for the given number of steps.
  162. for step = 1 to (training_steps + 1) do
  163. // Run the optimization to update W and b values.
  164. // Wrap computation inside a GradientTape for automatic differentiation.
  165. use g = tf.GradientTape()
  166. // Linear regression (Wx + b).
  167. let pred = W * train_X + b
  168. // Mean square error.
  169. let loss = tf.reduce_sum(tf.pow(pred - train_Y,2)) / (2 * n_samples)
  170. // should stop recording
  171. // compute gradients
  172. let gradients = g.gradient(loss,struct (W,b))
  173. // Update W and b following gradients.
  174. optimizer.apply_gradients(zip(gradients, struct (W,b)))
  175. if (step % display_step) = 0 then
  176. let pred = W * train_X + b
  177. let loss = tf.reduce_sum(tf.pow(pred-train_Y,2)) / (2 * n_samples)
  178. printfn $"step: {step}, loss: {loss.numpy()}, W: {W.numpy()}, b: {b.numpy()}"
  179. ```
  180. Read the book [The Definitive Guide to Tensorflow.NET](https://tensorflownet.readthedocs.io/en/latest/FrontCover.html) if you want to know more about TensorFlow for .NET under the hood.
  181. ### Contribute:
  182. 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.
  183. You can:
  184. * Let everyone know about this project
  185. * Port Tensorflow unit tests from Python to C# or F#
  186. * Port missing Tensorflow code from Python to C# or F#
  187. * Port Tensorflow examples to C# or F# and raise issues if you come accross missing parts of the API
  188. * Debug one of the unit tests that is marked as Ignored to get it to work
  189. * Debug one of the not yet working examples and get it to work
  190. ### How to debug unit tests:
  191. 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.
  192. ### Git Knowhow for Contributors
  193. Add SciSharp/TensorFlow.NET as upstream to your local repo ...
  194. ```git
  195. git remote add upstream git@github.com:SciSharp/TensorFlow.NET.git
  196. ```
  197. Please make sure you keep your fork up to date by regularly pulling from upstream.
  198. ```git
  199. git pull upstream master
  200. ```
  201. ### Support
  202. Buy our book to make open source project be sustainable [TensorFlow.NET实战](https://item.jd.com/13441549.html)
  203. <p float="left">
  204. <img src="https://user-images.githubusercontent.com/1705364/198852429-91741881-c196-401e-8e9e-2f8656196613.png" width="250" />
  205. <img src="https://user-images.githubusercontent.com/1705364/198852521-2f842043-3ace-49d2-8533-039c6a043a3f.png" width="260" />
  206. <img src="https://user-images.githubusercontent.com/1705364/198852721-54cd9e7e-9210-4931-a86c-77584b25b8e1.png" width="260" />
  207. </p>
  208. ### Contact
  209. 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/).
  210. Join our chat on [Gitter](https://gitter.im/sci-sharp/community).
  211. TensorFlow.NET is a part of [SciSharp STACK](https://scisharp.github.io/SciSharp/)
  212. <br>
  213. <a href="http://scisharpstack.org"><img src="https://github.com/SciSharp/SciSharp/blob/master/art/scisharp-stack.png" width="391" height="100" /></a>