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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 => true;
  18. public string Name => "Nearest Neighbor";
  19. Datasets mnist;
  20. NDArray Xtr, Ytr, Xte, Yte;
  21. public bool Run()
  22. {
  23. // tf Graph Input
  24. var xtr = tf.placeholder(tf.float32, new TensorShape(-1, 784));
  25. var xte = tf.placeholder(tf.float32, new TensorShape(784));
  26. // Nearest Neighbor calculation using L1 Distance
  27. // Calculate L1 Distance
  28. var distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices: 1);
  29. // Prediction: Get min distance index (Nearest neighbor)
  30. var pred = tf.arg_min(distance, 0);
  31. float accuracy = 0f;
  32. // Initialize the variables (i.e. assign their default value)
  33. var init = tf.global_variables_initializer();
  34. with(tf.Session(), sess =>
  35. {
  36. // Run the initializer
  37. sess.run(init);
  38. PrepareData();
  39. foreach(int i in range(Xte.shape[0]))
  40. {
  41. // Get nearest neighbor
  42. long nn_index = sess.run(pred, new FeedItem(xtr, Xtr), new FeedItem(xte, Xte[i]));
  43. // Get nearest neighbor class label and compare it to its true label
  44. int index = (int)nn_index;
  45. print($"Test {i} Prediction: {np.argmax(Ytr[(NDArray)index])} True Class: {np.argmax(Yte[i] as NDArray)}");
  46. // Calculate accuracy
  47. if (np.argmax(Ytr[(NDArray)index]) == np.argmax(Yte[i] as NDArray))
  48. accuracy += 1f/ Xte.shape[0];
  49. }
  50. print($"Accuracy: {accuracy}");
  51. });
  52. return accuracy > 0.9;
  53. }
  54. public void PrepareData()
  55. {
  56. mnist = MnistDataSet.read_data_sets("mnist", one_hot: true);
  57. // In this example, we limit mnist data
  58. (Xtr, Ytr) = mnist.train.next_batch(5000); // 5000 for training (nn candidates)
  59. (Xte, Yte) = mnist.test.next_batch(200); // 200 for testing
  60. }
  61. }
  62. }

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