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.

MNIST.cs 6.2 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /*****************************************************************************
  2. Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using NumSharp;
  14. using System;
  15. using System.IO;
  16. using Tensorflow;
  17. namespace TensorFlowNET.Examples.Utility
  18. {
  19. public class MNIST
  20. {
  21. private const string DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/";
  22. private const string TRAIN_IMAGES = "train-images-idx3-ubyte.gz";
  23. private const string TRAIN_LABELS = "train-labels-idx1-ubyte.gz";
  24. private const string TEST_IMAGES = "t10k-images-idx3-ubyte.gz";
  25. private const string TEST_LABELS = "t10k-labels-idx1-ubyte.gz";
  26. public static Datasets<DataSetMnist> read_data_sets(string train_dir,
  27. bool one_hot = false,
  28. TF_DataType dtype = TF_DataType.TF_FLOAT,
  29. bool reshape = true,
  30. int validation_size = 5000,
  31. int? train_size = null,
  32. int? test_size = null,
  33. string source_url = DEFAULT_SOURCE_URL)
  34. {
  35. if (train_size!=null && validation_size >= train_size)
  36. throw new ArgumentException("Validation set should be smaller than training set");
  37. Web.Download(source_url + TRAIN_IMAGES, train_dir, TRAIN_IMAGES);
  38. Compress.ExtractGZip(Path.Join(train_dir, TRAIN_IMAGES), train_dir);
  39. var train_images = extract_images(Path.Join(train_dir, TRAIN_IMAGES.Split('.')[0]), limit: train_size);
  40. Web.Download(source_url + TRAIN_LABELS, train_dir, TRAIN_LABELS);
  41. Compress.ExtractGZip(Path.Join(train_dir, TRAIN_LABELS), train_dir);
  42. var train_labels = extract_labels(Path.Join(train_dir, TRAIN_LABELS.Split('.')[0]), one_hot: one_hot, limit: train_size);
  43. Web.Download(source_url + TEST_IMAGES, train_dir, TEST_IMAGES);
  44. Compress.ExtractGZip(Path.Join(train_dir, TEST_IMAGES), train_dir);
  45. var test_images = extract_images(Path.Join(train_dir, TEST_IMAGES.Split('.')[0]), limit: test_size);
  46. Web.Download(source_url + TEST_LABELS, train_dir, TEST_LABELS);
  47. Compress.ExtractGZip(Path.Join(train_dir, TEST_LABELS), train_dir);
  48. var test_labels = extract_labels(Path.Join(train_dir, TEST_LABELS.Split('.')[0]), one_hot: one_hot, limit:test_size);
  49. int end = train_images.shape[0];
  50. var validation_images = train_images[np.arange(validation_size)];
  51. var validation_labels = train_labels[np.arange(validation_size)];
  52. train_images = train_images[np.arange(validation_size, end)];
  53. train_labels = train_labels[np.arange(validation_size, end)];
  54. var train = new DataSetMnist(train_images, train_labels, dtype, reshape);
  55. var validation = new DataSetMnist(validation_images, validation_labels, dtype, reshape);
  56. var test = new DataSetMnist(test_images, test_labels, dtype, reshape);
  57. return new Datasets<DataSetMnist>(train, validation, test);
  58. }
  59. public static NDArray extract_images(string file, int? limit=null)
  60. {
  61. using (var bytestream = new FileStream(file, FileMode.Open))
  62. {
  63. var magic = _read32(bytestream);
  64. if (magic != 2051)
  65. throw new ValueError($"Invalid magic number {magic} in MNIST image file: {file}");
  66. var num_images = _read32(bytestream);
  67. num_images = limit == null ? num_images : Math.Min(num_images, (uint)limit);
  68. var rows = _read32(bytestream);
  69. var cols = _read32(bytestream);
  70. var buf = new byte[rows * cols * num_images];
  71. bytestream.Read(buf, 0, buf.Length);
  72. var data = np.frombuffer(buf, np.uint8);
  73. data = data.reshape((int)num_images, (int)rows, (int)cols, 1);
  74. return data;
  75. }
  76. }
  77. public static NDArray extract_labels(string file, bool one_hot = false, int num_classes = 10, int? limit = null)
  78. {
  79. using (var bytestream = new FileStream(file, FileMode.Open))
  80. {
  81. var magic = _read32(bytestream);
  82. if (magic != 2049)
  83. throw new ValueError($"Invalid magic number {magic} in MNIST label file: {file}");
  84. var num_items = _read32(bytestream);
  85. num_items = limit == null ? num_items : Math.Min(num_items,(uint) limit);
  86. var buf = new byte[num_items];
  87. bytestream.Read(buf, 0, buf.Length);
  88. var labels = np.frombuffer(buf, np.uint8);
  89. if (one_hot)
  90. return dense_to_one_hot(labels, num_classes);
  91. return labels;
  92. }
  93. }
  94. private static NDArray dense_to_one_hot(NDArray labels_dense, int num_classes)
  95. {
  96. var num_labels = labels_dense.shape[0];
  97. var index_offset = np.arange(num_labels) * num_classes;
  98. var labels_one_hot = np.zeros(num_labels, num_classes);
  99. for(int row = 0; row < num_labels; row++)
  100. {
  101. var col = labels_dense.Data<byte>(row);
  102. labels_one_hot.SetData(1.0, row, col);
  103. }
  104. return labels_one_hot;
  105. }
  106. private static uint _read32(FileStream bytestream)
  107. {
  108. var buffer = new byte[sizeof(uint)];
  109. var count = bytestream.Read(buffer, 0, 4);
  110. return np.frombuffer(buffer, ">u4").Data<uint>(0);
  111. }
  112. }
  113. }