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.

FullyConnected.cs 5.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. /*****************************************************************************
  2. Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using NumSharp;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. using System.Text;
  18. using Tensorflow;
  19. using static Tensorflow.Binding;
  20. namespace TensorFlowNET.Examples
  21. {
  22. /// <summary>
  23. /// How to optimise your input pipeline with queues and multi-threading
  24. /// https://blog.metaflow.fr/tensorflow-how-to-optimise-your-input-pipeline-with-queues-and-multi-threading-e7c3874157e0
  25. /// </summary>
  26. public class FullyConnected : IExample
  27. {
  28. public bool Enabled { get; set; } = true;
  29. public bool IsImportingGraph { get; set; }
  30. public string Name => "Fully Connected Neural Network";
  31. Tensor input = null;
  32. Tensor x_inputs_data = null;
  33. Tensor y_inputs_data = null;
  34. Tensor accuracy = null;
  35. Tensor y_true = null;
  36. Tensor loss_op = null;
  37. Operation train_op = null;
  38. public Graph BuildGraph()
  39. {
  40. var g = tf.get_default_graph();
  41. Tensor z = null;
  42. tf_with(tf.variable_scope("placeholder"), delegate
  43. {
  44. input = tf.placeholder(tf.float32, shape: (-1, 1024));
  45. y_true = tf.placeholder(tf.int32, shape: (-1, 1));
  46. });
  47. tf_with(tf.variable_scope("FullyConnected"), delegate
  48. {
  49. var w = tf.get_variable("w", shape: (1024, 1024), initializer: tf.random_normal_initializer(stddev: 0.1f));
  50. var b = tf.get_variable("b", shape: 1024, initializer: tf.constant_initializer(0.1));
  51. z = tf.matmul(input, w) + b;
  52. var y = tf.nn.relu(z);
  53. var w2 = tf.get_variable("w2", shape: (1024, 1), initializer: tf.random_normal_initializer(stddev: 0.1f));
  54. var b2 = tf.get_variable("b2", shape: 1, initializer: tf.constant_initializer(0.1));
  55. z = tf.matmul(y, w2) + b2;
  56. });
  57. tf_with(tf.variable_scope("Loss"), delegate
  58. {
  59. var losses = tf.nn.sigmoid_cross_entropy_with_logits(tf.cast(y_true, tf.float32), z);
  60. loss_op = tf.reduce_mean(losses);
  61. });
  62. tf_with(tf.variable_scope("Accuracy"), delegate
  63. {
  64. var y_pred = tf.cast(z > 0, tf.int32);
  65. accuracy = tf.reduce_mean(tf.cast(tf.equal(y_pred, y_true), tf.float32));
  66. // accuracy = tf.Print(accuracy, data =[accuracy], message = "accuracy:")
  67. });
  68. // We add the training operation, ...
  69. var adam = tf.train.AdamOptimizer(0.01f);
  70. train_op = adam.minimize(loss_op, name: "train_op");
  71. return g;
  72. }
  73. public Graph ImportGraph()
  74. {
  75. throw new NotImplementedException();
  76. }
  77. public void Predict(Session sess)
  78. {
  79. throw new NotImplementedException();
  80. }
  81. public void PrepareData()
  82. {
  83. // batches of 128 samples, each containing 1024 data points
  84. x_inputs_data = tf.random_normal(new[] { 128, 1024 }, mean: 0, stddev: 1);
  85. // We will try to predict this law:
  86. // predict 1 if the sum of the elements is positive and 0 otherwise
  87. y_inputs_data = tf.cast(tf.reduce_sum(x_inputs_data, axis: 1, keepdims: true) > 0, tf.int32);
  88. }
  89. public bool Run()
  90. {
  91. PrepareData();
  92. var g = BuildGraph();
  93. using (var sess = tf.Session())
  94. Train(sess);
  95. return true;
  96. }
  97. public void Test(Session sess)
  98. {
  99. throw new NotImplementedException();
  100. }
  101. public void Train(Session sess)
  102. {
  103. var sw = new Stopwatch();
  104. sw.Start();
  105. // init variables
  106. sess.run(tf.global_variables_initializer());
  107. // check the accuracy before training
  108. var (x_input, y_input) = sess.run((x_inputs_data, y_inputs_data));
  109. sess.run(accuracy, (input, x_input), (y_true, y_input));
  110. // training
  111. foreach (var i in range(5000))
  112. {
  113. // by sampling some input data (fetching)
  114. (x_input, y_input) = sess.run((x_inputs_data, y_inputs_data));
  115. var (_, loss) = sess.run((train_op, loss_op), (input, x_input), (y_true, y_input));
  116. // We regularly check the loss
  117. if (i % 500 == 0)
  118. print($"iter:{i} - loss:{loss}");
  119. }
  120. // Finally, we check our final accuracy
  121. (x_input, y_input) = sess.run((x_inputs_data, y_inputs_data));
  122. sess.run(accuracy, (input, x_input), (y_true, y_input));
  123. print($"Time taken: {sw.Elapsed.TotalSeconds}s");
  124. }
  125. }
  126. }