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.

LogisticRegression.cs 7.4 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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.Diagnostics;
  16. using System.IO;
  17. using Tensorflow;
  18. using Tensorflow.Hub;
  19. using static Tensorflow.Binding;
  20. namespace TensorFlowNET.Examples
  21. {
  22. /// <summary>
  23. /// A logistic regression learning algorithm example using TensorFlow library.
  24. /// This example is using the MNIST database of handwritten digits
  25. /// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/logistic_regression.py
  26. /// </summary>
  27. public class LogisticRegression : IExample
  28. {
  29. public bool Enabled { get; set; } = true;
  30. public string Name => "Logistic Regression";
  31. public bool IsImportingGraph { get; set; } = false;
  32. public int training_epochs = 10;
  33. public int? train_size = null;
  34. public int validation_size = 5000;
  35. public int? test_size = null;
  36. public int batch_size = 100;
  37. private float learning_rate = 0.01f;
  38. private int display_step = 1;
  39. Datasets<MnistDataSet> mnist;
  40. public bool Run()
  41. {
  42. PrepareData();
  43. // tf Graph Input
  44. var x = tf.placeholder(tf.float32, new TensorShape(-1, 784)); // mnist data image of shape 28*28=784
  45. var y = tf.placeholder(tf.float32, new TensorShape(-1, 10)); // 0-9 digits recognition => 10 classes
  46. // Set model weights
  47. var W = tf.Variable(tf.zeros(new Shape(784, 10)));
  48. var b = tf.Variable(tf.zeros(new Shape(10)));
  49. // Construct model
  50. var pred = tf.nn.softmax(tf.matmul(x, W) + b); // Softmax
  51. // Minimize error using cross entropy
  52. var cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices: 1));
  53. // Gradient Descent
  54. var optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost);
  55. // Initialize the variables (i.e. assign their default value)
  56. var init = tf.global_variables_initializer();
  57. var sw = new Stopwatch();
  58. using (var sess = tf.Session())
  59. {
  60. // Run the initializer
  61. sess.run(init);
  62. // Training cycle
  63. foreach (var epoch in range(training_epochs))
  64. {
  65. sw.Start();
  66. var avg_cost = 0.0f;
  67. var total_batch = mnist.Train.NumOfExamples / batch_size;
  68. // Loop over all batches
  69. foreach (var i in range(total_batch))
  70. {
  71. var (batch_xs, batch_ys) = mnist.Train.GetNextBatch(batch_size);
  72. // Run optimization op (backprop) and cost op (to get loss value)
  73. (_, float c) = sess.run((optimizer, cost),
  74. (x, batch_xs),
  75. (y, batch_ys));
  76. // Compute average loss
  77. avg_cost += c / total_batch;
  78. }
  79. sw.Stop();
  80. // Display logs per epoch step
  81. if ((epoch + 1) % display_step == 0)
  82. print($"Epoch: {(epoch + 1).ToString("D4")} Cost: {avg_cost.ToString("G9")} Elapse: {sw.ElapsedMilliseconds}ms");
  83. sw.Reset();
  84. }
  85. print("Optimization Finished!");
  86. // SaveModel(sess);
  87. // Test model
  88. var correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1));
  89. // Calculate accuracy
  90. var accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32));
  91. float acc = accuracy.eval((x, mnist.Test.Data), (y, mnist.Test.Labels));
  92. print($"Accuracy: {acc.ToString("F4")}");
  93. return acc > 0.9;
  94. }
  95. }
  96. public void PrepareData()
  97. {
  98. mnist = MnistModelLoader.LoadAsync(".resources/mnist", oneHot: true, trainSize: train_size, validationSize: validation_size, testSize: test_size, showProgressInConsole: true).Result;
  99. }
  100. public void SaveModel(Session sess)
  101. {
  102. var saver = tf.train.Saver();
  103. var save_path = saver.save(sess, ".resources/logistic_regression/model.ckpt");
  104. tf.train.write_graph(sess.graph, ".resources/logistic_regression", "model.pbtxt", as_text: true);
  105. FreezeGraph.freeze_graph(input_graph: ".resources/logistic_regression/model.pbtxt",
  106. input_saver: "",
  107. input_binary: false,
  108. input_checkpoint: ".resources/logistic_regression/model.ckpt",
  109. output_node_names: "Softmax",
  110. restore_op_name: "save/restore_all",
  111. filename_tensor_name: "save/Const:0",
  112. output_graph: ".resources/logistic_regression/model.pb",
  113. clear_devices: true,
  114. initializer_nodes: "");
  115. }
  116. public void Predict(Session sess)
  117. {
  118. var graph = new Graph().as_default();
  119. graph.Import(Path.Join(".resources/logistic_regression", "model.pb"));
  120. // restoring the model
  121. // var saver = tf.train.import_meta_graph("logistic_regression/tensorflowModel.ckpt.meta");
  122. // saver.restore(sess, tf.train.latest_checkpoint('logistic_regression'));
  123. var pred = graph.OperationByName("Softmax");
  124. var output = pred.outputs[0];
  125. var x = graph.OperationByName("Placeholder");
  126. var input = x.outputs[0];
  127. // predict
  128. var (batch_xs, batch_ys) = mnist.Train.GetNextBatch(10);
  129. var results = sess.run(output, new FeedItem(input, batch_xs[np.arange(1)]));
  130. if (results[0].argmax() == (batch_ys[0] as NDArray).argmax())
  131. print("predicted OK!");
  132. else
  133. throw new ValueError("predict error, should be 90% accuracy");
  134. }
  135. public Graph ImportGraph()
  136. {
  137. throw new NotImplementedException();
  138. }
  139. public Graph BuildGraph()
  140. {
  141. throw new NotImplementedException();
  142. }
  143. public void Train(Session sess)
  144. {
  145. throw new NotImplementedException();
  146. }
  147. public void Test(Session sess)
  148. {
  149. throw new NotImplementedException();
  150. }
  151. }
  152. }