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.

BasicOperations.cs 2.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using NumSharp.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using Tensorflow;
  6. namespace TensorFlowNET.Examples
  7. {
  8. /// <summary>
  9. /// Basic Operations example using TensorFlow library.
  10. /// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/1_Introduction/basic_operations.py
  11. /// </summary>
  12. public class BasicOperations : IExample
  13. {
  14. private Session sess;
  15. public void Run()
  16. {
  17. // Basic constant operations
  18. // The value returned by the constructor represents the output
  19. // of the Constant op.
  20. var a = tf.constant(2);
  21. var b = tf.constant(3);
  22. // Launch the default graph.
  23. using (sess = tf.Session())
  24. {
  25. Console.WriteLine("a=2, b=3");
  26. Console.WriteLine($"Addition with constants: {sess.run(a + b)}");
  27. Console.WriteLine($"Multiplication with constants: {sess.run(a * b)}");
  28. }
  29. // Basic Operations with variable as graph input
  30. // The value returned by the constructor represents the output
  31. // of the Variable op. (define as input when running session)
  32. // tf Graph input
  33. a = tf.placeholder(tf.int16);
  34. b = tf.placeholder(tf.int16);
  35. // Define some operations
  36. var add = tf.add(a, b);
  37. var mul = tf.multiply(a, b);
  38. // Launch the default graph.
  39. using(sess = tf.Session())
  40. {
  41. var feed_dict = new Dictionary<Tensor, NDArray>();
  42. feed_dict.Add(a, (short)2);
  43. feed_dict.Add(b, (short)3);
  44. // Run every operation with variable input
  45. Console.WriteLine($"Addition with variables: {sess.run(add, feed_dict)}");
  46. Console.WriteLine($"Multiplication with variables: {sess.run(mul, feed_dict)}");
  47. }
  48. // ----------------
  49. // More in details:
  50. // Matrix Multiplication from TensorFlow official tutorial
  51. // Create a Constant op that produces a 1x2 matrix. The op is
  52. // added as a node to the default graph.
  53. //
  54. // The value returned by the constructor represents the output
  55. // of the Constant op.
  56. }
  57. }
  58. }

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。