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.

DataSet.cs 2.1 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using NumSharp.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using Tensorflow;
  6. namespace TensorFlowNET.Examples.Utility
  7. {
  8. public class DataSet
  9. {
  10. private int _num_examples;
  11. public int num_examples => _num_examples;
  12. private int _epochs_completed;
  13. public int epochs_completed => _epochs_completed;
  14. private int _index_in_epoch;
  15. public int index_in_epoch => _index_in_epoch;
  16. private NDArray _images;
  17. public NDArray images => _images;
  18. private NDArray _labels;
  19. public NDArray labels => _labels;
  20. public DataSet(NDArray images, NDArray labels, TF_DataType dtype, bool reshape)
  21. {
  22. _num_examples = images.shape[0];
  23. images = images.reshape(images.shape[0], images.shape[1] * images.shape[2]);
  24. images.astype(dtype.as_numpy_datatype());
  25. images = np.multiply(images, 1.0f / 255.0f);
  26. _images = images;
  27. _labels = labels;
  28. _epochs_completed = 0;
  29. _index_in_epoch = 0;
  30. }
  31. public (int, int) next_batch(int batch_size, bool fake_data = false, bool shuffle = true)
  32. {
  33. var start = _index_in_epoch;
  34. // Shuffle for the first epoch
  35. if(_epochs_completed == 0 && start == 0 && shuffle)
  36. {
  37. var perm0 = np.arange(_num_examples);
  38. np.random.shuffle(perm0);
  39. _images = images[perm0];
  40. _labels = labels[perm0];
  41. }
  42. // Go to the next epoch
  43. if (start + batch_size > _num_examples)
  44. {
  45. // Finished epoch
  46. _epochs_completed += 1;
  47. throw new NotImplementedException("next_batch");
  48. }
  49. else
  50. {
  51. _index_in_epoch += batch_size;
  52. var end = _index_in_epoch;
  53. return (_images[np.arange(start, end)], _labels[np.arange(start, end)]);
  54. }
  55. }
  56. }
  57. }

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