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

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