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

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. using Newtonsoft.Json;
  2. using NumSharp.Core;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using Tensorflow;
  9. using TensorFlowNET.Examples.Utility;
  10. namespace TensorFlowNET.Examples
  11. {
  12. /// <summary>
  13. /// A logistic regression learning algorithm example using TensorFlow library.
  14. /// This example is using the MNIST database of handwritten digits
  15. /// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/logistic_regression.py
  16. /// </summary>
  17. public class LogisticRegression : Python, IExample
  18. {
  19. public bool Enabled => true;
  20. private float learning_rate = 0.01f;
  21. private int training_epochs = 10;
  22. private int batch_size = 100;
  23. private int display_step = 1;
  24. Datasets mnist;
  25. public bool Run()
  26. {
  27. PrepareData();
  28. // tf Graph Input
  29. var x = tf.placeholder(tf.float32, new TensorShape(-1, 784)); // mnist data image of shape 28*28=784
  30. var y = tf.placeholder(tf.float32, new TensorShape(-1, 10)); // 0-9 digits recognition => 10 classes
  31. // Set model weights
  32. var W = tf.Variable(tf.zeros(new Shape(784, 10)));
  33. var b = tf.Variable(tf.zeros(new Shape(10)));
  34. // Construct model
  35. var pred = tf.nn.softmax(tf.matmul(x, W) + b); // Softmax
  36. // Minimize error using cross entropy
  37. var cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices: 1));
  38. // Gradient Descent
  39. var optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost);
  40. // Initialize the variables (i.e. assign their default value)
  41. var init = tf.global_variables_initializer();
  42. return with(tf.Session(), sess =>
  43. {
  44. // Run the initializer
  45. sess.run(init);
  46. // Training cycle
  47. foreach (var epoch in range(training_epochs))
  48. {
  49. var avg_cost = 0.0f;
  50. var total_batch = mnist.train.num_examples / batch_size;
  51. // Loop over all batches
  52. foreach (var i in range(total_batch))
  53. {
  54. var (batch_xs, batch_ys) = mnist.train.next_batch(batch_size);
  55. // Run optimization op (backprop) and cost op (to get loss value)
  56. var result = sess.run(new object[] { optimizer, cost },
  57. new FeedItem(x, batch_xs),
  58. new FeedItem(y, batch_ys));
  59. var c = (float)result[1];
  60. // Compute average loss
  61. avg_cost += c / total_batch;
  62. }
  63. // Display logs per epoch step
  64. if ((epoch + 1) % display_step == 0)
  65. print($"Epoch: {(epoch + 1).ToString("D4")} cost= {avg_cost.ToString("G9")}");
  66. }
  67. print("Optimization Finished!");
  68. // SaveModel(sess);
  69. // Test model
  70. var correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1));
  71. // Calculate accuracy
  72. var accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32));
  73. float acc = accuracy.eval(new FeedItem(x, mnist.test.images), new FeedItem(y, mnist.test.labels));
  74. print($"Accuracy: {acc.ToString("F4")}");
  75. return acc > 0.9;
  76. });
  77. }
  78. public void PrepareData()
  79. {
  80. mnist = MnistDataSet.read_data_sets("logistic_regression", one_hot: true);
  81. }
  82. public void SaveModel(Session sess)
  83. {
  84. var saver = tf.train.Saver();
  85. var save_path = saver.save(sess, "logistic_regression/model.ckpt");
  86. tf.train.write_graph(sess.graph, "logistic_regression", "model.pbtxt", as_text: true);
  87. FreezeGraph.freeze_graph(input_graph: "logistic_regression/model.pbtxt",
  88. input_saver: "",
  89. input_binary: false,
  90. input_checkpoint: "logistic_regression/model.ckpt",
  91. output_node_names: "Softmax",
  92. restore_op_name: "save/restore_all",
  93. filename_tensor_name: "save/Const:0",
  94. output_graph: "logistic_regression/model.pb",
  95. clear_devices: true,
  96. initializer_nodes: "");
  97. }
  98. public void Predict()
  99. {
  100. var graph = new Graph().as_default();
  101. graph.Import(Path.Join("logistic_regression", "model.pb"));
  102. with(tf.Session(graph), sess =>
  103. {
  104. // restoring the model
  105. // var saver = tf.train.import_meta_graph("logistic_regression/tensorflowModel.ckpt.meta");
  106. // saver.restore(sess, tf.train.latest_checkpoint('logistic_regression'));
  107. var pred = graph.OperationByName("Softmax");
  108. var output = pred.outputs[0];
  109. var x = graph.OperationByName("Placeholder");
  110. var input = x.outputs[0];
  111. // predict
  112. var (batch_xs, batch_ys) = mnist.train.next_batch(10);
  113. var results = sess.run(output, new FeedItem(input, batch_xs[np.arange(1)]));
  114. if (results.argmax() == (batch_ys[0] as NDArray).argmax())
  115. print("predicted OK!");
  116. else
  117. throw new ValueError("predict error, maybe 90% accuracy");
  118. });
  119. }
  120. }
  121. }

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