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

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