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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using NumSharp.Core;
  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. print($"Test {i} Prediction: {np.argmax(Ytr[nn_index])} True Class: {np.argmax(Yte[i] as NDArray)}");
  45. // Calculate accuracy
  46. if (np.argmax(Ytr[nn_index]) == np.argmax(Yte[i] as NDArray))
  47. accuracy += 1f/ Xte.shape[0];
  48. }
  49. print($"Accuracy: {accuracy}");
  50. });
  51. return accuracy > 0.9;
  52. }
  53. public void PrepareData()
  54. {
  55. mnist = MnistDataSet.read_data_sets("mnist", one_hot: true);
  56. // In this example, we limit mnist data
  57. (Xtr, Ytr) = mnist.train.next_batch(5000); // 5000 for training (nn candidates)
  58. (Xte, Yte) = mnist.test.next_batch(200); // 200 for testing
  59. }
  60. }
  61. }

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