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.

NearestNeighbor.cs 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 Tensorflow;
  16. using Tensorflow.Hub;
  17. using static Tensorflow.Python;
  18. using static Tensorflow.Binding;
  19. namespace TensorFlowNET.Examples
  20. {
  21. /// <summary>
  22. /// A nearest neighbor learning algorithm example
  23. /// This example is using the MNIST database of handwritten digits
  24. /// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/nearest_neighbor.py
  25. /// </summary>
  26. public class NearestNeighbor : IExample
  27. {
  28. public bool Enabled { get; set; } = true;
  29. public string Name => "Nearest Neighbor";
  30. Datasets<MnistDataSet> mnist;
  31. NDArray Xtr, Ytr, Xte, Yte;
  32. public int? TrainSize = null;
  33. public int ValidationSize = 5000;
  34. public int? TestSize = null;
  35. public bool IsImportingGraph { get; set; } = false;
  36. public bool Run()
  37. {
  38. // tf Graph Input
  39. var xtr = tf.placeholder(tf.float32, new TensorShape(-1, 784));
  40. var xte = tf.placeholder(tf.float32, new TensorShape(784));
  41. // Nearest Neighbor calculation using L1 Distance
  42. // Calculate L1 Distance
  43. var distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices: 1);
  44. // Prediction: Get min distance index (Nearest neighbor)
  45. var pred = tf.arg_min(distance, 0);
  46. float accuracy = 0f;
  47. // Initialize the variables (i.e. assign their default value)
  48. var init = tf.global_variables_initializer();
  49. using (var sess = tf.Session())
  50. {
  51. // Run the initializer
  52. sess.run(init);
  53. PrepareData();
  54. foreach(int i in range(Xte.shape[0]))
  55. {
  56. // Get nearest neighbor
  57. long nn_index = sess.run(pred, (xtr, Xtr), (xte, Xte[i]));
  58. // Get nearest neighbor class label and compare it to its true label
  59. int index = (int)nn_index;
  60. if (i % 10 == 0 || i == 0)
  61. print($"Test {i} Prediction: {np.argmax(Ytr[index])} True Class: {np.argmax(Yte[i])}");
  62. // Calculate accuracy
  63. if (np.argmax(Ytr[index]) == np.argmax(Yte[i]))
  64. accuracy += 1f/ Xte.shape[0];
  65. }
  66. print($"Accuracy: {accuracy}");
  67. }
  68. return accuracy > 0.8;
  69. }
  70. public void PrepareData()
  71. {
  72. mnist = MnistModelLoader.LoadAsync(".resources/mnist", oneHot: true, trainSize: TrainSize, validationSize: ValidationSize, testSize: TestSize, showProgressInConsole: true).Result;
  73. // In this example, we limit mnist data
  74. (Xtr, Ytr) = mnist.Train.GetNextBatch(TrainSize == null ? 5000 : TrainSize.Value / 100); // 5000 for training (nn candidates)
  75. (Xte, Yte) = mnist.Test.GetNextBatch(TestSize == null ? 200 : TestSize.Value / 100); // 200 for testing
  76. }
  77. public Graph ImportGraph()
  78. {
  79. throw new NotImplementedException();
  80. }
  81. public Graph BuildGraph()
  82. {
  83. throw new NotImplementedException();
  84. }
  85. public void Train(Session sess)
  86. {
  87. throw new NotImplementedException();
  88. }
  89. public void Predict(Session sess)
  90. {
  91. throw new NotImplementedException();
  92. }
  93. public void Test(Session sess)
  94. {
  95. throw new NotImplementedException();
  96. }
  97. }
  98. }