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

6 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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.CnnTextClassification
  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. }
  82. }

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