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.

BinaryTextClassification.cs 5.7 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using Tensorflow;
  5. using Newtonsoft.Json;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using NumSharp;
  9. using static Tensorflow.Python;
  10. namespace TensorFlowNET.Examples
  11. {
  12. /// <summary>
  13. /// This example classifies movie reviews as positive or negative using the text of the review.
  14. /// This is a binary—or two-class—classification, an important and widely applicable kind of machine learning problem.
  15. /// https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_text_classification.ipynb
  16. /// </summary>
  17. public class BinaryTextClassification : IExample
  18. {
  19. public bool Enabled { get; set; } = true;
  20. public string Name => "Binary Text Classification";
  21. public bool IsImportingGraph { get; set; } = true;
  22. string dir = "binary_text_classification";
  23. string dataFile = "imdb.zip";
  24. NDArray train_data, train_labels, test_data, test_labels;
  25. public bool Run()
  26. {
  27. PrepareData();
  28. Console.WriteLine($"Training entries: {train_data.len}, labels: {train_labels.len}");
  29. // A dictionary mapping words to an integer index
  30. var word_index = GetWordIndex();
  31. /*train_data = keras.preprocessing.sequence.pad_sequences(train_data,
  32. value: word_index["<PAD>"],
  33. padding: "post",
  34. maxlen: 256);
  35. test_data = keras.preprocessing.sequence.pad_sequences(test_data,
  36. value: word_index["<PAD>"],
  37. padding: "post",
  38. maxlen: 256);*/
  39. // input shape is the vocabulary count used for the movie reviews (10,000 words)
  40. int vocab_size = 10000;
  41. var model = keras.Sequential();
  42. var layer = keras.layers.Embedding(vocab_size, 16);
  43. model.add(layer);
  44. return false;
  45. }
  46. public void PrepareData()
  47. {
  48. Directory.CreateDirectory(dir);
  49. // get model file
  50. string url = $"https://github.com/SciSharp/TensorFlow.NET/raw/master/data/{dataFile}";
  51. Utility.Web.Download(url, dir, "imdb.zip");
  52. Utility.Compress.UnZip(Path.Join(dir, $"imdb.zip"), dir);
  53. // prepare training dataset
  54. var x_train = ReadData(Path.Join(dir, "x_train.txt"));
  55. var labels_train = ReadData(Path.Join(dir, "y_train.txt"));
  56. var indices_train = ReadData(Path.Join(dir, "indices_train.txt"));
  57. x_train = x_train[indices_train];
  58. labels_train = labels_train[indices_train];
  59. var x_test = ReadData(Path.Join(dir, "x_test.txt"));
  60. var labels_test = ReadData(Path.Join(dir, "y_test.txt"));
  61. var indices_test = ReadData(Path.Join(dir, "indices_test.txt"));
  62. x_test = x_test[indices_test];
  63. labels_test = labels_test[indices_test];
  64. // not completed
  65. var xs = x_train.hstack<string>(x_test);
  66. var labels = labels_train.hstack<int>(labels_test);
  67. var idx = x_train.size;
  68. var y_train = labels_train;
  69. var y_test = labels_test;
  70. // convert x_train
  71. train_data = new NDArray(np.int32, (x_train.size, 256));
  72. for (int i = 0; i < x_train.size; i++)
  73. train_data[i] = x_train[i].Data<string>(0).Split(',').Select(x => int.Parse(x)).ToArray();
  74. test_data = new NDArray(np.int32, (x_test.size, 256));
  75. for (int i = 0; i < x_test.size; i++)
  76. test_data[i] = x_test[i].Data<string>(0).Split(',').Select(x => int.Parse(x)).ToArray();
  77. train_labels = y_train;
  78. test_labels = y_test;
  79. }
  80. private NDArray ReadData(string file)
  81. {
  82. var lines = File.ReadAllLines(file);
  83. var nd = new NDArray(lines[0].StartsWith("[") ? typeof(string) : np.int32, new Shape(lines.Length));
  84. if (lines[0].StartsWith("["))
  85. {
  86. for (int i = 0; i < lines.Length; i++)
  87. {
  88. /*var matches = Regex.Matches(lines[i], @"\d+\s*");
  89. var data = new int[matches.Count];
  90. for (int j = 0; j < data.Length; j++)
  91. data[j] = Convert.ToInt32(matches[j].Value);
  92. nd[i] = data.ToArray();*/
  93. nd[i] = lines[i].Substring(1, lines[i].Length - 2).Replace(" ", string.Empty);
  94. }
  95. }
  96. else
  97. {
  98. for (int i = 0; i < lines.Length; i++)
  99. nd[i] = Convert.ToInt32(lines[i]);
  100. }
  101. return nd;
  102. }
  103. private Dictionary<string, int> GetWordIndex()
  104. {
  105. var result = new Dictionary<string, int>();
  106. var json = File.ReadAllText(Path.Join(dir, "imdb_word_index.json"));
  107. var dict = JsonConvert.DeserializeObject<Dictionary<string, int>>(json);
  108. dict.Keys.Select(k => result[k] = dict[k] + 3).ToList();
  109. result["<PAD>"] = 0;
  110. result["<START>"] = 1;
  111. result["<UNK>"] = 2; // unknown
  112. result["<UNUSED>"] = 3;
  113. return result;
  114. }
  115. public Graph ImportGraph()
  116. {
  117. throw new NotImplementedException();
  118. }
  119. public Graph BuildGraph()
  120. {
  121. throw new NotImplementedException();
  122. }
  123. public bool Train()
  124. {
  125. throw new NotImplementedException();
  126. }
  127. public bool Predict()
  128. {
  129. throw new NotImplementedException();
  130. }
  131. }
  132. }