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.

RetrainImageClassifier.cs 30 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. using NumSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using Tensorflow;
  9. using TensorFlowNET.Examples.Utility;
  10. using static Tensorflow.Python;
  11. namespace TensorFlowNET.Examples.ImageProcess
  12. {
  13. /// <summary>
  14. /// In this tutorial, we will reuse the feature extraction capabilities from powerful image classifiers trained on ImageNet
  15. /// and simply train a new classification layer on top. Transfer learning is a technique that shortcuts much of this
  16. /// by taking a piece of a model that has already been trained on a related task and reusing it in a new model.
  17. ///
  18. /// https://www.tensorflow.org/hub/tutorials/image_retraining
  19. /// </summary>
  20. public class RetrainImageClassifier : IExample
  21. {
  22. public int Priority => 16;
  23. public bool Enabled { get; set; } = false;
  24. public bool ImportGraph { get; set; } = true;
  25. public string Name => "Retrain Image Classifier";
  26. const string data_dir = "retrain_images";
  27. string summaries_dir = Path.Join(data_dir, "retrain_logs");
  28. string image_dir = Path.Join(data_dir, "flower_photos");
  29. string bottleneck_dir = Path.Join(data_dir, "bottleneck");
  30. // The location where variable checkpoints will be stored.
  31. string CHECKPOINT_NAME = Path.Join(data_dir, "_retrain_checkpoint");
  32. string tfhub_module = "https://tfhub.dev/google/imagenet/inception_v3/feature_vector/3";
  33. float testing_percentage = 0.1f;
  34. float validation_percentage = 0.1f;
  35. float learning_rate = 0.01f;
  36. Tensor resized_image_tensor;
  37. Dictionary<string, Dictionary<string, string[]>> image_lists;
  38. int how_many_training_steps = 200;
  39. int eval_step_interval = 10;
  40. int train_batch_size = 100;
  41. int validation_batch_size = 100;
  42. int intermediate_store_frequency = 0;
  43. int class_count = 0;
  44. const int MAX_NUM_IMAGES_PER_CLASS = 134217727;
  45. Operation train_step;
  46. Tensor final_tensor;
  47. Tensor bottleneck_input;
  48. Tensor cross_entropy;
  49. Tensor ground_truth_input;
  50. public bool Run()
  51. {
  52. PrepareData();
  53. // Set up the pre-trained graph.
  54. var (graph, bottleneck_tensor, resized_image_tensor, wants_quantization) =
  55. create_module_graph();
  56. // Add the new layer that we'll be training.
  57. with(graph.as_default(), delegate
  58. {
  59. (train_step, cross_entropy, bottleneck_input,
  60. ground_truth_input, final_tensor) = add_final_retrain_ops(
  61. class_count, "final_result", bottleneck_tensor,
  62. wants_quantization, is_training: true);
  63. });
  64. /*Tensor bottleneck_tensor = graph.OperationByName("module_apply_default/hub_output/feature_vector/SpatialSqueeze");
  65. Tensor resized_image_tensor = graph.OperationByName("Placeholder");
  66. Tensor final_tensor = graph.OperationByName("final_result");
  67. Tensor ground_truth_input = graph.OperationByName("input/GroundTruthInput");
  68. train_step = graph.OperationByName("train/GradientDescent");
  69. Tensor bottleneck_input = graph.OperationByName("input/BottleneckInputPlaceholder");
  70. Tensor cross_entropy = graph.OperationByName("cross_entropy/sparse_softmax_cross_entropy_loss/value");*/
  71. var sw = new Stopwatch();
  72. with(tf.Session(graph), sess =>
  73. {
  74. // Initialize all weights: for the module to their pretrained values,
  75. // and for the newly added retraining layer to random initial values.
  76. var init = tf.global_variables_initializer();
  77. sess.run(init);
  78. var (jpeg_data_tensor, decoded_image_tensor) = add_jpeg_decoding();
  79. // We'll make sure we've calculated the 'bottleneck' image summaries and
  80. // cached them on disk.
  81. cache_bottlenecks(sess, image_lists, image_dir,
  82. bottleneck_dir, jpeg_data_tensor,
  83. decoded_image_tensor, resized_image_tensor,
  84. bottleneck_tensor, tfhub_module);
  85. // Create the operations we need to evaluate the accuracy of our new layer.
  86. var (evaluation_step, _) = add_evaluation_step(final_tensor, ground_truth_input);
  87. // Merge all the summaries and write them out to the summaries_dir
  88. var merged = tf.summary.merge_all();
  89. var train_writer = tf.summary.FileWriter(summaries_dir + "/train", sess.graph);
  90. var validation_writer = tf.summary.FileWriter(summaries_dir + "/validation", sess.graph);
  91. // Create a train saver that is used to restore values into an eval graph
  92. // when exporting models.
  93. // var train_saver = tf.train.Saver();
  94. for (int i = 0; i < how_many_training_steps; i++)
  95. {
  96. var (train_bottlenecks, train_ground_truth, _) = get_random_cached_bottlenecks(
  97. sess, image_lists, train_batch_size, "training",
  98. bottleneck_dir, image_dir, jpeg_data_tensor,
  99. decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
  100. tfhub_module);
  101. // Feed the bottlenecks and ground truth into the graph, and run a training
  102. // step. Capture training summaries for TensorBoard with the `merged` op.
  103. var results = sess.run(
  104. new ITensorOrOperation[] { merged, train_step },
  105. new FeedItem(bottleneck_input, train_bottlenecks),
  106. new FeedItem(ground_truth_input, train_ground_truth));
  107. var train_summary = results[0];
  108. // TODO
  109. train_writer.add_summary(train_summary, i);
  110. // Every so often, print out how well the graph is training.
  111. bool is_last_step = (i + 1 == how_many_training_steps);
  112. if ((i % eval_step_interval) == 0 || is_last_step)
  113. {
  114. results = sess.run(
  115. new Tensor[] { evaluation_step, cross_entropy },
  116. new FeedItem(bottleneck_input, train_bottlenecks),
  117. new FeedItem(ground_truth_input, train_ground_truth));
  118. (float train_accuracy, float cross_entropy_value) = (results[0], results[1]);
  119. print($"{DateTime.Now}: Step {i}: Train accuracy = {train_accuracy * 100}%");
  120. print($"{DateTime.Now}: Step {i}: Cross entropy = {cross_entropy_value}");
  121. var (validation_bottlenecks, validation_ground_truth, _) = get_random_cached_bottlenecks(
  122. sess, image_lists, validation_batch_size, "validation",
  123. bottleneck_dir, image_dir, jpeg_data_tensor,
  124. decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
  125. tfhub_module);
  126. // Run a validation step and capture training summaries for TensorBoard
  127. // with the `merged` op.
  128. results = sess.run(new Tensor[] { merged, evaluation_step },
  129. new FeedItem(bottleneck_input, validation_bottlenecks),
  130. new FeedItem(ground_truth_input, validation_ground_truth));
  131. (string validation_summary, float validation_accuracy) = (results[0], results[1]);
  132. validation_writer.add_summary(validation_summary, i);
  133. print($"{DateTime.Now}: Step {i}: Validation accuracy = {validation_accuracy * 100}% (N={len(validation_bottlenecks)})");
  134. }
  135. // Store intermediate results
  136. int intermediate_frequency = intermediate_store_frequency;
  137. if (intermediate_frequency > 0 && i % intermediate_frequency == 0 && i > 0)
  138. {
  139. }
  140. }
  141. // After training is complete, force one last save of the train checkpoint.
  142. // train_saver.save(sess, CHECKPOINT_NAME);
  143. // We've completed all our training, so run a final test evaluation on
  144. // some new images we haven't used before.
  145. run_final_eval(sess, null, class_count, image_lists,
  146. jpeg_data_tensor, decoded_image_tensor, resized_image_tensor,
  147. bottleneck_tensor);
  148. });
  149. return false;
  150. }
  151. /// <summary>
  152. /// Runs a final evaluation on an eval graph using the test data set.
  153. /// </summary>
  154. /// <param name="train_session"></param>
  155. /// <param name="module_spec"></param>
  156. /// <param name="class_count"></param>
  157. /// <param name="image_lists"></param>
  158. /// <param name="jpeg_data_tensor"></param>
  159. /// <param name="decoded_image_tensor"></param>
  160. /// <param name="resized_image_tensor"></param>
  161. /// <param name="bottleneck_tensor"></param>
  162. private void run_final_eval(Session train_session, object module_spec, int class_count,
  163. Dictionary<string, Dictionary<string, string[]>> image_lists,
  164. Tensor jpeg_data_tensor, Tensor decoded_image_tensor,
  165. Tensor resized_image_tensor, Tensor bottleneck_tensor)
  166. {
  167. /*var (eval_session, _, bottleneck_input, ground_truth_input, evaluation_step,
  168. prediction) = build_eval_session(module_spec, class_count);*/
  169. }
  170. private void build_eval_session(int class_count)
  171. {
  172. // If quantized, we need to create the correct eval graph for exporting.
  173. var (eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization) = create_module_graph();
  174. var eval_sess = tf.Session(graph: eval_graph);
  175. with(eval_graph.as_default(), graph =>
  176. {
  177. });
  178. }
  179. /// <summary>
  180. /// Adds a new softmax and fully-connected layer for training and eval.
  181. ///
  182. /// We need to retrain the top layer to identify our new classes, so this function
  183. /// adds the right operations to the graph, along with some variables to hold the
  184. /// weights, and then sets up all the gradients for the backward pass.
  185. ///
  186. /// The set up for the softmax and fully-connected layers is based on:
  187. /// https://www.tensorflow.org/tutorials/mnist/beginners/index.html
  188. /// </summary>
  189. /// <param name="class_count"></param>
  190. /// <param name="final_tensor_name"></param>
  191. /// <param name="bottleneck_tensor"></param>
  192. /// <param name="quantize_layer"></param>
  193. /// <param name="is_training"></param>
  194. /// <returns></returns>
  195. private (Operation, Tensor, Tensor, Tensor, Tensor) add_final_retrain_ops(int class_count, string final_tensor_name,
  196. Tensor bottleneck_tensor, bool quantize_layer, bool is_training)
  197. {
  198. var (batch_size, bottleneck_tensor_size) = (bottleneck_tensor.GetShape().Dimensions[0], bottleneck_tensor.GetShape().Dimensions[1]);
  199. with(tf.name_scope("input"), scope =>
  200. {
  201. bottleneck_input = tf.placeholder_with_default(
  202. bottleneck_tensor,
  203. shape: bottleneck_tensor.GetShape().Dimensions,
  204. name: "BottleneckInputPlaceholder");
  205. ground_truth_input = tf.placeholder(tf.int64, new TensorShape(batch_size), name: "GroundTruthInput");
  206. });
  207. // Organizing the following ops so they are easier to see in TensorBoard.
  208. string layer_name = "final_retrain_ops";
  209. Tensor logits = null;
  210. with(tf.name_scope(layer_name), scope =>
  211. {
  212. RefVariable layer_weights = null;
  213. with(tf.name_scope("weights"), delegate
  214. {
  215. var initial_value = tf.truncated_normal(new int[] { bottleneck_tensor_size, class_count }, stddev: 0.001f);
  216. layer_weights = tf.Variable(initial_value, name: "final_weights");
  217. variable_summaries(layer_weights);
  218. });
  219. RefVariable layer_biases = null;
  220. with(tf.name_scope("biases"), delegate
  221. {
  222. layer_biases = tf.Variable(tf.zeros((class_count)), name: "final_biases");
  223. variable_summaries(layer_biases);
  224. });
  225. with(tf.name_scope("Wx_plus_b"), delegate
  226. {
  227. logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases;
  228. tf.summary.histogram("pre_activations", logits);
  229. });
  230. });
  231. final_tensor = tf.nn.softmax(logits, name: final_tensor_name);
  232. // The tf.contrib.quantize functions rewrite the graph in place for
  233. // quantization. The imported model graph has already been rewritten, so upon
  234. // calling these rewrites, only the newly added final layer will be
  235. // transformed.
  236. if (quantize_layer)
  237. {
  238. throw new NotImplementedException("quantize_layer");
  239. /*if (is_training)
  240. tf.contrib.quantize.create_training_graph();
  241. else
  242. tf.contrib.quantize.create_eval_graph();*/
  243. }
  244. tf.summary.histogram("activations", final_tensor);
  245. // If this is an eval graph, we don't need to add loss ops or an optimizer.
  246. if (!is_training)
  247. return (null, null, bottleneck_input, ground_truth_input, final_tensor);
  248. Tensor cross_entropy_mean = null;
  249. with(tf.name_scope("cross_entropy"), delegate
  250. {
  251. cross_entropy_mean = tf.losses.sparse_softmax_cross_entropy(
  252. labels: ground_truth_input, logits: logits);
  253. });
  254. tf.summary.scalar("cross_entropy", cross_entropy_mean);
  255. with(tf.name_scope("train"), delegate
  256. {
  257. var optimizer = tf.train.GradientDescentOptimizer(learning_rate);
  258. train_step = optimizer.minimize(cross_entropy_mean);
  259. });
  260. return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input,
  261. final_tensor);
  262. }
  263. private void variable_summaries(RefVariable var)
  264. {
  265. with(tf.name_scope("summaries"), delegate
  266. {
  267. var mean = tf.reduce_mean(var);
  268. tf.summary.scalar("mean", mean);
  269. Tensor stddev = null;
  270. with(tf.name_scope("stddev"), delegate {
  271. stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)));
  272. });
  273. tf.summary.scalar("stddev", stddev);
  274. tf.summary.scalar("max", tf.reduce_max(var));
  275. tf.summary.scalar("min", tf.reduce_min(var));
  276. tf.summary.histogram("histogram", var);
  277. });
  278. }
  279. private (Graph, Tensor, Tensor, bool) create_module_graph()
  280. {
  281. var (height, width) = (299, 299);
  282. return with(tf.Graph().as_default(), graph =>
  283. {
  284. tf.train.import_meta_graph("graph/InceptionV3.meta");
  285. Tensor resized_input_tensor = graph.OperationByName("Placeholder"); //tf.placeholder(tf.float32, new TensorShape(-1, height, width, 3));
  286. // var m = hub.Module(module_spec);
  287. Tensor bottleneck_tensor = graph.OperationByName("module_apply_default/hub_output/feature_vector/SpatialSqueeze");// m(resized_input_tensor);
  288. var wants_quantization = false;
  289. return (graph, bottleneck_tensor, resized_input_tensor, wants_quantization);
  290. });
  291. }
  292. private (NDArray, long[], string[]) get_random_cached_bottlenecks(Session sess, Dictionary<string, Dictionary<string, string[]>> image_lists,
  293. int how_many, string category, string bottleneck_dir, string image_dir,
  294. Tensor jpeg_data_tensor, Tensor decoded_image_tensor, Tensor resized_input_tensor,
  295. Tensor bottleneck_tensor, string module_name)
  296. {
  297. var bottlenecks = new List<float[]>();
  298. var ground_truths = new List<long>();
  299. var filenames = new List<string>();
  300. class_count = image_lists.Keys.Count;
  301. foreach (var unused_i in range(how_many))
  302. {
  303. int label_index = new Random().Next(class_count);
  304. string label_name = image_lists.Keys.ToArray()[label_index];
  305. int image_index = new Random().Next(MAX_NUM_IMAGES_PER_CLASS);
  306. string image_name = get_image_path(image_lists, label_name, image_index,
  307. image_dir, category);
  308. var bottleneck = get_or_create_bottleneck(
  309. sess, image_lists, label_name, image_index, image_dir, category,
  310. bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
  311. resized_input_tensor, bottleneck_tensor, module_name);
  312. bottlenecks.Add(bottleneck);
  313. ground_truths.Add(label_index);
  314. filenames.Add(image_name);
  315. }
  316. return (bottlenecks.ToArray(), ground_truths.ToArray(), filenames.ToArray());
  317. }
  318. /// <summary>
  319. /// Inserts the operations we need to evaluate the accuracy of our results.
  320. /// </summary>
  321. /// <param name="result_tensor"></param>
  322. /// <param name="ground_truth_tensor"></param>
  323. /// <returns></returns>
  324. private (Tensor, Tensor) add_evaluation_step(Tensor result_tensor, Tensor ground_truth_tensor)
  325. {
  326. Tensor evaluation_step = null, correct_prediction = null, prediction = null;
  327. with(tf.name_scope("accuracy"), scope =>
  328. {
  329. with(tf.name_scope("correct_prediction"), delegate
  330. {
  331. prediction = tf.argmax(result_tensor, 1);
  332. correct_prediction = tf.equal(prediction, ground_truth_tensor);
  333. });
  334. with(tf.name_scope("accuracy"), delegate
  335. {
  336. evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32));
  337. });
  338. });
  339. tf.summary.scalar("accuracy", evaluation_step);
  340. return (evaluation_step, prediction);
  341. }
  342. /// <summary>
  343. /// Ensures all the training, testing, and validation bottlenecks are cached.
  344. /// </summary>
  345. /// <param name="sess"></param>
  346. /// <param name="image_lists"></param>
  347. /// <param name="image_dir"></param>
  348. /// <param name="bottleneck_dir"></param>
  349. /// <param name="jpeg_data_tensor"></param>
  350. /// <param name="decoded_image_tensor"></param>
  351. /// <param name="resized_image_tensor"></param>
  352. /// <param name="bottleneck_tensor"></param>
  353. /// <param name="tfhub_module"></param>
  354. private void cache_bottlenecks(Session sess, Dictionary<string, Dictionary<string, string[]>> image_lists,
  355. string image_dir, string bottleneck_dir, Tensor jpeg_data_tensor, Tensor decoded_image_tensor,
  356. Tensor resized_input_tensor, Tensor bottleneck_tensor, string module_name)
  357. {
  358. int how_many_bottlenecks = 0;
  359. foreach(var (label_name, label_lists) in image_lists)
  360. {
  361. foreach(var category in new string[] { "training", "testing", "validation" })
  362. {
  363. var category_list = label_lists[category];
  364. foreach(var (index, unused_base_name) in enumerate(category_list))
  365. {
  366. get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir, category,
  367. bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
  368. resized_input_tensor, bottleneck_tensor, module_name);
  369. how_many_bottlenecks++;
  370. if (how_many_bottlenecks % 100 == 0)
  371. print($"{how_many_bottlenecks} bottleneck files created.");
  372. }
  373. }
  374. }
  375. }
  376. private float[] get_or_create_bottleneck(Session sess, Dictionary<string, Dictionary<string, string[]>> image_lists,
  377. string label_name, int index, string image_dir, string category, string bottleneck_dir,
  378. Tensor jpeg_data_tensor, Tensor decoded_image_tensor, Tensor resized_input_tensor,
  379. Tensor bottleneck_tensor, string module_name)
  380. {
  381. var label_lists = image_lists[label_name];
  382. var sub_dir_path = Path.Join(bottleneck_dir, label_name);
  383. Directory.CreateDirectory(sub_dir_path);
  384. string bottleneck_path = get_bottleneck_path(image_lists, label_name, index,
  385. bottleneck_dir, category, module_name);
  386. if (!File.Exists(bottleneck_path))
  387. create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
  388. image_dir, category, sess, jpeg_data_tensor,
  389. decoded_image_tensor, resized_input_tensor,
  390. bottleneck_tensor);
  391. var bottleneck_string = File.ReadAllText(bottleneck_path);
  392. var bottleneck_values = Array.ConvertAll(bottleneck_string.Split(','), x => float.Parse(x));
  393. return bottleneck_values;
  394. }
  395. private void create_bottleneck_file(string bottleneck_path, Dictionary<string, Dictionary<string, string[]>> image_lists,
  396. string label_name, int index, string image_dir, string category, Session sess,
  397. Tensor jpeg_data_tensor, Tensor decoded_image_tensor, Tensor resized_input_tensor, Tensor bottleneck_tensor)
  398. {
  399. // Create a single bottleneck file.
  400. print("Creating bottleneck at " + bottleneck_path);
  401. var image_path = get_image_path(image_lists, label_name, index, image_dir, category);
  402. if (!File.Exists(image_path))
  403. print($"File does not exist {image_path}");
  404. var image_data = File.ReadAllBytes(image_path);
  405. var bottleneck_values = run_bottleneck_on_image(
  406. sess, image_data, jpeg_data_tensor, decoded_image_tensor,
  407. resized_input_tensor, bottleneck_tensor);
  408. var values = bottleneck_values.Data<float>();
  409. var bottleneck_string = string.Join(",", values);
  410. File.WriteAllText(bottleneck_path, bottleneck_string);
  411. }
  412. /// <summary>
  413. /// Runs inference on an image to extract the 'bottleneck' summary layer.
  414. /// </summary>
  415. /// <param name="sess">Current active TensorFlow Session.</param>
  416. /// <param name="image_data">Data of raw JPEG data.</param>
  417. /// <param name="image_data_tensor">Input data layer in the graph.</param>
  418. /// <param name="decoded_image_tensor">Output of initial image resizing and preprocessing.</param>
  419. /// <param name="resized_input_tensor">The input node of the recognition graph.</param>
  420. /// <param name="bottleneck_tensor">Layer before the final softmax.</param>
  421. /// <returns></returns>
  422. private NDArray run_bottleneck_on_image(Session sess, byte[] image_data, Tensor image_data_tensor,
  423. Tensor decoded_image_tensor, Tensor resized_input_tensor, Tensor bottleneck_tensor)
  424. {
  425. // First decode the JPEG image, resize it, and rescale the pixel values.
  426. var resized_input_values = sess.run(decoded_image_tensor, new FeedItem(image_data_tensor, image_data));
  427. // Then run it through the recognition network.
  428. var bottleneck_values = sess.run(bottleneck_tensor, new FeedItem(resized_input_tensor, resized_input_values));
  429. bottleneck_values = np.squeeze(bottleneck_values);
  430. return bottleneck_values;
  431. }
  432. private string get_bottleneck_path(Dictionary<string, Dictionary<string, string[]>> image_lists, string label_name, int index,
  433. string bottleneck_dir, string category, string module_name)
  434. {
  435. module_name = (module_name.Replace("://", "~") // URL scheme.
  436. .Replace('/', '~') // URL and Unix paths.
  437. .Replace(':', '~').Replace('\\', '~')); // Windows paths.
  438. return get_image_path(image_lists, label_name, index, bottleneck_dir,
  439. category) + "_" + module_name + ".txt";
  440. }
  441. private string get_image_path(Dictionary<string, Dictionary<string, string[]>> image_lists, string label_name,
  442. int index, string image_dir, string category)
  443. {
  444. if (!image_lists.ContainsKey(label_name))
  445. print($"Label does not exist {label_name}");
  446. var label_lists = image_lists[label_name];
  447. if (!label_lists.ContainsKey(category))
  448. print($"Category does not exist {category}");
  449. var category_list = label_lists[category];
  450. if (category_list.Length == 0)
  451. print($"Label {label_name} has no images in the category {category}.");
  452. var mod_index = index % len(category_list);
  453. var base_name = category_list[mod_index].Split(Path.DirectorySeparatorChar).Last();
  454. var sub_dir = label_name;
  455. var full_path = Path.Join(image_dir, sub_dir, base_name);
  456. return full_path;
  457. }
  458. public void PrepareData()
  459. {
  460. // get a set of images to teach the network about the new classes
  461. string fileName = "flower_photos.tgz";
  462. string url = $"http://download.tensorflow.org/models/{fileName}";
  463. Web.Download(url, data_dir, fileName);
  464. Compress.ExtractTGZ(Path.Join(data_dir, fileName), data_dir);
  465. // download graph meta data
  466. url = "https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/graph/InceptionV3.meta";
  467. Web.Download(url, "graph", "InceptionV3.meta");
  468. // Prepare necessary directories that can be used during training
  469. Directory.CreateDirectory(summaries_dir);
  470. Directory.CreateDirectory(bottleneck_dir);
  471. // Look at the folder structure, and create lists of all the images.
  472. image_lists = create_image_lists();
  473. class_count = len(image_lists);
  474. if (class_count == 0)
  475. print($"No valid folders of images found at {image_dir}");
  476. if (class_count == 1)
  477. print("Only one valid folder of images found at " +
  478. image_dir +
  479. " - multiple classes are needed for classification.");
  480. }
  481. private (Tensor, Tensor) add_jpeg_decoding()
  482. {
  483. // height, width, depth
  484. var input_dim = (299, 299, 3);
  485. var jpeg_data = tf.placeholder(tf.chars, name: "DecodeJPGInput");
  486. var decoded_image = tf.image.decode_jpeg(jpeg_data, channels: input_dim.Item3);
  487. // Convert from full range of uint8 to range [0,1] of float32.
  488. var decoded_image_as_float = tf.image.convert_image_dtype(decoded_image, tf.float32);
  489. var decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0);
  490. var resize_shape = tf.stack(new int[] { input_dim.Item1, input_dim.Item2 });
  491. var resize_shape_as_int = tf.cast(resize_shape, dtype: tf.int32);
  492. var resized_image = tf.image.resize_bilinear(decoded_image_4d, resize_shape_as_int);
  493. return (jpeg_data, resized_image);
  494. }
  495. /// <summary>
  496. /// Builds a list of training images from the file system.
  497. /// </summary>
  498. private Dictionary<string, Dictionary<string, string[]>> create_image_lists()
  499. {
  500. var sub_dirs = tf.gfile.Walk(image_dir)
  501. .Select(x => x.Item1)
  502. .OrderBy(x => x)
  503. .ToArray();
  504. var result = new Dictionary<string, Dictionary<string, string[]>>();
  505. foreach(var sub_dir in sub_dirs)
  506. {
  507. var dir_name = sub_dir.Split(Path.DirectorySeparatorChar).Last();
  508. print($"Looking for images in '{dir_name}'");
  509. var file_list = Directory.GetFiles(sub_dir);
  510. if (len(file_list) < 20)
  511. print($"WARNING: Folder has less than 20 images, which may cause issues.");
  512. var label_name = dir_name.ToLower();
  513. result[label_name] = new Dictionary<string, string[]>();
  514. int testing_count = (int)Math.Floor(file_list.Length * testing_percentage);
  515. int validation_count = (int)Math.Floor(file_list.Length * validation_percentage);
  516. result[label_name]["testing"] = file_list.Take(testing_count).ToArray();
  517. result[label_name]["validation"] = file_list.Skip(testing_count).Take(validation_count).ToArray();
  518. result[label_name]["training"] = file_list.Skip(testing_count + validation_count).ToArray();
  519. }
  520. return result;
  521. }
  522. }
  523. }