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.

TextClassificationTrain.cs 9.4 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using NumSharp;
  9. using Tensorflow;
  10. using Tensorflow.Keras.Engine;
  11. using TensorFlowNET.Examples.Text.cnn_models;
  12. using TensorFlowNET.Examples.TextClassification;
  13. using TensorFlowNET.Examples.Utility;
  14. using static Tensorflow.Python;
  15. namespace TensorFlowNET.Examples.CnnTextClassification
  16. {
  17. /// <summary>
  18. /// https://github.com/dongjun-Lee/text-classification-models-tf
  19. /// </summary>
  20. public class TextClassificationTrain : IExample
  21. {
  22. public int Priority => 100;
  23. public bool Enabled { get; set; } = false;
  24. public string Name => "Text Classification";
  25. public int? DataLimit = null;
  26. public bool ImportGraph { get; set; } = true;
  27. private string dataDir = "text_classification";
  28. private string dataFileName = "dbpedia_csv.tar.gz";
  29. public string model_name = "vd_cnn"; // word_cnn | char_cnn | vd_cnn | word_rnn | att_rnn | rcnn
  30. private const int CHAR_MAX_LEN = 1014;
  31. private const int NUM_CLASS = 2;
  32. private const int BATCH_SIZE = 64;
  33. private const int NUM_EPOCHS = 10;
  34. protected float loss_value = 0;
  35. public bool Run()
  36. {
  37. PrepareData();
  38. var graph = tf.Graph().as_default();
  39. return with(tf.Session(graph), sess =>
  40. {
  41. if (ImportGraph)
  42. return RunWithImportedGraph(sess, graph);
  43. else
  44. return RunWithBuiltGraph(sess, graph);
  45. });
  46. }
  47. protected virtual bool RunWithImportedGraph(Session sess, Graph graph)
  48. {
  49. var stopwatch = Stopwatch.StartNew();
  50. Console.WriteLine("Building dataset...");
  51. var (x, y, alphabet_size) = DataHelpers.build_char_dataset("train", model_name, CHAR_MAX_LEN, DataLimit=null);
  52. Console.WriteLine("\tDONE ");
  53. var (train_x, valid_x, train_y, valid_y) = train_test_split(x, y, test_size: 0.15f);
  54. Console.WriteLine("Import graph...");
  55. var meta_file = model_name + ".meta";
  56. tf.train.import_meta_graph(Path.Join("graph", meta_file));
  57. Console.WriteLine("\tDONE " + stopwatch.Elapsed);
  58. sess.run(tf.global_variables_initializer());
  59. var train_batches = batch_iter(train_x, train_y, BATCH_SIZE, NUM_EPOCHS);
  60. var num_batches_per_epoch = (len(train_x) - 1) / BATCH_SIZE + 1;
  61. double max_accuracy = 0;
  62. Tensor is_training = graph.get_operation_by_name("is_training");
  63. Tensor model_x = graph.get_operation_by_name("x");
  64. Tensor model_y = graph.get_operation_by_name("y");
  65. Tensor loss = graph.get_operation_by_name("loss/value");
  66. //var optimizer_nodes = graph._nodes_by_name.Keys.Where(key => key.Contains("optimizer")).ToArray();
  67. Tensor optimizer = graph.get_operation_by_name("loss/optimizer");
  68. Tensor global_step = graph.get_operation_by_name("global_step");
  69. Tensor accuracy = graph.get_operation_by_name("accuracy/value");
  70. stopwatch = Stopwatch.StartNew();
  71. int i = 0;
  72. foreach (var (x_batch, y_batch, total) in train_batches)
  73. {
  74. i++;
  75. var train_feed_dict = new Hashtable
  76. {
  77. [model_x] = x_batch,
  78. [model_y] = y_batch,
  79. [is_training] = true,
  80. };
  81. // original python:
  82. //_, step, loss = sess.run([model.optimizer, model.global_step, model.loss], feed_dict = train_feed_dict)
  83. var result = sess.run(new ITensorOrOperation[] { optimizer, global_step, loss }, train_feed_dict);
  84. //loss_value = result[2];
  85. var step = result[1];
  86. if (step % 10 == 0)
  87. {
  88. var estimate = TimeSpan.FromSeconds((stopwatch.Elapsed.TotalSeconds / i) * total);
  89. Console.WriteLine($"Training on batch {i}/{total}. Estimated training time: {estimate}");
  90. Console.WriteLine($"Step {step} loss: {result[2]}");
  91. }
  92. if (step % 100 == 0)
  93. {
  94. continue;
  95. // # Test accuracy with validation data for each epoch.
  96. var valid_batches = batch_iter(valid_x, valid_y, BATCH_SIZE, 1);
  97. var (sum_accuracy, cnt) = (0, 0);
  98. foreach (var (valid_x_batch, valid_y_batch, total_validation_batches) in valid_batches)
  99. {
  100. // valid_feed_dict = {
  101. // model.x: valid_x_batch,
  102. // model.y: valid_y_batch,
  103. // model.is_training: False
  104. // }
  105. // accuracy = sess.run(model.accuracy, feed_dict = valid_feed_dict)
  106. // sum_accuracy += accuracy
  107. // cnt += 1
  108. }
  109. // valid_accuracy = sum_accuracy / cnt
  110. // print("\nValidation Accuracy = {1}\n".format(step // num_batches_per_epoch, sum_accuracy / cnt))
  111. // # Save model
  112. // if valid_accuracy > max_accuracy:
  113. // max_accuracy = valid_accuracy
  114. // saver.save(sess, "{0}/{1}.ckpt".format(args.model, args.model), global_step = step)
  115. // print("Model is saved.\n")
  116. }
  117. }
  118. return false;
  119. }
  120. protected virtual bool RunWithBuiltGraph(Session session, Graph graph)
  121. {
  122. Console.WriteLine("Building dataset...");
  123. var (x, y, alphabet_size) = DataHelpers.build_char_dataset("train", model_name, CHAR_MAX_LEN, DataLimit);
  124. var (train_x, valid_x, train_y, valid_y) = train_test_split(x, y, test_size: 0.15f);
  125. ITextClassificationModel model = null;
  126. switch (model_name) // word_cnn | char_cnn | vd_cnn | word_rnn | att_rnn | rcnn
  127. {
  128. case "word_cnn":
  129. case "char_cnn":
  130. case "word_rnn":
  131. case "att_rnn":
  132. case "rcnn":
  133. throw new NotImplementedException();
  134. break;
  135. case "vd_cnn":
  136. model = new VdCnn(alphabet_size, CHAR_MAX_LEN, NUM_CLASS);
  137. break;
  138. }
  139. // todo train the model
  140. return false;
  141. }
  142. // TODO: this originally is an SKLearn utility function. it randomizes train and test which we don't do here
  143. private (NDArray, NDArray, NDArray, NDArray) train_test_split(NDArray x, NDArray y, float test_size = 0.3f)
  144. {
  145. Console.WriteLine("Splitting in Training and Testing data...");
  146. int len = x.shape[0];
  147. //int classes = y.Data<int>().Distinct().Count();
  148. //int samples = len / classes;
  149. int train_size = (int)Math.Round(len * (1 - test_size));
  150. var train_x = x[new Slice(stop:train_size), new Slice()];
  151. var valid_x = x[new Slice(start: train_size+1), new Slice()];
  152. var train_y = y[new Slice(stop: train_size)];
  153. var valid_y = y[new Slice(start: train_size + 1)];
  154. Console.WriteLine("\tDONE");
  155. return (train_x, valid_x, train_y, valid_y);
  156. }
  157. private IEnumerable<(NDArray, NDArray, int)> batch_iter(NDArray inputs, NDArray outputs, int batch_size, int num_epochs)
  158. {
  159. var num_batches_per_epoch = (len(inputs) - 1) / batch_size;
  160. var total_batches = num_batches_per_epoch * num_epochs;
  161. foreach (var epoch in range(num_epochs))
  162. {
  163. foreach (var batch_num in range(num_batches_per_epoch))
  164. {
  165. var start_index = batch_num * batch_size;
  166. var end_index = Math.Min((batch_num + 1) * batch_size, len(inputs));
  167. if (end_index <= start_index)
  168. break;
  169. yield return (inputs[new Slice(start_index, end_index)], outputs[new Slice(start_index,end_index)], total_batches);
  170. }
  171. }
  172. }
  173. public void PrepareData()
  174. {
  175. string url = "https://github.com/le-scientifique/torchDatasets/raw/master/dbpedia_csv.tar.gz";
  176. Web.Download(url, dataDir, dataFileName);
  177. Compress.ExtractTGZ(Path.Join(dataDir, dataFileName), dataDir);
  178. if (ImportGraph)
  179. {
  180. // download graph meta data
  181. var meta_file = model_name + ".meta";
  182. if (File.GetLastWriteTime(meta_file) < new DateTime(2019,05,11)) // delete old cached file which contains errors
  183. File.Delete(meta_file);
  184. url = "https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/graph/" + meta_file;
  185. Web.Download(url, "graph", meta_file);
  186. }
  187. }
  188. }
  189. }

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