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.6 kB

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

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