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

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

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。