├── README.md ├── LICENSE └── active_learning_for_images.py /README.md: -------------------------------------------------------------------------------- 1 | # Active Learning with TensorFlow and ImageNet 2 | Coding exercise to extend TensorFlow for ImageNet to Active Learning, for use in a job interview or similar context. 3 | 4 | The code runs, but _IS DELIBERATELY A BAD IMPLEMENTATION OF ACTIVE LEARNING_ 5 | 6 | The task is to fix this code. 7 | 8 | # Context 9 | 10 | A company has approached you that wants to classify a large set of sports images according to the ImageNet set of labels. 11 | 12 | However, there are several problems: 13 | 1. They are trying to classify with the pre-compiled TensorFlow model, but the model is not very accurate on their data. So, they want to manually label some of their images to retrain the classifier on their own images. 14 | 1. They have millions of images, so they cannot manually label them all. 15 | 1. Their collection of images may include some that are not related to sports. They want to make sure the sports images are filtered out, but they don't otherwise care about these images. 16 | 17 | This is a real-world situation that occurs regularly. For this exercise, we will use the open set of sports images from CrowdFlower's Data for Everyone program: 18 | 19 | https://www.crowdflower.com/data-for-everyone/ 20 | 21 | ## About ImageNet 22 | 23 | ImageNet uses a classification scheme based on WordNet, where words are grouped by synonyms, called 'synsets'. Each 'synset' is a group of closely related words. These synsets are the labels for this task, which you will see when you run the code. For example, the label for 'racing car' is `'racer, race car, racing car'`. 24 | 25 | The output from the classifier will therefore look something like this: 26 | 27 | `['candle, taper, wax light', 0.079653569], ['wreck', 0.055132806], ['tow truck, tow car, wrecker', 0.038218945], ...` 28 | 29 | This indicates that the image being classified has a 0.07965 probability of being a `'candle, taper, wax light'`, a 0.05513 probability of being a `'wreck'`, etc. 30 | 31 | While the classifier is flat, WordNet itself organizes the synsets in hierarchies. For example 'baseball' and 'cricket' could be types of 'sport', and in turn 'sport' could be a type of 'activity'. Generally, items that are closer in the hierarchy tend to be closer in real-life. For example, 'sports car' and 'racing car' are both types of 'cars' in WordNet/ImageNet, and are also closely related in real-life. By contrast, 'sports car' and 'pine tree' are not closely related in WordNet/ImageNet, or in real-life. 32 | 33 | 34 | ## Getting started 35 | 36 | A (250MB) subset of the images is available at: 37 | 38 | http://www.robertmunro.com/research/test_images.tar 39 | 40 | The starter code is in the same directory as this readme: 41 | 42 | `active_learning_for_images.py` 43 | 44 | 45 | # Exercise 46 | 47 | Your exercise is to improve the code so that it: 48 | 1. takes a collection of unlabled images 49 | 1. attempts to classify each image with Inception trained on ImageNet (2012) 50 | 1. orders the images according to how each should be manually labled, to create the best possible training data from the new images. 51 | 52 | Steps 1 and 2 are implemented (but could be improved). 53 | 54 | Step 3 currently orders the images from the most-to-least confidently classified, which is a bad strategy. 55 | 56 | Most of the code to be edited is within `order_images_for_active_learning()`, but you may edit any code that you think will improve the output. 57 | 58 | # Potential Solutions 59 | 60 | There are many extensions to this code, from a 1 hour exercise to improve how confidence is used to order the images, to a multiple week exercise that could included retraining all/parts of the model and providing interfaces that are optimal for different kinds of human labeling. 61 | 62 | ## 2 Hour Exercise 63 | 64 | For the 2 Hour Exercise, there is a coding and a written component. 65 | 66 | It is recommended that you take 30 minutes to become familiar with the problem and decide on your approach, 60 minutes for the coding exercise, and 30 minutes on the writing exercise. 67 | 68 | You may use any resources that are available to you on your machine or on the internet. You can ask the instructor for any clarifications questions, but please complete this as a solo exercise without live input from other people. 69 | 70 | ### Coding Exercise 71 | 72 | Reimplement `order_images_for_active_learning()` so that it has a better strategy to determine which images will be the most valuable to classify. Your strategy should identify images as highly valuable if are one or more of the following: 73 | 1. Images that seem unknown to the current TensorFlow model - this means that they are likely to be the most different from those in the ImageNet training data. 74 | 1. Images that are hard for the current TensorFlow model to classify - this means that they are likely to be images that would produce errors. 75 | 1. Images that cover as broad a selection of labels as possible - the customer wants the model to be accurate across all the labels that they care about. 76 | 1. Images that help with evaluation - the customer wants to be certain that they can correctly measure the accuracy of their models. 77 | 78 | Aim to have working code. It's likely that you won't have time to implement everything that you would like, so the writing exercise allows you to talk about the other strategies that you thought about: 79 | 80 | ### Writing Exercise 81 | 82 | For the writing exercise, pretend like you are addressing the customer about what you have implemented and what you are proposing to build. You can keep the style casual: assume it's a professional email sent to their technical team, not a formal proposal for their executives. 83 | 84 | First, write a 1-paragraph description of what you implemented in the coding exercise, justifying each decision. There are many possible solutions that can be implemented in about 60 minutes, so this is more about your reasoning than your exact strategy. 85 | 86 | Second, please write a few paragraphs or bullet points proposing other strategies that you might with the customer, covering: 87 | 1. How else could you ensure that you covered as broad a selection of images as possible? 88 | 1. What kind of user interfaces could a human annotator use to manually add the labels efficiently and accurately? 89 | 1. How would you retrain the model with the newly labelled images, and what might be the pros and cons of retraining TensorFlow on the newly labeled images very frequently vs training only a few times or even just once? 90 | 1. How would you evaluate the effectiveness of your strategies to see what worked best? 91 | 92 | ### Submitting the 2 Hour Exercise 93 | 94 | Please email the updated code and written exercise to the instructor when you are complete. 95 | 96 | 97 | # Installation and code source 98 | 99 | A (250MB) subset of the images is available at: 100 | 101 | http://www.robertmunro.com/research/test_images.tar 102 | 103 | The company made starter code that is in this same directory at: 104 | 105 | `active_learning_for_images.py` 106 | 107 | The code is in the style of TensorFlow tutorials and is adapted with thanks to the original authors of: 108 | 109 | https://github.com/tensorflow/models/blob/master/tutorials/image/imagenet/classify_image.py 110 | 111 | The code can be run in the same tutorial folder (although not required): 112 | 113 | https://github.com/tensorflow/models/tree/master/tutorials/image/imagenet 114 | 115 | To install TensorFlow and for more context on this problem, see: 116 | 117 | https://www.tensorflow.org/tutorials/image_recognition 118 | 119 | In short, you can clone tensorflow at: 120 | 121 | `git clone https://github.com/tensorflow/models` 122 | 123 | And then find the location of the tutorial from which this was based at: 124 | 125 | `cd models/tutorials/image/imagenet` 126 | 127 | This tutorial is not required reading for this exercise, but will give you more context if you are not familiar with TensorFlow or ImageNet. 128 | 129 | If you are on a Mac, you might need to install TensorFlow with the following command: 130 | 131 | `sudo -H pip install tensorflow --upgrade --ignore-installed` 132 | 133 | Usage: 134 | 135 | `python active_learning_for_images.py --directory=DIRECTORY_OF_IMAGES` 136 | 137 | Where `DIRECTORY_OF_IMAGES` is the directory containing the JPGs you want to apply Active Learning to. 138 | 139 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /active_learning_for_images.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Robert Munro, with additional code from sources as indicated below. 2 | # 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 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | """Active Learning for ImageNet 17 | 18 | This code is designed as a coding exercise, for use in a job interview or similar situation. 19 | 20 | The code runs, but IS DELIBERATELY A BAD IMPLEMENTATION OF ACTIVE LEARNING 21 | 22 | The exercise is to improve the code so that it: 23 | 1) takes collection of unlabled images 24 | 2) attempts to classify each image with Inception trained on ImageNet (2012) 25 | 3) orders the images according to how ecch should be manually labled, to create the best possible training data from the new images. 26 | 27 | Steps 1 and 2 are implemented (but could be improved). 28 | 29 | Step 3 currently orders the images from the most-to-least confidently classified, which is a bad strategy. 30 | 31 | There are many extensions to this code, from a 1 hour exercise to improve how confidence is used, to a multiple week exercice that included retraining all/parts of the model and provided interfaces that were optimal for retraining. 32 | 33 | The code is in the style of TensorFlow tutorials and is adapted with thanks to the original authors of: 34 | https://github.com/tensorflow/models/blob/master/tutorials/image/imagenet/classify_image.py 35 | 36 | The code can be run in the same tutorial folder (although not required): 37 | https://github.com/tensorflow/models/tree/master/tutorials/image/imagenet 38 | 39 | To install TensorFlow and for more context on this problem, see: 40 | https://www.tensorflow.org/tutorials/image_recognition 41 | In short, you can clone tensorflow at: 42 | git clone https://github.com/tensorflow/models 43 | And then find the location of the tutorial at: 44 | cd models/tutorials/image/imagenet 45 | If you are on a Mac, you might need to install tensorflow with the following command: 46 | sudo -H pip install tensorflow --upgrade --ignore-installed 47 | 48 | Usage: 49 | python active_learning_for_images.py --directory=DIRECTORY_OF_IMAGES 50 | 51 | Where DIRECTORY_OF_IMAGES is the directory containing the JPGs you want apply Active Learning to. 52 | 53 | Output: 54 | a printed listed of image names, ordered by how important they are for the training data. 55 | 56 | """ 57 | 58 | from __future__ import absolute_import 59 | from __future__ import division 60 | from __future__ import print_function 61 | 62 | import argparse 63 | import os.path 64 | import re 65 | import sys 66 | import tarfile 67 | 68 | import numpy as np 69 | from six.moves import urllib 70 | import tensorflow as tf 71 | 72 | FLAGS = None 73 | 74 | # pylint: disable=line-too-long 75 | DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' 76 | # pylint: enable=line-too-long 77 | 78 | 79 | class NodeLookup(object): 80 | """Converts integer node ID's to human readable labels.""" 81 | 82 | def __init__(self, 83 | label_lookup_path=None, 84 | uid_lookup_path=None): 85 | if not label_lookup_path: 86 | label_lookup_path = os.path.join( 87 | FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt') 88 | if not uid_lookup_path: 89 | uid_lookup_path = os.path.join( 90 | FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt') 91 | self.node_lookup = self.load(label_lookup_path, uid_lookup_path) 92 | 93 | def load(self, label_lookup_path, uid_lookup_path): 94 | """Loads a human readable English name for each softmax node. 95 | 96 | Args: 97 | label_lookup_path: string UID to integer node ID. 98 | uid_lookup_path: string UID to human-readable string. 99 | 100 | Returns: 101 | dict from integer node ID to human-readable string. 102 | """ 103 | if not tf.gfile.Exists(uid_lookup_path): 104 | tf.logging.fatal('File does not exist %s', uid_lookup_path) 105 | if not tf.gfile.Exists(label_lookup_path): 106 | tf.logging.fatal('File does not exist %s', label_lookup_path) 107 | 108 | # Loads mapping from string UID to human-readable string 109 | proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines() 110 | uid_to_human = {} 111 | p = re.compile(r'[n\d]*[ \S,]*') 112 | for line in proto_as_ascii_lines: 113 | parsed_items = p.findall(line) 114 | uid = parsed_items[0] 115 | human_string = parsed_items[2] 116 | uid_to_human[uid] = human_string 117 | 118 | # Loads mapping from string UID to integer node ID. 119 | node_id_to_uid = {} 120 | proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines() 121 | for line in proto_as_ascii: 122 | if line.startswith(' target_class:'): 123 | target_class = int(line.split(': ')[1]) 124 | if line.startswith(' target_class_string:'): 125 | target_class_string = line.split(': ')[1] 126 | node_id_to_uid[target_class] = target_class_string[1:-2] 127 | 128 | # Loads the final mapping of integer node ID to human-readable string 129 | node_id_to_name = {} 130 | for key, val in node_id_to_uid.items(): 131 | if val not in uid_to_human: 132 | tf.logging.fatal('Failed to locate: %s', val) 133 | name = uid_to_human[val] 134 | node_id_to_name[key] = name 135 | 136 | return node_id_to_name 137 | 138 | def id_to_string(self, node_id): 139 | if node_id not in self.node_lookup: 140 | return '' 141 | return self.node_lookup[node_id] 142 | 143 | 144 | def create_graph(): 145 | """Creates a graph from saved GraphDef file and returns a saver.""" 146 | # Creates graph from saved graph_def.pb. 147 | with tf.gfile.FastGFile(os.path.join( 148 | FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f: 149 | graph_def = tf.GraphDef() 150 | graph_def.ParseFromString(f.read()) 151 | _ = tf.import_graph_def(graph_def, name='') 152 | 153 | 154 | def run_inference_on_image(image): 155 | """Runs inference on an image. 156 | 157 | Args: 158 | image: Image file name. 159 | 160 | Returns: 161 | Nothing 162 | """ 163 | 164 | # Creates graph from saved GraphDef. 165 | create_graph() 166 | 167 | if not tf.gfile.Exists(image): 168 | tf.logging.fatal('File does not exist %s', image) 169 | image_data = tf.gfile.FastGFile(image, 'rb').read() 170 | 171 | 172 | with tf.Session() as sess: 173 | # Some useful tensors: 174 | # 175 | # 'softmax:0': A tensor containing the normalized prediction across 176 | # 1000 labels. 177 | # 178 | # 'pool_3:0': A tensor containing the next-to-last layer containing 2048 179 | # float description of the image. 180 | # 181 | # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG 182 | # encoding of the image. 183 | # 184 | # Runs the softmax tensor by feeding the image_data as input to the graph. 185 | 186 | softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') 187 | predictions = sess.run(softmax_tensor, 188 | {'DecodeJpeg/contents:0': image_data}) 189 | predictions = np.squeeze(predictions) 190 | 191 | # Creates node ID --> English string lookup. 192 | node_lookup = NodeLookup() 193 | 194 | top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1] 195 | 196 | scores = [] # all scores for this image 197 | 198 | for node_id in top_k: 199 | human_string = node_lookup.id_to_string(node_id) 200 | score = predictions[node_id] 201 | 202 | # Record the label (human readable string) and the score (confidence), 203 | # for the most confident labels for each prediction 204 | scores.append([human_string, score]) 205 | 206 | # print('%s (score = %.5f)' % (human_string, score)) 207 | 208 | # return all the labels/scores for this image 209 | return scores 210 | 211 | 212 | def maybe_download_and_extract(): 213 | """Download and extract model tar file.""" 214 | dest_directory = FLAGS.model_dir 215 | if not os.path.exists(dest_directory): 216 | os.makedirs(dest_directory) 217 | filename = DATA_URL.split('/')[-1] 218 | filepath = os.path.join(dest_directory, filename) 219 | if not os.path.exists(filepath): 220 | def _progress(count, block_size, total_size): 221 | sys.stdout.write('\r>> Downloading %s %.1f%%' % ( 222 | filename, float(count * block_size) / float(total_size) * 100.0)) 223 | sys.stdout.flush() 224 | filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress) 225 | print() 226 | statinfo = os.stat(filepath) 227 | print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') 228 | tarfile.open(filepath, 'r:gz').extractall(dest_directory) 229 | 230 | 231 | 232 | def order_images_for_active_learning(directory): 233 | """takes a directory containing JPGs, and returns the order in which they should be annotated, 234 | in order to maximize the accuracy of the trained model as quickly as possible.""" 235 | 236 | # the image and its scores for each label 237 | image_scores = [] 238 | 239 | # get the current predictions for each image 240 | images = os.listdir(directory) 241 | for image in images: 242 | if image.endswith('jpg'): 243 | 244 | with tf.Graph().as_default(): 245 | try: 246 | scores = run_inference_on_image(directory+'/'+image) 247 | 248 | top_guess = scores[0][0] 249 | top_score = scores[0][1] 250 | 251 | # TO ADD TO ARRAY OF ALL SCORES: [IMAGE_NAME, TOP_LABEL, TOP_SCORE, [ALL_SCORES]] 252 | image_info = [image, top_guess, top_score, scores] 253 | 254 | print(image_info) # DEBUGGING: de-comment to see what is recorded for each image 255 | image_scores.append(image_info) 256 | 257 | except ValueError: 258 | # skip files that produce an error 259 | sys.stderr.write("Couldn't get a prediction on "+image+" - skipping\n") 260 | 261 | 262 | # the final ordered list of images that we will return 263 | sorted_images = [] 264 | 265 | #BEGIN CODE TO ORDER IMAGES BY IMPORTANCE TO ADD HUMAN LABEL: 266 | 267 | # SORT ARRAY OF ALL SCORES BY 'TOP_SCORE' FOR EACH IMAGE 268 | image_scores.sort(key=lambda x: x[2], reverse=True) 269 | 270 | for score in image_scores: 271 | sorted_images.append(score[0]) 272 | print("\n") 273 | print(score) 274 | 275 | #END CODE TO ORDER IMAGES BY IMPORTANCE TO ADD HUMAN LABEL 276 | 277 | return sorted_images 278 | 279 | 280 | 281 | def main(_): 282 | maybe_download_and_extract() # download model if not already 283 | 284 | #check for if a dictionary was passed as an argument 285 | directory = (FLAGS.directory if FLAGS.directory else 286 | os.path.join(FLAGS.model_dir, '/')) 287 | 288 | #order the images 289 | ordered_images = order_images_for_active_learning(directory) 290 | 291 | #print the optimal order 292 | print(ordered_images) 293 | 294 | 295 | if __name__ == '__main__': 296 | parser = argparse.ArgumentParser() 297 | # classify_image_graph_def.pb: 298 | # Binary representation of the GraphDef protocol buffer. 299 | # imagenet_synset_to_human_label_map.txt: 300 | # Map from synset ID to a human readable string. 301 | # imagenet_2012_challenge_label_map_proto.pbtxt: 302 | # Text representation of a protocol buffer mapping a label to synset ID. 303 | parser.add_argument( 304 | '--model_dir', 305 | type=str, 306 | default='/tmp/imagenet', 307 | help="""\ 308 | Path to classify_image_graph_def.pb, 309 | imagenet_synset_to_human_label_map.txt, and 310 | imagenet_2012_challenge_label_map_proto.pbtxt.\ 311 | """ 312 | ) 313 | parser.add_argument( 314 | '--directory', 315 | type=str, 316 | default='', 317 | help='Absolute path to directory of images.' 318 | ) 319 | parser.add_argument( 320 | '--num_top_predictions', 321 | type=int, 322 | default=5, 323 | help='Return this many predictions per image.' 324 | ) 325 | FLAGS, unparsed = parser.parse_known_args() 326 | tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 327 | 328 | --------------------------------------------------------------------------------