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

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