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
4 years ago
6 years ago
4 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
4 years ago
6 years ago
4 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. *master branch is based on tensorflow 2.3 now, v0.15-tensorflow1.15 is from tensorflow1.15.*
  10. ![tensors_flowing](docs/assets/tensors_flowing.gif)
  11. ### Why TensorFlow in C# and F# ?
  12. `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.
  13. ![pythn vs csharp](docs/assets/syntax-comparision.png)
  14. 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.
  15. 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 also implements Tensorflow's high level API where all the magic happens. This computation graph building layer is still under active development. Once it is completely implemented you can build new Machine Learning models in C# or F#.
  16. ### How to use
  17. | 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 |
  18. | -------------------------- | ------------- | -------------- | ------------- | ------------- |
  19. | tf.net 0.3x, tf.keras 0.2 | | | x | not compatible |
  20. | tf.net 0.2x | | x | x | |
  21. | tf.net 0.15 | x | x | | |
  22. | tf.net 0.14 | x | | | |
  23. Troubleshooting of running example or installation, please refer [here](tensorflowlib/README.md).
  24. There are many examples reside at [TensorFlow.NET Examples](https://github.com/SciSharp/TensorFlow.NET-Examples) written in C# and F#.
  25. #### C# Example
  26. Install TF.NET and TensorFlow binary through NuGet.
  27. ```sh
  28. ### install tensorflow C#/F# binding
  29. PM> Install-Package TensorFlow.NET
  30. ### install keras for tensorflow
  31. PM> Install-Package TensorFlow.Keras
  32. ### Install tensorflow binary
  33. ### For CPU version
  34. PM> Install-Package SciSharp.TensorFlow.Redist
  35. ### For GPU version (CUDA and cuDNN are required)
  36. PM> Install-Package SciSharp.TensorFlow.Redist-Windows-GPU
  37. ```
  38. Import TF.NET and Keras API in your project.
  39. ```csharp
  40. using static Tensorflow.Binding;
  41. using static Tensorflow.KerasApi;
  42. using Tensorflow;
  43. using NumSharp;
  44. ```
  45. Linear Regression in `Eager` mode:
  46. ```csharp
  47. // Parameters
  48. var training_steps = 1000;
  49. var learning_rate = 0.01f;
  50. var display_step = 100;
  51. // Sample data
  52. var X = np.array(3.3f, 4.4f, 5.5f, 6.71f, 6.93f, 4.168f, 9.779f, 6.182f, 7.59f, 2.167f,
  53. 7.042f, 10.791f, 5.313f, 7.997f, 5.654f, 9.27f, 3.1f);
  54. var Y = np.array(1.7f, 2.76f, 2.09f, 3.19f, 1.694f, 1.573f, 3.366f, 2.596f, 2.53f, 1.221f,
  55. 2.827f, 3.465f, 1.65f, 2.904f, 2.42f, 2.94f, 1.3f);
  56. var n_samples = X.shape[0];
  57. // We can set a fixed init value in order to demo
  58. var W = tf.Variable(-0.06f, name: "weight");
  59. var b = tf.Variable(-0.73f, name: "bias");
  60. var optimizer = keras.optimizers.SGD(learning_rate);
  61. // Run training for the given number of steps.
  62. foreach (var step in range(1, training_steps + 1))
  63. {
  64. // Run the optimization to update W and b values.
  65. // Wrap computation inside a GradientTape for automatic differentiation.
  66. using var g = tf.GradientTape();
  67. // Linear regression (Wx + b).
  68. var pred = W * X + b;
  69. // Mean square error.
  70. var loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
  71. // should stop recording
  72. // Compute gradients.
  73. var gradients = g.gradient(loss, (W, b));
  74. // Update W and b following gradients.
  75. optimizer.apply_gradients(zip(gradients, (W, b)));
  76. if (step % display_step == 0)
  77. {
  78. pred = W * X + b;
  79. loss = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples);
  80. print($"step: {step}, loss: {loss.numpy()}, W: {W.numpy()}, b: {b.numpy()}");
  81. }
  82. }
  83. ```
  84. Run this example in [Jupyter Notebook](https://github.com/SciSharp/SciSharpCube).
  85. Toy version of `ResNet` in `Keras` functional API:
  86. ```csharp
  87. var layers = new LayersApi();
  88. // input layer
  89. var inputs = keras.Input(shape: (32, 32, 3), name: "img");
  90. // convolutional layer
  91. var x = layers.Conv2D(32, 3, activation: "relu").Apply(inputs);
  92. x = layers.Conv2D(64, 3, activation: "relu").Apply(x);
  93. var block_1_output = layers.MaxPooling2D(3).Apply(x);
  94. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_1_output);
  95. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
  96. var block_2_output = layers.Add().Apply(new Tensors(x, block_1_output));
  97. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(block_2_output);
  98. x = layers.Conv2D(64, 3, activation: "relu", padding: "same").Apply(x);
  99. var block_3_output = layers.Add().Apply(new Tensors(x, block_2_output));
  100. x = layers.Conv2D(64, 3, activation: "relu").Apply(block_3_output);
  101. x = layers.GlobalAveragePooling2D().Apply(x);
  102. x = layers.Dense(256, activation: "relu").Apply(x);
  103. x = layers.Dropout(0.5f).Apply(x);
  104. // output layer
  105. var outputs = layers.Dense(10).Apply(x);
  106. // build keras model
  107. var model = keras.Model(inputs, outputs, name: "toy_resnet");
  108. model.summary();
  109. // compile keras model in tensorflow static graph
  110. model.compile(optimizer: keras.optimizers.RMSprop(1e-3f),
  111. loss: keras.losses.CategoricalCrossentropy(from_logits: true),
  112. metrics: new[] { "acc" });
  113. // prepare dataset
  114. var ((x_train, y_train), (x_test, y_test)) = keras.datasets.cifar10.load_data();
  115. x_train = x_train / 255.0f;
  116. y_train = np_utils.to_categorical(y_train, 10);
  117. // training
  118. model.fit(x_train[new Slice(0, 2000)], y_train[new Slice(0, 2000)],
  119. batch_size: 64,
  120. epochs: 10,
  121. validation_split: 0.2f);
  122. ```
  123. #### F# Example
  124. Linear Regression in `Eager` mode:
  125. ```fsharp
  126. #r "nuget: TensorFlow.Net"
  127. #r "nuget: TensorFlow.Keras"
  128. #r "nuget: SciSharp.TensorFlow.Redist"
  129. #r "nuget: NumSharp"
  130. open NumSharp
  131. open Tensorflow
  132. open type Tensorflow.Binding
  133. open type Tensorflow.KerasApi
  134. let tf = New<tensorflow>()
  135. tf.enable_eager_execution()
  136. // Parameters
  137. let training_steps = 1000
  138. let learning_rate = 0.01f
  139. let display_step = 100
  140. // Sample data
  141. let train_X =
  142. np.array(3.3f, 4.4f, 5.5f, 6.71f, 6.93f, 4.168f, 9.779f, 6.182f, 7.59f, 2.167f,
  143. 7.042f, 10.791f, 5.313f, 7.997f, 5.654f, 9.27f, 3.1f)
  144. let train_Y =
  145. np.array(1.7f, 2.76f, 2.09f, 3.19f, 1.694f, 1.573f, 3.366f, 2.596f, 2.53f, 1.221f,
  146. 2.827f, 3.465f, 1.65f, 2.904f, 2.42f, 2.94f, 1.3f)
  147. let n_samples = train_X.shape.[0]
  148. // We can set a fixed init value in order to demo
  149. let W = tf.Variable(-0.06f,name = "weight")
  150. let b = tf.Variable(-0.73f, name = "bias")
  151. let optimizer = keras.optimizers.SGD(learning_rate)
  152. // Run training for the given number of steps.
  153. for step = 1 to (training_steps + 1) do
  154. // Run the optimization to update W and b values.
  155. // Wrap computation inside a GradientTape for automatic differentiation.
  156. use g = tf.GradientTape()
  157. // Linear regression (Wx + b).
  158. let pred = W * train_X + b
  159. // Mean square error.
  160. let loss = tf.reduce_sum(tf.pow(pred - train_Y,2)) / (2 * n_samples)
  161. // should stop recording
  162. // compute gradients
  163. let gradients = g.gradient(loss,struct (W,b))
  164. // Update W and b following gradients.
  165. optimizer.apply_gradients(zip(gradients, struct (W,b)))
  166. if (step % display_step) = 0 then
  167. let pred = W * train_X + b
  168. let loss = tf.reduce_sum(tf.pow(pred-train_Y,2)) / (2 * n_samples)
  169. printfn $"step: {step}, loss: {loss.numpy()}, W: {W.numpy()}, b: {b.numpy()}"
  170. ```
  171. Read the docs & 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.
  172. ### Contribute:
  173. 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.
  174. You can:
  175. * Let everyone know about this project
  176. * Port Tensorflow unit tests from Python to C# or F#
  177. * Port missing Tensorflow code from Python to C# or F#
  178. * Port Tensorflow examples to C# or F# and raise issues if you come accross missing parts of the API
  179. * Debug one of the unit tests that is marked as Ignored to get it to work
  180. * Debug one of the not yet working examples and get it to work
  181. ### How to debug unit tests:
  182. 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.
  183. ### Git Knowhow for Contributors
  184. Add SciSharp/TensorFlow.NET as upstream to your local repo ...
  185. ```git
  186. git remote add upstream git@github.com:SciSharp/TensorFlow.NET.git
  187. ```
  188. Please make sure you keep your fork up to date by regularly pulling from upstream.
  189. ```git
  190. git pull upstream master
  191. ```
  192. ### Contact
  193. 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/).
  194. Join our chat on [Gitter](https://gitter.im/sci-sharp/community).
  195. Scan QR code to join Tencent TIM group:
  196. ![SciSharp STACK](docs/TIM.jpg)
  197. WeChat Sponsor 微信打赏:
  198. ![SciSharp STACK](docs/assets/WeChatCollection.jpg)
  199. TensorFlow.NET is a part of [SciSharp STACK](https://scisharp.github.io/SciSharp/)
  200. <br>
  201. <a href="http://scisharpstack.org"><img src="https://github.com/SciSharp/SciSharp/blob/master/art/scisharp-stack.png" width="391" height="100" /></a>