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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using NumSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using Tensorflow;
  6. using static Tensorflow.Python;
  7. namespace TensorFlowNET.Examples
  8. {
  9. /// <summary>
  10. /// Basic Operations example using TensorFlow library.
  11. /// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/1_Introduction/basic_operations.py
  12. /// </summary>
  13. public class BasicOperations : IExample
  14. {
  15. public bool Enabled { get; set; } = true;
  16. public string Name => "Basic Operations";
  17. public bool IsImportingGraph { get; set; } = false;
  18. private Session sess;
  19. public bool Run()
  20. {
  21. // Basic constant operations
  22. // The value returned by the constructor represents the output
  23. // of the Constant op.
  24. var a = tf.constant(2);
  25. var b = tf.constant(3);
  26. // Launch the default graph.
  27. using (sess = tf.Session())
  28. {
  29. Console.WriteLine("a=2, b=3");
  30. Console.WriteLine($"Addition with constants: {sess.run(a + b)}");
  31. Console.WriteLine($"Multiplication with constants: {sess.run(a * b)}");
  32. }
  33. // Basic Operations with variable as graph input
  34. // The value returned by the constructor represents the output
  35. // of the Variable op. (define as input when running session)
  36. // tf Graph input
  37. a = tf.placeholder(tf.int16);
  38. b = tf.placeholder(tf.int16);
  39. // Define some operations
  40. var add = tf.add(a, b);
  41. var mul = tf.multiply(a, b);
  42. // Launch the default graph.
  43. using(sess = tf.Session())
  44. {
  45. var feed_dict = new FeedItem[]
  46. {
  47. new FeedItem(a, (short)2),
  48. new FeedItem(b, (short)3)
  49. };
  50. // Run every operation with variable input
  51. Console.WriteLine($"Addition with variables: {sess.run(add, feed_dict)}");
  52. Console.WriteLine($"Multiplication with variables: {sess.run(mul, feed_dict)}");
  53. }
  54. // ----------------
  55. // More in details:
  56. // Matrix Multiplication from TensorFlow official tutorial
  57. // Create a Constant op that produces a 1x2 matrix. The op is
  58. // added as a node to the default graph.
  59. //
  60. // The value returned by the constructor represents the output
  61. // of the Constant op.
  62. var nd1 = np.array(3, 3).reshape(1, 2);
  63. var matrix1 = tf.constant(nd1);
  64. // Create another Constant that produces a 2x1 matrix.
  65. var nd2 = np.array(2, 2).reshape(2, 1);
  66. var matrix2 = tf.constant(nd2);
  67. // Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
  68. // The returned value, 'product', represents the result of the matrix
  69. // multiplication.
  70. var product = tf.matmul(matrix1, matrix2);
  71. // To run the matmul op we call the session 'run()' method, passing 'product'
  72. // which represents the output of the matmul op. This indicates to the call
  73. // that we want to get the output of the matmul op back.
  74. //
  75. // All inputs needed by the op are run automatically by the session. They
  76. // typically are run in parallel.
  77. //
  78. // The call 'run(product)' thus causes the execution of threes ops in the
  79. // graph: the two constants and matmul.
  80. //
  81. // The output of the op is returned in 'result' as a numpy `ndarray` object.
  82. using (sess = tf.Session())
  83. {
  84. var result = sess.run(product);
  85. Console.WriteLine(result.ToString()); // ==> [[ 12.]]
  86. };
  87. // `BatchMatMul` is actually embedded into the `MatMul` operation on the tensorflow.dll side. Every time we ask
  88. // for a multiplication between matrices with rank > 2, the first rank - 2 dimensions are checked to be consistent
  89. // across the two matrices and a common matrix multiplication is done on the residual 2 dimensions.
  90. //
  91. // np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape(3, 3, 3)
  92. // array([[[1, 2, 3],
  93. // [4, 5, 6],
  94. // [7, 8, 9]],
  95. //
  96. // [[1, 2, 3],
  97. // [4, 5, 6],
  98. // [7, 8, 9]],
  99. //
  100. // [[1, 2, 3],
  101. // [4, 5, 6],
  102. // [7, 8, 9]]])
  103. var firstTensor = tf.convert_to_tensor(
  104. np.reshape(
  105. np.array<float>(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9),
  106. 3, 3, 3));
  107. //
  108. // np.array([0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0]).reshape(3,3,2)
  109. // array([[[0, 1],
  110. // [0, 1],
  111. // [0, 1]],
  112. //
  113. // [[0, 1],
  114. // [0, 0],
  115. // [1, 0]],
  116. //
  117. // [[1, 0],
  118. // [1, 0],
  119. // [1, 0]]])
  120. var secondTensor = tf.convert_to_tensor(
  121. np.reshape(
  122. np.array<float>(0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0),
  123. 3, 3, 2));
  124. var batchMul = tf.batch_matmul(firstTensor, secondTensor);
  125. var checkTensor = np.array<float>(0, 6, 0, 15, 0, 24, 3, 1, 6, 4, 9, 7, 6, 0, 15, 0, 24, 0);
  126. return with(tf.Session(), sess =>
  127. {
  128. var result = sess.run(batchMul);
  129. Console.WriteLine(result.ToString());
  130. //
  131. // ==> array([[[0, 6],
  132. // [0, 15],
  133. // [0, 24]],
  134. //
  135. // [[ 3, 1],
  136. // [ 6, 4],
  137. // [ 9, 7]],
  138. //
  139. // [[ 6, 0],
  140. // [15, 0],
  141. // [24, 0]]])
  142. return np.reshape(result, 18)
  143. .array_equal(checkTensor);
  144. });
  145. }
  146. public void PrepareData()
  147. {
  148. }
  149. public Graph ImportGraph()
  150. {
  151. throw new NotImplementedException();
  152. }
  153. public Graph BuildGraph()
  154. {
  155. throw new NotImplementedException();
  156. }
  157. public void Train(Session sess)
  158. {
  159. throw new NotImplementedException();
  160. }
  161. public void Predict(Session sess)
  162. {
  163. throw new NotImplementedException();
  164. }
  165. public void Test(Session sess)
  166. {
  167. throw new NotImplementedException();
  168. }
  169. }
  170. }