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

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