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.

CnnTextClassification.cs 10 kB

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