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

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