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.

TextClassificationWithMovieReviews.cs 4.4 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using Tensorflow;
  5. using NumSharp.Core;
  6. using Newtonsoft.Json;
  7. using System.Linq;
  8. using System.Text.RegularExpressions;
  9. namespace TensorFlowNET.Examples
  10. {
  11. public class TextClassificationWithMovieReviews : Python, IExample
  12. {
  13. public int Priority => 7;
  14. public bool Enabled => false;
  15. public string Name => "Movie Reviews";
  16. string dir = "text_classification_with_movie_reviews";
  17. string dataFile = "imdb.zip";
  18. NDArray train_data, train_labels, test_data, test_labels;
  19. public bool Run()
  20. {
  21. PrepareData();
  22. Console.WriteLine($"Training entries: {train_data.size}, labels: {train_labels.size}");
  23. // A dictionary mapping words to an integer index
  24. var word_index = GetWordIndex();
  25. train_data = keras.preprocessing.sequence.pad_sequences(train_data,
  26. value: word_index["<PAD>"],
  27. padding: "post",
  28. maxlen: 256);
  29. test_data = keras.preprocessing.sequence.pad_sequences(test_data,
  30. value: word_index["<PAD>"],
  31. padding: "post",
  32. maxlen: 256);
  33. // input shape is the vocabulary count used for the movie reviews (10,000 words)
  34. int vocab_size = 10000;
  35. var model = keras.Sequential();
  36. model.add(keras.layers.Embedding(vocab_size, 16));
  37. return false;
  38. }
  39. public void PrepareData()
  40. {
  41. Directory.CreateDirectory(dir);
  42. // get model file
  43. string url = $"https://github.com/SciSharp/TensorFlow.NET/raw/master/data/{dataFile}";
  44. Utility.Web.Download(url, dir, "imdb.zip");
  45. Utility.Compress.UnZip(Path.Join(dir, $"imdb.zip"), dir);
  46. // prepare training dataset
  47. var x_train = ReadData(Path.Join(dir, "x_train.txt"));
  48. var labels_train = ReadData(Path.Join(dir, "y_train.txt"));
  49. var indices_train = ReadData(Path.Join(dir, "indices_train.txt"));
  50. x_train = x_train[indices_train];
  51. labels_train = labels_train[indices_train];
  52. var x_test = ReadData(Path.Join(dir, "x_test.txt"));
  53. var labels_test = ReadData(Path.Join(dir, "y_test.txt"));
  54. var indices_test = ReadData(Path.Join(dir, "indices_test.txt"));
  55. x_test = x_test[indices_test];
  56. labels_test = labels_test[indices_test];
  57. // not completed
  58. var xs = x_train.hstack(x_test);
  59. var labels = labels_train.hstack(labels_test);
  60. var idx = x_train.size;
  61. var y_train = labels_train;
  62. var y_test = labels_test;
  63. x_train = train_data;
  64. train_labels = y_train;
  65. test_data = x_test;
  66. test_labels = y_test;
  67. }
  68. private NDArray ReadData(string file)
  69. {
  70. var lines = File.ReadAllLines(file);
  71. var nd = new NDArray(lines[0].StartsWith("[") ? typeof(object) : np.int32, new Shape(lines.Length));
  72. if (lines[0].StartsWith("["))
  73. {
  74. for (int i = 0; i < lines.Length; i++)
  75. {
  76. var matches = Regex.Matches(lines[i], @"\d+\s*");
  77. var data = new int[matches.Count];
  78. for (int j = 0; j < data.Length; j++)
  79. data[j] = Convert.ToInt32(matches[j].Value);
  80. nd[i] = data.ToArray();
  81. }
  82. }
  83. else
  84. {
  85. for (int i = 0; i < lines.Length; i++)
  86. nd[i] = Convert.ToInt32(lines[i]);
  87. }
  88. return nd;
  89. }
  90. private Dictionary<string, int> GetWordIndex()
  91. {
  92. var result = new Dictionary<string, int>();
  93. var json = File.ReadAllText(Path.Join(dir, "imdb_word_index.json"));
  94. var dict = JsonConvert.DeserializeObject<Dictionary<string, int>>(json);
  95. dict.Keys.Select(k => result[k] = dict[k] + 3).ToList();
  96. result["<PAD>"] = 0;
  97. result["<START>"] = 1;
  98. result["<UNK>"] = 2; // unknown
  99. result["<UNUSED>"] = 3;
  100. return result;
  101. }
  102. }
  103. }

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