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

6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. public bool UseSubset = true; // <----- set this true to use a limited subset of dbpedia
  28. private string dataDir = "text_classification";
  29. private string dataFileName = "dbpedia_csv.tar.gz";
  30. public string model_name = "vd_cnn"; // word_cnn | char_cnn | vd_cnn | word_rnn | att_rnn | rcnn
  31. private const string TRAIN_PATH = "text_classification/dbpedia_csv/train.csv";
  32. private const string SUBSET_PATH = "text_classification/dbpedia_csv/dbpedia_6400.csv";
  33. private const string TEST_PATH = "text_classification/dbpedia_csv/test.csv";
  34. private const int CHAR_MAX_LEN = 1014;
  35. private const int WORD_MAX_LEN = 1014;
  36. private const int NUM_CLASS = 14;
  37. private const int BATCH_SIZE = 64;
  38. private const int NUM_EPOCHS = 10;
  39. protected float loss_value = 0;
  40. public bool Run()
  41. {
  42. PrepareData();
  43. var graph = tf.Graph().as_default();
  44. return with(tf.Session(graph), sess =>
  45. {
  46. if (ImportGraph)
  47. return RunWithImportedGraph(sess, graph);
  48. else
  49. return RunWithBuiltGraph(sess, graph);
  50. });
  51. }
  52. protected virtual bool RunWithImportedGraph(Session sess, Graph graph)
  53. {
  54. var stopwatch = Stopwatch.StartNew();
  55. Console.WriteLine("Building dataset...");
  56. var path = UseSubset ? SUBSET_PATH : TRAIN_PATH;
  57. var (x, y, alphabet_size) = DataHelpers.build_char_dataset(path, model_name, CHAR_MAX_LEN, DataLimit = null, shuffle:!UseSubset);
  58. Console.WriteLine("\tDONE ");
  59. var (train_x, valid_x, train_y, valid_y) = train_test_split(x, y, test_size: 0.15f);
  60. Console.WriteLine("Training set size: " + train_x.len);
  61. Console.WriteLine("Test set size: " + valid_x.len);
  62. Console.WriteLine("Import graph...");
  63. var meta_file = model_name + ".meta";
  64. tf.train.import_meta_graph(Path.Join("graph", meta_file));
  65. Console.WriteLine("\tDONE " + stopwatch.Elapsed);
  66. sess.run(tf.global_variables_initializer());
  67. var train_batches = batch_iter(train_x, train_y, BATCH_SIZE, NUM_EPOCHS);
  68. var num_batches_per_epoch = (len(train_x) - 1) / BATCH_SIZE + 1;
  69. double max_accuracy = 0;
  70. Tensor is_training = graph.get_tensor_by_name("is_training:0");
  71. Tensor model_x = graph.get_tensor_by_name("x:0");
  72. Tensor model_y = graph.get_tensor_by_name("y:0");
  73. Tensor loss = graph.get_tensor_by_name("loss/value:0");
  74. Tensor optimizer = graph.get_tensor_by_name("loss/optimizer:0");
  75. Tensor global_step = graph.get_tensor_by_name("global_step:0");
  76. Tensor accuracy = graph.get_tensor_by_name("accuracy/value:0");
  77. stopwatch = Stopwatch.StartNew();
  78. int i = 0;
  79. foreach (var (x_batch, y_batch, total) in train_batches)
  80. {
  81. i++;
  82. var train_feed_dict = new Hashtable
  83. {
  84. [model_x] = x_batch,
  85. [model_y] = y_batch,
  86. [is_training] = true,
  87. };
  88. //Console.WriteLine("x: " + x_batch.ToString() + "\n");
  89. //Console.WriteLine("y: " + y_batch.ToString());
  90. // original python:
  91. //_, step, loss = sess.run([model.optimizer, model.global_step, model.loss], feed_dict = train_feed_dict)
  92. var result = sess.run(new ITensorOrOperation[] { optimizer, global_step, loss }, train_feed_dict);
  93. loss_value = result[2];
  94. var step = (int)result[1];
  95. if (step % 10 == 0 || step < 10)
  96. {
  97. var estimate = TimeSpan.FromSeconds((stopwatch.Elapsed.TotalSeconds / i) * total);
  98. Console.WriteLine($"Training on batch {i}/{total}. Estimated training time: {estimate}");
  99. Console.WriteLine($"Step {step} loss: {loss_value}");
  100. }
  101. if (step % 100 == 0)
  102. {
  103. continue;
  104. // # Test accuracy with validation data for each epoch.
  105. var valid_batches = batch_iter(valid_x, valid_y, BATCH_SIZE, 1);
  106. var (sum_accuracy, cnt) = (0, 0);
  107. foreach (var (valid_x_batch, valid_y_batch, total_validation_batches) in valid_batches)
  108. {
  109. // valid_feed_dict = {
  110. // model.x: valid_x_batch,
  111. // model.y: valid_y_batch,
  112. // model.is_training: False
  113. // }
  114. // accuracy = sess.run(model.accuracy, feed_dict = valid_feed_dict)
  115. // sum_accuracy += accuracy
  116. // cnt += 1
  117. }
  118. // valid_accuracy = sum_accuracy / cnt
  119. // print("\nValidation Accuracy = {1}\n".format(step // num_batches_per_epoch, sum_accuracy / cnt))
  120. // # Save model
  121. // if valid_accuracy > max_accuracy:
  122. // max_accuracy = valid_accuracy
  123. // saver.save(sess, "{0}/{1}.ckpt".format(args.model, args.model), global_step = step)
  124. // print("Model is saved.\n")
  125. }
  126. }
  127. return false;
  128. }
  129. protected virtual bool RunWithBuiltGraph(Session session, Graph graph)
  130. {
  131. Console.WriteLine("Building dataset...");
  132. var (x, y, alphabet_size) = DataHelpers.build_char_dataset("train", model_name, CHAR_MAX_LEN, DataLimit);
  133. var (train_x, valid_x, train_y, valid_y) = train_test_split(x, y, test_size: 0.15f);
  134. ITextClassificationModel model = null;
  135. switch (model_name) // word_cnn | char_cnn | vd_cnn | word_rnn | att_rnn | rcnn
  136. {
  137. case "word_cnn":
  138. case "char_cnn":
  139. case "word_rnn":
  140. case "att_rnn":
  141. case "rcnn":
  142. throw new NotImplementedException();
  143. break;
  144. case "vd_cnn":
  145. model = new VdCnn(alphabet_size, CHAR_MAX_LEN, NUM_CLASS);
  146. break;
  147. }
  148. // todo train the model
  149. return false;
  150. }
  151. // TODO: this originally is an SKLearn utility function. it randomizes train and test which we don't do here
  152. private (NDArray, NDArray, NDArray, NDArray) train_test_split(NDArray x, NDArray y, float test_size = 0.3f)
  153. {
  154. Console.WriteLine("Splitting in Training and Testing data...");
  155. int len = x.shape[0];
  156. //int classes = y.Data<int>().Distinct().Count();
  157. //int samples = len / classes;
  158. int train_size = (int)Math.Round(len * (1 - test_size));
  159. var train_x = x[new Slice(stop: train_size), new Slice()];
  160. var valid_x = x[new Slice(start: train_size + 1), new Slice()];
  161. var train_y = y[new Slice(stop: train_size)];
  162. var valid_y = y[new Slice(start: train_size + 1)];
  163. Console.WriteLine("\tDONE");
  164. return (train_x, valid_x, train_y, valid_y);
  165. }
  166. //private (int[][], int[][], int[], int[]) train_test_split(int[][] x, int[] y, float test_size = 0.3f)
  167. //{
  168. // Console.WriteLine("Splitting in Training and Testing data...");
  169. // var stopwatch = Stopwatch.StartNew();
  170. // int len = x.Length;
  171. // int train_size = int.Parse((len * (1 - test_size)).ToString());
  172. // var random = new Random(17);
  173. // // we collect indices of labels
  174. // var labels = new Dictionary<int, HashSet<int>>();
  175. // var shuffled_indices = random.Shuffle<int>(range(len).ToArray());
  176. // foreach (var i in shuffled_indices)
  177. // {
  178. // var label = y[i];
  179. // if (!labels.ContainsKey(i))
  180. // labels[label] = new HashSet<int>();
  181. // labels[label].Add(i);
  182. // }
  183. // var train_x = new int[train_size][];
  184. // var valid_x = new int[len - train_size][];
  185. // var train_y = new int[train_size];
  186. // var valid_y = new int[len - train_size];
  187. // FillWithShuffledLabels(x, y, train_x, train_y, random, labels);
  188. // FillWithShuffledLabels(x, y, valid_x, valid_y, random, labels);
  189. // Console.WriteLine("\tDONE " + stopwatch.Elapsed);
  190. // return (train_x, valid_x, train_y, valid_y);
  191. //}
  192. private static void FillWithShuffledLabels(int[][] x, int[] y, int[][] shuffled_x, int[] shuffled_y, Random random, Dictionary<int, HashSet<int>> labels)
  193. {
  194. int i = 0;
  195. var label_keys = labels.Keys.ToArray();
  196. while (i < shuffled_x.Length)
  197. {
  198. var key = label_keys[random.Next(label_keys.Length)];
  199. var set = labels[key];
  200. var index = set.First();
  201. if (set.Count == 0)
  202. {
  203. labels.Remove(key); // remove the set as it is empty
  204. label_keys = labels.Keys.ToArray();
  205. }
  206. shuffled_x[i] = x[index];
  207. shuffled_y[i] = y[index];
  208. i++;
  209. }
  210. }
  211. private IEnumerable<(NDArray, NDArray, int)> batch_iter(NDArray inputs, NDArray outputs, int batch_size, int num_epochs)
  212. {
  213. var num_batches_per_epoch = (len(inputs) - 1) / batch_size + 1;
  214. var total_batches = num_batches_per_epoch * num_epochs;
  215. foreach (var epoch in range(num_epochs))
  216. {
  217. foreach (var batch_num in range(num_batches_per_epoch))
  218. {
  219. var start_index = batch_num * batch_size;
  220. var end_index = Math.Min((batch_num + 1) * batch_size, len(inputs));
  221. if (end_index <= start_index)
  222. break;
  223. yield return (inputs[new Slice(start_index, end_index)], outputs[new Slice(start_index, end_index)], total_batches);
  224. }
  225. }
  226. }
  227. public void PrepareData()
  228. {
  229. if (UseSubset)
  230. {
  231. var url = "https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/data/dbpedia_subset.zip";
  232. Web.Download(url, dataDir, "dbpedia_subset.zip");
  233. Compress.UnZip(Path.Combine(dataDir, "dbpedia_subset.zip"), Path.Combine(dataDir, "dbpedia_csv"));
  234. }
  235. else
  236. {
  237. string url = "https://github.com/le-scientifique/torchDatasets/raw/master/dbpedia_csv.tar.gz";
  238. Web.Download(url, dataDir, dataFileName);
  239. Compress.ExtractTGZ(Path.Join(dataDir, dataFileName), dataDir);
  240. }
  241. if (ImportGraph)
  242. {
  243. // download graph meta data
  244. var meta_file = model_name + ".meta";
  245. var meta_path = Path.Combine("graph", meta_file);
  246. if (File.GetLastWriteTime(meta_path) < new DateTime(2019, 05, 11))
  247. {
  248. // delete old cached file which contains errors
  249. Console.WriteLine("Discarding cached file: " + meta_path);
  250. File.Delete(meta_path);
  251. }
  252. var url = "https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/graph/" + meta_file;
  253. Web.Download(url, "graph", meta_file);
  254. }
  255. }
  256. }
  257. }

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