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

6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. using NumSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. namespace TensorFlowNET.Examples
  9. {
  10. public class DataHelpers
  11. {
  12. private const string TRAIN_PATH = "text_classification/dbpedia_csv/train.csv";
  13. private const string TEST_PATH = "text_classification/dbpedia_csv/test.csv";
  14. public static (int[][], int[], int) build_char_dataset(string step, string model, int document_max_len, int? limit = null)
  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(TRAIN_PATH);
  27. var size = limit == null ? contents.Length : limit.Value;
  28. var x = new int[size][];
  29. var y = new int[size];
  30. for (int i = 0; i < size; i++)
  31. {
  32. string[] parts = contents[i].ToLower().Split(",\"").ToArray();
  33. string content = parts[2];
  34. content = content.Substring(0, content.Length - 1);
  35. x[i] = new int[document_max_len];
  36. for (int j = 0; j < document_max_len; j++)
  37. {
  38. if (j >= content.Length)
  39. x[i][j] = char_dict["<pad>"];
  40. else
  41. x[i][j] = char_dict.ContainsKey(content[j].ToString()) ? char_dict[content[j].ToString()] : char_dict["<unk>"];
  42. }
  43. y[i] = int.Parse(parts[0]);
  44. }
  45. return (x, y, alphabet.Length + 2);
  46. }
  47. /// <summary>
  48. /// Loads MR polarity data from files, splits the data into words and generates labels.
  49. /// Returns split sentences and labels.
  50. /// </summary>
  51. /// <param name="positive_data_file"></param>
  52. /// <param name="negative_data_file"></param>
  53. /// <returns></returns>
  54. public static (string[], NDArray) load_data_and_labels(string positive_data_file, string negative_data_file)
  55. {
  56. Directory.CreateDirectory("CnnTextClassification");
  57. Utility.Web.Download(positive_data_file, "CnnTextClassification", "rt -polarity.pos");
  58. Utility.Web.Download(negative_data_file, "CnnTextClassification", "rt-polarity.neg");
  59. // Load data from files
  60. var positive_examples = File.ReadAllLines("CnnTextClassification/rt-polarity.pos")
  61. .Select(x => x.Trim())
  62. .ToArray();
  63. var negative_examples = File.ReadAllLines("CnnTextClassification/rt-polarity.neg")
  64. .Select(x => x.Trim())
  65. .ToArray();
  66. var x_text = new List<string>();
  67. x_text.AddRange(positive_examples);
  68. x_text.AddRange(negative_examples);
  69. x_text = x_text.Select(x => clean_str(x)).ToList();
  70. var positive_labels = positive_examples.Select(x => new int[2] { 0, 1 }).ToArray();
  71. var negative_labels = negative_examples.Select(x => new int[2] { 1, 0 }).ToArray();
  72. var y = np.concatenate(new int[][][] { positive_labels, negative_labels });
  73. return (x_text.ToArray(), y);
  74. }
  75. private static string clean_str(string str)
  76. {
  77. str = Regex.Replace(str, @"[^A-Za-z0-9(),!?\'\`]", " ");
  78. str = Regex.Replace(str, @"\'s", " \'s");
  79. return str;
  80. }
  81. /// <summary>
  82. /// Padding
  83. /// </summary>
  84. /// <param name="sequences"></param>
  85. /// <param name="pad_tok">the char to pad with</param>
  86. /// <returns>a list of list where each sublist has same length</returns>
  87. public static (int[][], int[]) pad_sequences(int[][] sequences, int pad_tok = 0)
  88. {
  89. int max_length = sequences.Select(x => x.Length).Max();
  90. return _pad_sequences(sequences, pad_tok, max_length);
  91. }
  92. public static (int[][][], int[][]) pad_sequences(int[][][] sequences, int pad_tok = 0)
  93. {
  94. int max_length_word = sequences.Select(x => x.Select(w => w.Length).Max()).Max();
  95. int[][][] sequence_padded;
  96. var sequence_length = new int[sequences.Length][];
  97. for (int i = 0; i < sequences.Length; i++)
  98. {
  99. // all words are same length now
  100. var (sp, sl) = _pad_sequences(sequences[i], pad_tok, max_length_word);
  101. sequence_length[i] = sl;
  102. }
  103. int max_length_sentence = sequences.Select(x => x.Length).Max();
  104. (sequence_padded, _) = _pad_sequences(sequences, np.repeat(pad_tok, max_length_word).Data<int>(), max_length_sentence);
  105. (sequence_length, _) = _pad_sequences(sequence_length, 0, max_length_sentence);
  106. return (sequence_padded, sequence_length);
  107. }
  108. private static (int[][], int[]) _pad_sequences(int[][] sequences, int pad_tok, int max_length)
  109. {
  110. var sequence_length = new int[sequences.Length];
  111. for (int i = 0; i < sequences.Length; i++)
  112. {
  113. sequence_length[i] = sequences[i].Length;
  114. Array.Resize(ref sequences[i], max_length);
  115. }
  116. return (sequences, sequence_length);
  117. }
  118. private static (int[][][], int[]) _pad_sequences(int[][][] sequences, int[] pad_tok, int max_length)
  119. {
  120. var sequence_length = new int[sequences.Length];
  121. for (int i = 0; i < sequences.Length; i++)
  122. {
  123. sequence_length[i] = sequences[i].Length;
  124. Array.Resize(ref sequences[i], max_length);
  125. for (int j = 0; j < max_length - sequence_length[i]; j++)
  126. {
  127. sequences[i][max_length - j - 1] = new int[pad_tok.Length];
  128. Array.Copy(pad_tok, sequences[i][max_length - j - 1], pad_tok.Length);
  129. }
  130. }
  131. return (sequences, sequence_length);
  132. }
  133. }
  134. }

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。