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.

KMeansClustering.cs 6.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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.Diagnostics;
  17. using System.Linq;
  18. using System.Text;
  19. using Tensorflow;
  20. using Tensorflow.Clustering;
  21. using TensorFlowNET.Examples.Utility;
  22. using static Tensorflow.Python;
  23. namespace TensorFlowNET.Examples
  24. {
  25. /// <summary>
  26. /// Implement K-Means algorithm with TensorFlow.NET, and apply it to classify
  27. /// handwritten digit images.
  28. /// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/kmeans.py
  29. /// </summary>
  30. public class KMeansClustering : IExample
  31. {
  32. public bool Enabled { get; set; } = false;
  33. public string Name => "K-means Clustering";
  34. public bool IsImportingGraph { get; set; } = true;
  35. public int? train_size = null;
  36. public int validation_size = 5000;
  37. public int? test_size = null;
  38. public int batch_size = 1024; // The number of samples per batch
  39. Datasets<DataSetMnist> mnist;
  40. NDArray full_data_x;
  41. int num_steps = 20; // Total steps to train
  42. int k = 25; // The number of clusters
  43. int num_classes = 10; // The 10 digits
  44. int num_features = 784; // Each image is 28x28 pixels
  45. float accuray_test = 0f;
  46. public bool Run()
  47. {
  48. PrepareData();
  49. var graph = ImportGraph();
  50. with(tf.Session(graph), sess =>
  51. {
  52. Train(sess);
  53. });
  54. return accuray_test > 0.70;
  55. }
  56. public void PrepareData()
  57. {
  58. mnist = MNIST.read_data_sets("mnist", one_hot: true, train_size: train_size, validation_size:validation_size, test_size:test_size);
  59. full_data_x = mnist.train.data;
  60. // download graph meta data
  61. string url = "https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/graph/kmeans.meta";
  62. Web.Download(url, "graph", "kmeans.meta");
  63. }
  64. public Graph ImportGraph()
  65. {
  66. var graph = tf.Graph().as_default();
  67. tf.train.import_meta_graph("graph/kmeans.meta");
  68. return graph;
  69. }
  70. public Graph BuildGraph()
  71. {
  72. throw new NotImplementedException();
  73. }
  74. public void Train(Session sess)
  75. {
  76. var graph = tf.Graph();
  77. // Input images
  78. Tensor X = graph.get_operation_by_name("Placeholder"); // tf.placeholder(tf.float32, shape: new TensorShape(-1, num_features));
  79. // Labels (for assigning a label to a centroid and testing)
  80. Tensor Y = graph.get_operation_by_name("Placeholder_1"); // tf.placeholder(tf.float32, shape: new TensorShape(-1, num_classes));
  81. // K-Means Parameters
  82. //var kmeans = new KMeans(X, k, distance_metric: KMeans.COSINE_DISTANCE, use_mini_batch: true);
  83. // Build KMeans graph
  84. //var training_graph = kmeans.training_graph();
  85. var init_vars = tf.global_variables_initializer();
  86. Tensor init_op = graph.get_operation_by_name("cond/Merge");
  87. var train_op = graph.get_operation_by_name("group_deps");
  88. Tensor avg_distance = graph.get_operation_by_name("Mean");
  89. Tensor cluster_idx = graph.get_operation_by_name("Squeeze_1");
  90. NDArray result = null;
  91. sess.run(init_vars, new FeedItem(X, full_data_x));
  92. sess.run(init_op, new FeedItem(X, full_data_x));
  93. // Training
  94. var sw = new Stopwatch();
  95. foreach (var i in range(1, num_steps + 1))
  96. {
  97. sw.Restart();
  98. result = sess.run(new ITensorOrOperation[] { train_op, avg_distance, cluster_idx }, new FeedItem(X, full_data_x));
  99. sw.Stop();
  100. if (i % 4 == 0 || i == 1)
  101. print($"Step {i}, Avg Distance: {result[1]} Elapse: {sw.ElapsedMilliseconds}ms");
  102. }
  103. var idx = result[2].Data<int>();
  104. // Assign a label to each centroid
  105. // Count total number of labels per centroid, using the label of each training
  106. // sample to their closest centroid (given by 'idx')
  107. var counts = np.zeros((k, num_classes), np.float32);
  108. sw.Start();
  109. foreach (var i in range(idx.Length))
  110. {
  111. var x = mnist.train.labels[i];
  112. counts[idx[i]] += x;
  113. }
  114. sw.Stop();
  115. print($"Assign a label to each centroid took {sw.ElapsedMilliseconds}ms");
  116. // Assign the most frequent label to the centroid
  117. var labels_map_array = np.argmax(counts, 1);
  118. var labels_map = tf.convert_to_tensor(labels_map_array);
  119. // Evaluation ops
  120. // Lookup: centroid_id -> label
  121. var cluster_label = tf.nn.embedding_lookup(labels_map, cluster_idx);
  122. // Compute accuracy
  123. var correct_prediction = tf.equal(cluster_label, tf.cast(tf.argmax(Y, 1), tf.int32));
  124. var cast = tf.cast(correct_prediction, tf.float32);
  125. var accuracy_op = tf.reduce_mean(cast);
  126. // Test Model
  127. var (test_x, test_y) = (mnist.test.data, mnist.test.labels);
  128. result = sess.run(accuracy_op, new FeedItem(X, test_x), new FeedItem(Y, test_y));
  129. accuray_test = result;
  130. print($"Test Accuracy: {accuray_test}");
  131. }
  132. public void Predict(Session sess)
  133. {
  134. throw new NotImplementedException();
  135. }
  136. public void Test(Session sess)
  137. {
  138. throw new NotImplementedException();
  139. }
  140. }
  141. }