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.

DataHelpers.cs 7.5 kB

6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using NumSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using TensorFlowNET.Examples.Utility;
  10. namespace TensorFlowNET.Examples
  11. {
  12. public class DataHelpers
  13. {
  14. public static (int[][], int[], int) build_char_dataset(string path, string model, int document_max_len, int? limit = null, bool shuffle=true)
  15. {
  16. if (model != "vd_cnn")
  17. throw new NotImplementedException(model);
  18. string alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:’'\"/|_#$%ˆ&*˜‘+=<>()[]{} ";
  19. /*if (step == "train")
  20. df = pd.read_csv(TRAIN_PATH, names =["class", "title", "content"]);*/
  21. var char_dict = new Dictionary<string, int>();
  22. char_dict["<pad>"] = 0;
  23. char_dict["<unk>"] = 1;
  24. foreach (char c in alphabet)
  25. char_dict[c.ToString()] = char_dict.Count;
  26. var contents = File.ReadAllLines(path);
  27. if (shuffle)
  28. new Random(17).Shuffle(contents);
  29. //File.WriteAllLines("text_classification/dbpedia_csv/train_6400.csv", contents.Take(6400));
  30. var size = limit == null ? contents.Length : limit.Value;
  31. var x = new int[size][];
  32. var y = new int[size];
  33. var tenth = size / 10;
  34. var percent = 0;
  35. for (int i = 0; i < size; i++)
  36. {
  37. if ((i + 1) % tenth == 0)
  38. {
  39. percent += 10;
  40. Console.WriteLine($"\t{percent}%");
  41. }
  42. string[] parts = contents[i].ToLower().Split(",\"").ToArray();
  43. string content = parts[2];
  44. content = content.Substring(0, content.Length - 1);
  45. var a = new int[document_max_len];
  46. for (int j = 0; j < document_max_len; j++)
  47. {
  48. if (j >= content.Length)
  49. a[j] = char_dict["<pad>"];
  50. else
  51. a[j] = char_dict.ContainsKey(content[j].ToString()) ? char_dict[content[j].ToString()] : char_dict["<unk>"];
  52. }
  53. x[i] = a;
  54. y[i] = int.Parse(parts[0]);
  55. }
  56. return (x, y, alphabet.Length + 2);
  57. }
  58. /// <summary>
  59. /// Loads MR polarity data from files, splits the data into words and generates labels.
  60. /// Returns split sentences and labels.
  61. /// </summary>
  62. /// <param name="positive_data_file"></param>
  63. /// <param name="negative_data_file"></param>
  64. /// <returns></returns>
  65. public static (string[], NDArray) load_data_and_labels(string positive_data_file, string negative_data_file)
  66. {
  67. Directory.CreateDirectory("CnnTextClassification");
  68. Utility.Web.Download(positive_data_file, "CnnTextClassification", "rt -polarity.pos");
  69. Utility.Web.Download(negative_data_file, "CnnTextClassification", "rt-polarity.neg");
  70. // Load data from files
  71. var positive_examples = File.ReadAllLines("CnnTextClassification/rt-polarity.pos")
  72. .Select(x => x.Trim())
  73. .ToArray();
  74. var negative_examples = File.ReadAllLines("CnnTextClassification/rt-polarity.neg")
  75. .Select(x => x.Trim())
  76. .ToArray();
  77. var x_text = new List<string>();
  78. x_text.AddRange(positive_examples);
  79. x_text.AddRange(negative_examples);
  80. x_text = x_text.Select(x => clean_str(x)).ToList();
  81. var positive_labels = positive_examples.Select(x => new int[2] { 0, 1 }).ToArray();
  82. var negative_labels = negative_examples.Select(x => new int[2] { 1, 0 }).ToArray();
  83. var y = np.concatenate(new int[][][] { positive_labels, negative_labels });
  84. return (x_text.ToArray(), y);
  85. }
  86. private static string clean_str(string str)
  87. {
  88. str = Regex.Replace(str, @"[^A-Za-z0-9(),!?\'\`]", " ");
  89. str = Regex.Replace(str, @"\'s", " \'s");
  90. return str;
  91. }
  92. /// <summary>
  93. /// Padding
  94. /// </summary>
  95. /// <param name="sequences"></param>
  96. /// <param name="pad_tok">the char to pad with</param>
  97. /// <returns>a list of list where each sublist has same length</returns>
  98. public static (int[][], int[]) pad_sequences(int[][] sequences, int pad_tok = 0)
  99. {
  100. int max_length = sequences.Select(x => x.Length).Max();
  101. return _pad_sequences(sequences, pad_tok, max_length);
  102. }
  103. public static (int[][][], int[][]) pad_sequences(int[][][] sequences, int pad_tok = 0)
  104. {
  105. int max_length_word = sequences.Select(x => x.Select(w => w.Length).Max()).Max();
  106. int[][][] sequence_padded;
  107. var sequence_length = new int[sequences.Length][];
  108. for (int i = 0; i < sequences.Length; i++)
  109. {
  110. // all words are same length now
  111. var (sp, sl) = _pad_sequences(sequences[i], pad_tok, max_length_word);
  112. sequence_length[i] = sl;
  113. }
  114. int max_length_sentence = sequences.Select(x => x.Length).Max();
  115. (sequence_padded, _) = _pad_sequences(sequences, np.repeat(pad_tok, max_length_word).Data<int>(), max_length_sentence);
  116. (sequence_length, _) = _pad_sequences(sequence_length, 0, max_length_sentence);
  117. return (sequence_padded, sequence_length);
  118. }
  119. private static (int[][], int[]) _pad_sequences(int[][] sequences, int pad_tok, int max_length)
  120. {
  121. var sequence_length = new int[sequences.Length];
  122. for (int i = 0; i < sequences.Length; i++)
  123. {
  124. sequence_length[i] = sequences[i].Length;
  125. Array.Resize(ref sequences[i], max_length);
  126. }
  127. return (sequences, sequence_length);
  128. }
  129. private static (int[][][], int[]) _pad_sequences(int[][][] sequences, int[] pad_tok, int max_length)
  130. {
  131. var sequence_length = new int[sequences.Length];
  132. for (int i = 0; i < sequences.Length; i++)
  133. {
  134. sequence_length[i] = sequences[i].Length;
  135. Array.Resize(ref sequences[i], max_length);
  136. for (int j = 0; j < max_length - sequence_length[i]; j++)
  137. {
  138. sequences[i][max_length - j - 1] = new int[pad_tok.Length];
  139. Array.Copy(pad_tok, sequences[i][max_length - j - 1], pad_tok.Length);
  140. }
  141. }
  142. return (sequences, sequence_length);
  143. }
  144. public static string CalculateMD5Hash(string input)
  145. {
  146. // step 1, calculate MD5 hash from input
  147. MD5 md5 = System.Security.Cryptography.MD5.Create();
  148. byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
  149. byte[] hash = md5.ComputeHash(inputBytes);
  150. // step 2, convert byte array to hex string
  151. StringBuilder sb = new StringBuilder();
  152. for (int i = 0; i < hash.Length; i++)
  153. {
  154. sb.Append(hash[i].ToString("X2"));
  155. }
  156. return sb.ToString();
  157. }
  158. }
  159. }