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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. public int Priority => 100;
  18. public bool Enabled => false;
  19. public string Name => "Text Classification";
  20. private string dataDir = "text_classification";
  21. private string dataFileName = "dbpedia_csv.tar.gz";
  22. private const int CHAR_MAX_LEN = 1014;
  23. private const int NUM_CLASS = 2;
  24. public bool Run()
  25. {
  26. PrepareData();
  27. Console.WriteLine("Building dataset...");
  28. var (x, y, alphabet_size) = DataHelpers.build_char_dataset("train", "vdcnn", CHAR_MAX_LEN);
  29. var (train_x, valid_x, train_y, valid_y) = train_test_split(x, y, test_size: 0.15f);
  30. return with(tf.Session(), sess =>
  31. {
  32. new VdCnn(alphabet_size, CHAR_MAX_LEN, NUM_CLASS);
  33. return false;
  34. });
  35. }
  36. private (int[][], int[][], int[], int[]) train_test_split(int[][] x, int[] y, float test_size = 0.3f)
  37. {
  38. int len = x.Length;
  39. int classes = y.Distinct().Count();
  40. int samples = len / classes;
  41. int train_size = int.Parse((samples * (1 - test_size)).ToString());
  42. var train_x = new List<int[]>();
  43. var valid_x = new List<int[]>();
  44. var train_y = new List<int>();
  45. var valid_y = new List<int>();
  46. for (int i = 0; i< classes; i++)
  47. {
  48. for (int j = 0; j < samples; j++)
  49. {
  50. int idx = i * samples + j;
  51. if (idx < train_size + samples * i)
  52. {
  53. train_x.Add(x[idx]);
  54. train_y.Add(y[idx]);
  55. }
  56. else
  57. {
  58. valid_x.Add(x[idx]);
  59. valid_y.Add(y[idx]);
  60. }
  61. }
  62. }
  63. return (train_x.ToArray(), valid_x.ToArray(), train_y.ToArray(), valid_y.ToArray());
  64. }
  65. public void PrepareData()
  66. {
  67. string url = "https://github.com/le-scientifique/torchDatasets/raw/master/dbpedia_csv.tar.gz";
  68. Web.Download(url, dataDir, dataFileName);
  69. Compress.ExtractTGZ(Path.Join(dataDir, dataFileName), dataDir);
  70. }
  71. }
  72. }

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