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

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

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