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 3.1 kB

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