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

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

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