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

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

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