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