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.

TextClassificationTrain.cs 2.8 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using Tensorflow;
  7. using TensorFlowNET.Examples.TextClassification;
  8. using TensorFlowNET.Examples.Utility;
  9. namespace TensorFlowNET.Examples.CnnTextClassification
  10. {
  11. /// <summary>
  12. /// https://github.com/dongjun-Lee/text-classification-models-tf
  13. /// </summary>
  14. public class TextClassificationTrain : Python, IExample
  15. {
  16. public int Priority => 100;
  17. public bool Enabled { get; set; }= false;
  18. public string Name => "Text Classification";
  19. private string dataDir = "text_classification";
  20. private string dataFileName = "dbpedia_csv.tar.gz";
  21. private const int CHAR_MAX_LEN = 1014;
  22. private const int NUM_CLASS = 2;
  23. public bool Run()
  24. {
  25. PrepareData();
  26. Console.WriteLine("Building dataset...");
  27. var (x, y, alphabet_size) = DataHelpers.build_char_dataset("train", "vdcnn", CHAR_MAX_LEN);
  28. var (train_x, valid_x, train_y, valid_y) = train_test_split(x, y, test_size: 0.15f);
  29. return with(tf.Session(), sess =>
  30. {
  31. new VdCnn(alphabet_size, CHAR_MAX_LEN, NUM_CLASS);
  32. return false;
  33. });
  34. }
  35. private (int[][], int[][], int[], int[]) train_test_split(int[][] x, int[] y, float test_size = 0.3f)
  36. {
  37. int len = x.Length;
  38. int classes = y.Distinct().Count();
  39. int samples = len / classes;
  40. int train_size = int.Parse((samples * (1 - test_size)).ToString());
  41. var train_x = new List<int[]>();
  42. var valid_x = new List<int[]>();
  43. var train_y = new List<int>();
  44. var valid_y = new List<int>();
  45. for (int i = 0; i< classes; i++)
  46. {
  47. for (int j = 0; j < samples; j++)
  48. {
  49. int idx = i * samples + j;
  50. if (idx < train_size + samples * i)
  51. {
  52. train_x.Add(x[idx]);
  53. train_y.Add(y[idx]);
  54. }
  55. else
  56. {
  57. valid_x.Add(x[idx]);
  58. valid_y.Add(y[idx]);
  59. }
  60. }
  61. }
  62. return (train_x.ToArray(), valid_x.ToArray(), train_y.ToArray(), valid_y.ToArray());
  63. }
  64. public void PrepareData()
  65. {
  66. string url = "https://github.com/le-scientifique/torchDatasets/raw/master/dbpedia_csv.tar.gz";
  67. Web.Download(url, dataDir, dataFileName);
  68. Compress.ExtractTGZ(Path.Join(dataDir, dataFileName), dataDir);
  69. }
  70. }
  71. }

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