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

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

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