├── .gitignore ├── README.md ├── label_image.py ├── results ├── A_1105_1.LEFT_MLO.LJPEG.1_highpass.png ├── A_1363_1.RIGHT_MLO.LJPEG.1_highpass.png ├── benign.png ├── final.png ├── malevolent.png └── normal.png ├── retrain.py └── retrained_labels.txt /.gitignore: -------------------------------------------------------------------------------- 1 | /bottlenecks 2 | /inception 3 | /mammogram_photos 4 | /training_summaries 5 | retrained_graph.pb -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TensorFlow Mammogram Image Classifier 2 | By using a convolutional neural network (CNN) this program classifies microcalcifications and masses in a mammogram as either *benign* or *malignant*. If there are no masses present in the breast tissue then the mammogram will be classified as *normal*. The biggest challenge in this project was that the amount of mammogram images without any segmentation or overlay available online (publicly) was scarce and not feasible to train an entire CNN on, thus why I trained the last layer of Google's Inception v3 network on pre-segmented image data. The .gitignore contains files that are installed via the retrain.py script that is pulled from TensorFlow. 3 | ![Left](/results/A_1105_1.LEFT_MLO.LJPEG.1_highpass.png) ![Right](/results/A_1363_1.RIGHT_MLO.LJPEG.1_highpass.png) 4 | 5 | ## Tools & Resources 6 | - [TensorFlow for Poets](https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#0) 7 | - [Docker](https://www.docker.com/) 8 | - [Digital Database for Screening Mammography (DDSM)](http://marathon.csee.usf.edu/Mammography/Database.html) 9 | 10 | ## Results 11 | #### Normal image test 12 | ![Normal Test](/results/normal.png) 13 | 14 | #### Benign image test 15 | ![Benign Test](/results/benign.png) 16 | 17 | #### Malignant image test 18 | ![Malevolent Test](/results/malevolent.png) 19 | 20 | ## Overall Accuracy 21 | ![Final Test](/results/final.png) 22 | -------------------------------------------------------------------------------- /label_image.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | 3 | import tensorflow as tf 4 | 5 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 6 | 7 | # change this as you see fit 8 | image_path = sys.argv[1] 9 | 10 | # Read in the image_data 11 | image_data = tf.gfile.FastGFile(image_path, 'rb').read() 12 | 13 | # Loads label file, strips off carriage return 14 | label_lines = [line.rstrip() for line 15 | in tf.gfile.GFile("retrained_labels.txt")] 16 | 17 | # Unpersists graph from file 18 | with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f: 19 | graph_def = tf.GraphDef() 20 | graph_def.ParseFromString(f.read()) 21 | tf.import_graph_def(graph_def, name='') 22 | 23 | with tf.Session() as sess: 24 | # Feed the image_data as input to the graph and get first prediction 25 | softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') 26 | 27 | predictions = sess.run(softmax_tensor, \ 28 | {'DecodeJpeg/contents:0': image_data}) 29 | 30 | # Sort to show labels of first prediction in order of confidence 31 | top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] 32 | 33 | for node_id in top_k: 34 | human_string = label_lines[node_id] 35 | score = predictions[0][node_id] 36 | print('%s (score = %.5f)' % (human_string, score)) -------------------------------------------------------------------------------- /results/A_1105_1.LEFT_MLO.LJPEG.1_highpass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akashxg/Mammogram-Image-Classifier/8970e3fa783ee348872b6ece49e6e3d292e6aa6c/results/A_1105_1.LEFT_MLO.LJPEG.1_highpass.png -------------------------------------------------------------------------------- /results/A_1363_1.RIGHT_MLO.LJPEG.1_highpass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akashxg/Mammogram-Image-Classifier/8970e3fa783ee348872b6ece49e6e3d292e6aa6c/results/A_1363_1.RIGHT_MLO.LJPEG.1_highpass.png -------------------------------------------------------------------------------- /results/benign.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akashxg/Mammogram-Image-Classifier/8970e3fa783ee348872b6ece49e6e3d292e6aa6c/results/benign.png -------------------------------------------------------------------------------- /results/final.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akashxg/Mammogram-Image-Classifier/8970e3fa783ee348872b6ece49e6e3d292e6aa6c/results/final.png -------------------------------------------------------------------------------- /results/malevolent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akashxg/Mammogram-Image-Classifier/8970e3fa783ee348872b6ece49e6e3d292e6aa6c/results/malevolent.png -------------------------------------------------------------------------------- /results/normal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akashxg/Mammogram-Image-Classifier/8970e3fa783ee348872b6ece49e6e3d292e6aa6c/results/normal.png -------------------------------------------------------------------------------- /retrain.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | 5 | import argparse 6 | from datetime import datetime 7 | import hashlib 8 | import os.path 9 | import random 10 | import re 11 | import struct 12 | import sys 13 | import tarfile 14 | 15 | import numpy as np 16 | from six.moves import urllib 17 | import tensorflow as tf 18 | 19 | from tensorflow.python.framework import graph_util 20 | from tensorflow.python.framework import tensor_shape 21 | from tensorflow.python.platform import gfile 22 | from tensorflow.python.util import compat 23 | 24 | FLAGS = None 25 | 26 | # These are all parameters that are tied to the particular model architecture 27 | # we're using for Inception v3. These include things like tensor names and their 28 | # sizes. If you want to adapt this script to work with another model, you will 29 | # need to update these to reflect the values in the network you're using. 30 | # pylint: disable=line-too-long 31 | DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' 32 | # pylint: enable=line-too-long 33 | BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0' 34 | BOTTLENECK_TENSOR_SIZE = 2048 35 | MODEL_INPUT_WIDTH = 299 36 | MODEL_INPUT_HEIGHT = 299 37 | MODEL_INPUT_DEPTH = 3 38 | JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0' 39 | RESIZED_INPUT_TENSOR_NAME = 'ResizeBilinear:0' 40 | MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1 # ~134M 41 | 42 | 43 | def create_image_lists(image_dir, testing_percentage, validation_percentage): 44 | """Builds a list of training images from the file system. 45 | 46 | Analyzes the sub folders in the image directory, splits them into stable 47 | training, testing, and validation sets, and returns a data structure 48 | describing the lists of images for each label and their paths. 49 | 50 | Args: 51 | image_dir: String path to a folder containing subfolders of images. 52 | testing_percentage: Integer percentage of the images to reserve for tests. 53 | validation_percentage: Integer percentage of images reserved for validation. 54 | 55 | Returns: 56 | A dictionary containing an entry for each label subfolder, with images split 57 | into training, testing, and validation sets within each label. 58 | """ 59 | if not gfile.Exists(image_dir): 60 | print("Image directory '" + image_dir + "' not found.") 61 | return None 62 | result = {} 63 | sub_dirs = [x[0] for x in gfile.Walk(image_dir)] 64 | # The root directory comes first, so skip it. 65 | is_root_dir = True 66 | for sub_dir in sub_dirs: 67 | if is_root_dir: 68 | is_root_dir = False 69 | continue 70 | extensions = ['jpg', 'jpeg', 'JPG', 'JPEG'] 71 | file_list = [] 72 | dir_name = os.path.basename(sub_dir) 73 | if dir_name == image_dir: 74 | continue 75 | print("Looking for images in '" + dir_name + "'") 76 | for extension in extensions: 77 | file_glob = os.path.join(image_dir, dir_name, '*.' + extension) 78 | file_list.extend(gfile.Glob(file_glob)) 79 | if not file_list: 80 | print('No files found') 81 | continue 82 | if len(file_list) < 20: 83 | print('WARNING: Folder has less than 20 images, which may cause issues.') 84 | elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS: 85 | print('WARNING: Folder {} has more than {} images. Some images will ' 86 | 'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS)) 87 | label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower()) 88 | training_images = [] 89 | testing_images = [] 90 | validation_images = [] 91 | for file_name in file_list: 92 | base_name = os.path.basename(file_name) 93 | # We want to ignore anything after '_nohash_' in the file name when 94 | # deciding which set to put an image in, the data set creator has a way of 95 | # grouping photos that are close variations of each other. For example 96 | # this is used in the plant disease data set to group multiple pictures of 97 | # the same leaf. 98 | hash_name = re.sub(r'_nohash_.*$', '', file_name) 99 | # This looks a bit magical, but we need to decide whether this file should 100 | # go into the training, testing, or validation sets, and we want to keep 101 | # existing files in the same set even if more files are subsequently 102 | # added. 103 | # To do that, we need a stable way of deciding based on just the file name 104 | # itself, so we do a hash of that and then use that to generate a 105 | # probability value that we use to assign it. 106 | hash_name_hashed = hashlib.sha1(compat.as_bytes(hash_name)).hexdigest() 107 | percentage_hash = ((int(hash_name_hashed, 16) % 108 | (MAX_NUM_IMAGES_PER_CLASS + 1)) * 109 | (100.0 / MAX_NUM_IMAGES_PER_CLASS)) 110 | if percentage_hash < validation_percentage: 111 | validation_images.append(base_name) 112 | elif percentage_hash < (testing_percentage + validation_percentage): 113 | testing_images.append(base_name) 114 | else: 115 | training_images.append(base_name) 116 | result[label_name] = { 117 | 'dir': dir_name, 118 | 'training': training_images, 119 | 'testing': testing_images, 120 | 'validation': validation_images, 121 | } 122 | return result 123 | 124 | 125 | def get_image_path(image_lists, label_name, index, image_dir, category): 126 | """"Returns a path to an image for a label at the given index. 127 | 128 | Args: 129 | image_lists: Dictionary of training images for each label. 130 | label_name: Label string we want to get an image for. 131 | index: Int offset of the image we want. This will be moduloed by the 132 | available number of images for the label, so it can be arbitrarily large. 133 | image_dir: Root folder string of the subfolders containing the training 134 | images. 135 | category: Name string of set to pull images from - training, testing, or 136 | validation. 137 | 138 | Returns: 139 | File system path string to an image that meets the requested parameters. 140 | 141 | """ 142 | if label_name not in image_lists: 143 | tf.logging.fatal('Label does not exist %s.', label_name) 144 | label_lists = image_lists[label_name] 145 | if category not in label_lists: 146 | tf.logging.fatal('Category does not exist %s.', category) 147 | category_list = label_lists[category] 148 | if not category_list: 149 | tf.logging.fatal('Label %s has no images in the category %s.', 150 | label_name, category) 151 | mod_index = index % len(category_list) 152 | base_name = category_list[mod_index] 153 | sub_dir = label_lists['dir'] 154 | full_path = os.path.join(image_dir, sub_dir, base_name) 155 | return full_path 156 | 157 | 158 | def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, 159 | category): 160 | """"Returns a path to a bottleneck file for a label at the given index. 161 | 162 | Args: 163 | image_lists: Dictionary of training images for each label. 164 | label_name: Label string we want to get an image for. 165 | index: Integer offset of the image we want. This will be moduloed by the 166 | available number of images for the label, so it can be arbitrarily large. 167 | bottleneck_dir: Folder string holding cached files of bottleneck values. 168 | category: Name string of set to pull images from - training, testing, or 169 | validation. 170 | 171 | Returns: 172 | File system path string to an image that meets the requested parameters. 173 | """ 174 | return get_image_path(image_lists, label_name, index, bottleneck_dir, 175 | category) + '.txt' 176 | 177 | 178 | def create_inception_graph(): 179 | """"Creates a graph from saved GraphDef file and returns a Graph object. 180 | 181 | Returns: 182 | Graph holding the trained Inception network, and various tensors we'll be 183 | manipulating. 184 | """ 185 | with tf.Session() as sess: 186 | model_filename = os.path.join( 187 | FLAGS.model_dir, 'classify_image_graph_def.pb') 188 | with gfile.FastGFile(model_filename, 'rb') as f: 189 | graph_def = tf.GraphDef() 190 | graph_def.ParseFromString(f.read()) 191 | bottleneck_tensor, jpeg_data_tensor, resized_input_tensor = ( 192 | tf.import_graph_def(graph_def, name='', return_elements=[ 193 | BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME, 194 | RESIZED_INPUT_TENSOR_NAME])) 195 | return sess.graph, bottleneck_tensor, jpeg_data_tensor, resized_input_tensor 196 | 197 | 198 | def run_bottleneck_on_image(sess, image_data, image_data_tensor, 199 | bottleneck_tensor): 200 | """Runs inference on an image to extract the 'bottleneck' summary layer. 201 | 202 | Args: 203 | sess: Current active TensorFlow Session. 204 | image_data: String of raw JPEG data. 205 | image_data_tensor: Input data layer in the graph. 206 | bottleneck_tensor: Layer before the final softmax. 207 | 208 | Returns: 209 | Numpy array of bottleneck values. 210 | """ 211 | bottleneck_values = sess.run( 212 | bottleneck_tensor, 213 | {image_data_tensor: image_data}) 214 | bottleneck_values = np.squeeze(bottleneck_values) 215 | return bottleneck_values 216 | 217 | 218 | def maybe_download_and_extract(): 219 | """Download and extract model tar file. 220 | 221 | If the pretrained model we're using doesn't already exist, this function 222 | downloads it from the TensorFlow.org website and unpacks it into a directory. 223 | """ 224 | dest_directory = FLAGS.model_dir 225 | if not os.path.exists(dest_directory): 226 | os.makedirs(dest_directory) 227 | filename = DATA_URL.split('/')[-1] 228 | filepath = os.path.join(dest_directory, filename) 229 | if not os.path.exists(filepath): 230 | 231 | def _progress(count, block_size, total_size): 232 | sys.stdout.write('\r>> Downloading %s %.1f%%' % 233 | (filename, 234 | float(count * block_size) / float(total_size) * 100.0)) 235 | sys.stdout.flush() 236 | 237 | filepath, _ = urllib.request.urlretrieve(DATA_URL, 238 | filepath, 239 | _progress) 240 | print() 241 | statinfo = os.stat(filepath) 242 | print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') 243 | tarfile.open(filepath, 'r:gz').extractall(dest_directory) 244 | 245 | 246 | def ensure_dir_exists(dir_name): 247 | """Makes sure the folder exists on disk. 248 | 249 | Args: 250 | dir_name: Path string to the folder we want to create. 251 | """ 252 | if not os.path.exists(dir_name): 253 | os.makedirs(dir_name) 254 | 255 | 256 | def write_list_of_floats_to_file(list_of_floats , file_path): 257 | """Writes a given list of floats to a binary file. 258 | 259 | Args: 260 | list_of_floats: List of floats we want to write to a file. 261 | file_path: Path to a file where list of floats will be stored. 262 | 263 | """ 264 | 265 | s = struct.pack('d' * BOTTLENECK_TENSOR_SIZE, *list_of_floats) 266 | with open(file_path, 'wb') as f: 267 | f.write(s) 268 | 269 | 270 | def read_list_of_floats_from_file(file_path): 271 | """Reads list of floats from a given file. 272 | 273 | Args: 274 | file_path: Path to a file where list of floats was stored. 275 | Returns: 276 | Array of bottleneck values (list of floats). 277 | 278 | """ 279 | 280 | with open(file_path, 'rb') as f: 281 | s = struct.unpack('d' * BOTTLENECK_TENSOR_SIZE, f.read()) 282 | return list(s) 283 | 284 | 285 | bottleneck_path_2_bottleneck_values = {} 286 | 287 | def create_bottleneck_file(bottleneck_path, image_lists, label_name, index, 288 | image_dir, category, sess, jpeg_data_tensor, bottleneck_tensor): 289 | print('Creating bottleneck at ' + bottleneck_path) 290 | image_path = get_image_path(image_lists, label_name, index, image_dir, category) 291 | if not gfile.Exists(image_path): 292 | tf.logging.fatal('File does not exist %s', image_path) 293 | image_data = gfile.FastGFile(image_path, 'rb').read() 294 | bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor) 295 | bottleneck_string = ','.join(str(x) for x in bottleneck_values) 296 | with open(bottleneck_path, 'w') as bottleneck_file: 297 | bottleneck_file.write(bottleneck_string) 298 | 299 | def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir, 300 | category, bottleneck_dir, jpeg_data_tensor, 301 | bottleneck_tensor): 302 | """Retrieves or calculates bottleneck values for an image. 303 | 304 | If a cached version of the bottleneck data exists on-disk, return that, 305 | otherwise calculate the data and save it to disk for future use. 306 | 307 | Args: 308 | sess: The current active TensorFlow Session. 309 | image_lists: Dictionary of training images for each label. 310 | label_name: Label string we want to get an image for. 311 | index: Integer offset of the image we want. This will be modulo-ed by the 312 | available number of images for the label, so it can be arbitrarily large. 313 | image_dir: Root folder string of the subfolders containing the training 314 | images. 315 | category: Name string of which set to pull images from - training, testing, 316 | or validation. 317 | bottleneck_dir: Folder string holding cached files of bottleneck values. 318 | jpeg_data_tensor: The tensor to feed loaded jpeg data into. 319 | bottleneck_tensor: The output tensor for the bottleneck values. 320 | 321 | Returns: 322 | Numpy array of values produced by the bottleneck layer for the image. 323 | """ 324 | label_lists = image_lists[label_name] 325 | sub_dir = label_lists['dir'] 326 | sub_dir_path = os.path.join(bottleneck_dir, sub_dir) 327 | ensure_dir_exists(sub_dir_path) 328 | bottleneck_path = get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category) 329 | if not os.path.exists(bottleneck_path): 330 | create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, bottleneck_tensor) 331 | with open(bottleneck_path, 'r') as bottleneck_file: 332 | bottleneck_string = bottleneck_file.read() 333 | did_hit_error = False 334 | try: 335 | bottleneck_values = [float(x) for x in bottleneck_string.split(',')] 336 | except: 337 | print("Invalid float found, recreating bottleneck") 338 | did_hit_error = True 339 | if did_hit_error: 340 | create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, bottleneck_tensor) 341 | with open(bottleneck_path, 'r') as bottleneck_file: 342 | bottleneck_string = bottleneck_file.read() 343 | # Allow exceptions to propagate here, since they shouldn't happen after a fresh creation 344 | bottleneck_values = [float(x) for x in bottleneck_string.split(',')] 345 | return bottleneck_values 346 | 347 | def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir, 348 | jpeg_data_tensor, bottleneck_tensor): 349 | """Ensures all the training, testing, and validation bottlenecks are cached. 350 | 351 | Because we're likely to read the same image multiple times (if there are no 352 | distortions applied during training) it can speed things up a lot if we 353 | calculate the bottleneck layer values once for each image during 354 | preprocessing, and then just read those cached values repeatedly during 355 | training. Here we go through all the images we've found, calculate those 356 | values, and save them off. 357 | 358 | Args: 359 | sess: The current active TensorFlow Session. 360 | image_lists: Dictionary of training images for each label. 361 | image_dir: Root folder string of the subfolders containing the training 362 | images. 363 | bottleneck_dir: Folder string holding cached files of bottleneck values. 364 | jpeg_data_tensor: Input tensor for jpeg data from file. 365 | bottleneck_tensor: The penultimate output layer of the graph. 366 | 367 | Returns: 368 | Nothing. 369 | """ 370 | how_many_bottlenecks = 0 371 | ensure_dir_exists(bottleneck_dir) 372 | for label_name, label_lists in image_lists.items(): 373 | for category in ['training', 'testing', 'validation']: 374 | category_list = label_lists[category] 375 | for index, unused_base_name in enumerate(category_list): 376 | get_or_create_bottleneck(sess, image_lists, label_name, index, 377 | image_dir, category, bottleneck_dir, 378 | jpeg_data_tensor, bottleneck_tensor) 379 | 380 | how_many_bottlenecks += 1 381 | if how_many_bottlenecks % 100 == 0: 382 | print(str(how_many_bottlenecks) + ' bottleneck files created.') 383 | 384 | 385 | def get_random_cached_bottlenecks(sess, image_lists, how_many, category, 386 | bottleneck_dir, image_dir, jpeg_data_tensor, 387 | bottleneck_tensor): 388 | """Retrieves bottleneck values for cached images. 389 | 390 | If no distortions are being applied, this function can retrieve the cached 391 | bottleneck values directly from disk for images. It picks a random set of 392 | images from the specified category. 393 | 394 | Args: 395 | sess: Current TensorFlow Session. 396 | image_lists: Dictionary of training images for each label. 397 | how_many: If positive, a random sample of this size will be chosen. 398 | If negative, all bottlenecks will be retrieved. 399 | category: Name string of which set to pull from - training, testing, or 400 | validation. 401 | bottleneck_dir: Folder string holding cached files of bottleneck values. 402 | image_dir: Root folder string of the subfolders containing the training 403 | images. 404 | jpeg_data_tensor: The layer to feed jpeg image data into. 405 | bottleneck_tensor: The bottleneck output layer of the CNN graph. 406 | 407 | Returns: 408 | List of bottleneck arrays, their corresponding ground truths, and the 409 | relevant filenames. 410 | """ 411 | class_count = len(image_lists.keys()) 412 | bottlenecks = [] 413 | ground_truths = [] 414 | filenames = [] 415 | if how_many >= 0: 416 | # Retrieve a random sample of bottlenecks. 417 | for unused_i in range(how_many): 418 | label_index = random.randrange(class_count) 419 | label_name = list(image_lists.keys())[label_index] 420 | image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) 421 | image_name = get_image_path(image_lists, label_name, image_index, 422 | image_dir, category) 423 | bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, 424 | image_index, image_dir, category, 425 | bottleneck_dir, jpeg_data_tensor, 426 | bottleneck_tensor) 427 | ground_truth = np.zeros(class_count, dtype=np.float32) 428 | ground_truth[label_index] = 1.0 429 | bottlenecks.append(bottleneck) 430 | ground_truths.append(ground_truth) 431 | filenames.append(image_name) 432 | else: 433 | # Retrieve all bottlenecks. 434 | for label_index, label_name in enumerate(image_lists.keys()): 435 | for image_index, image_name in enumerate( 436 | image_lists[label_name][category]): 437 | image_name = get_image_path(image_lists, label_name, image_index, 438 | image_dir, category) 439 | bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, 440 | image_index, image_dir, category, 441 | bottleneck_dir, jpeg_data_tensor, 442 | bottleneck_tensor) 443 | ground_truth = np.zeros(class_count, dtype=np.float32) 444 | ground_truth[label_index] = 1.0 445 | bottlenecks.append(bottleneck) 446 | ground_truths.append(ground_truth) 447 | filenames.append(image_name) 448 | return bottlenecks, ground_truths, filenames 449 | 450 | 451 | def get_random_distorted_bottlenecks( 452 | sess, image_lists, how_many, category, image_dir, input_jpeg_tensor, 453 | distorted_image, resized_input_tensor, bottleneck_tensor): 454 | """Retrieves bottleneck values for training images, after distortions. 455 | 456 | If we're training with distortions like crops, scales, or flips, we have to 457 | recalculate the full model for every image, and so we can't use cached 458 | bottleneck values. Instead we find random images for the requested category, 459 | run them through the distortion graph, and then the full graph to get the 460 | bottleneck results for each. 461 | 462 | Args: 463 | sess: Current TensorFlow Session. 464 | image_lists: Dictionary of training images for each label. 465 | how_many: The integer number of bottleneck values to return. 466 | category: Name string of which set of images to fetch - training, testing, 467 | or validation. 468 | image_dir: Root folder string of the subfolders containing the training 469 | images. 470 | input_jpeg_tensor: The input layer we feed the image data to. 471 | distorted_image: The output node of the distortion graph. 472 | resized_input_tensor: The input node of the recognition graph. 473 | bottleneck_tensor: The bottleneck output layer of the CNN graph. 474 | 475 | Returns: 476 | List of bottleneck arrays and their corresponding ground truths. 477 | """ 478 | class_count = len(image_lists.keys()) 479 | bottlenecks = [] 480 | ground_truths = [] 481 | for unused_i in range(how_many): 482 | label_index = random.randrange(class_count) 483 | label_name = list(image_lists.keys())[label_index] 484 | image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) 485 | image_path = get_image_path(image_lists, label_name, image_index, image_dir, 486 | category) 487 | if not gfile.Exists(image_path): 488 | tf.logging.fatal('File does not exist %s', image_path) 489 | jpeg_data = gfile.FastGFile(image_path, 'rb').read() 490 | # Note that we materialize the distorted_image_data as a numpy array before 491 | # sending running inference on the image. This involves 2 memory copies and 492 | # might be optimized in other implementations. 493 | distorted_image_data = sess.run(distorted_image, 494 | {input_jpeg_tensor: jpeg_data}) 495 | bottleneck = run_bottleneck_on_image(sess, distorted_image_data, 496 | resized_input_tensor, 497 | bottleneck_tensor) 498 | ground_truth = np.zeros(class_count, dtype=np.float32) 499 | ground_truth[label_index] = 1.0 500 | bottlenecks.append(bottleneck) 501 | ground_truths.append(ground_truth) 502 | return bottlenecks, ground_truths 503 | 504 | 505 | def should_distort_images(flip_left_right, random_crop, random_scale, 506 | random_brightness): 507 | """Whether any distortions are enabled, from the input flags. 508 | 509 | Args: 510 | flip_left_right: Boolean whether to randomly mirror images horizontally. 511 | random_crop: Integer percentage setting the total margin used around the 512 | crop box. 513 | random_scale: Integer percentage of how much to vary the scale by. 514 | random_brightness: Integer range to randomly multiply the pixel values by. 515 | 516 | Returns: 517 | Boolean value indicating whether any distortions should be applied. 518 | """ 519 | return (flip_left_right or (random_crop != 0) or (random_scale != 0) or 520 | (random_brightness != 0)) 521 | 522 | 523 | def add_input_distortions(flip_left_right, random_crop, random_scale, 524 | random_brightness): 525 | """Creates the operations to apply the specified distortions. 526 | 527 | During training it can help to improve the results if we run the images 528 | through simple distortions like crops, scales, and flips. These reflect the 529 | kind of variations we expect in the real world, and so can help train the 530 | model to cope with natural data more effectively. Here we take the supplied 531 | parameters and construct a network of operations to apply them to an image. 532 | 533 | Cropping 534 | ~~~~~~~~ 535 | 536 | Cropping is done by placing a bounding box at a random position in the full 537 | image. The cropping parameter controls the size of that box relative to the 538 | input image. If it's zero, then the box is the same size as the input and no 539 | cropping is performed. If the value is 50%, then the crop box will be half the 540 | width and height of the input. In a diagram it looks like this: 541 | 542 | < width > 543 | +---------------------+ 544 | | | 545 | | width - crop% | 546 | | < > | 547 | | +------+ | 548 | | | | | 549 | | | | | 550 | | | | | 551 | | +------+ | 552 | | | 553 | | | 554 | +---------------------+ 555 | 556 | Scaling 557 | ~~~~~~~ 558 | 559 | Scaling is a lot like cropping, except that the bounding box is always 560 | centered and its size varies randomly within the given range. For example if 561 | the scale percentage is zero, then the bounding box is the same size as the 562 | input and no scaling is applied. If it's 50%, then the bounding box will be in 563 | a random range between half the width and height and full size. 564 | 565 | Args: 566 | flip_left_right: Boolean whether to randomly mirror images horizontally. 567 | random_crop: Integer percentage setting the total margin used around the 568 | crop box. 569 | random_scale: Integer percentage of how much to vary the scale by. 570 | random_brightness: Integer range to randomly multiply the pixel values by. 571 | graph. 572 | 573 | Returns: 574 | The jpeg input layer and the distorted result tensor. 575 | """ 576 | 577 | jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput') 578 | decoded_image = tf.image.decode_jpeg(jpeg_data, channels=MODEL_INPUT_DEPTH) 579 | decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32) 580 | decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0) 581 | margin_scale = 1.0 + (random_crop / 100.0) 582 | resize_scale = 1.0 + (random_scale / 100.0) 583 | margin_scale_value = tf.constant(margin_scale) 584 | resize_scale_value = tf.random_uniform(tensor_shape.scalar(), 585 | minval=1.0, 586 | maxval=resize_scale) 587 | scale_value = tf.multiply(margin_scale_value, resize_scale_value) 588 | precrop_width = tf.multiply(scale_value, MODEL_INPUT_WIDTH) 589 | precrop_height = tf.multiply(scale_value, MODEL_INPUT_HEIGHT) 590 | precrop_shape = tf.stack([precrop_height, precrop_width]) 591 | precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32) 592 | precropped_image = tf.image.resize_bilinear(decoded_image_4d, 593 | precrop_shape_as_int) 594 | precropped_image_3d = tf.squeeze(precropped_image, squeeze_dims=[0]) 595 | cropped_image = tf.random_crop(precropped_image_3d, 596 | [MODEL_INPUT_HEIGHT, MODEL_INPUT_WIDTH, 597 | MODEL_INPUT_DEPTH]) 598 | if flip_left_right: 599 | flipped_image = tf.image.random_flip_left_right(cropped_image) 600 | else: 601 | flipped_image = cropped_image 602 | brightness_min = 1.0 - (random_brightness / 100.0) 603 | brightness_max = 1.0 + (random_brightness / 100.0) 604 | brightness_value = tf.random_uniform(tensor_shape.scalar(), 605 | minval=brightness_min, 606 | maxval=brightness_max) 607 | brightened_image = tf.multiply(flipped_image, brightness_value) 608 | distort_result = tf.expand_dims(brightened_image, 0, name='DistortResult') 609 | return jpeg_data, distort_result 610 | 611 | 612 | def variable_summaries(var): 613 | """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" 614 | with tf.name_scope('summaries'): 615 | mean = tf.reduce_mean(var) 616 | tf.summary.scalar('mean', mean) 617 | with tf.name_scope('stddev'): 618 | stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) 619 | tf.summary.scalar('stddev', stddev) 620 | tf.summary.scalar('max', tf.reduce_max(var)) 621 | tf.summary.scalar('min', tf.reduce_min(var)) 622 | tf.summary.histogram('histogram', var) 623 | 624 | 625 | def add_final_training_ops(class_count, final_tensor_name, bottleneck_tensor): 626 | """Adds a new softmax and fully-connected layer for training. 627 | 628 | We need to retrain the top layer to identify our new classes, so this function 629 | adds the right operations to the graph, along with some variables to hold the 630 | weights, and then sets up all the gradients for the backward pass. 631 | 632 | The set up for the softmax and fully-connected layers is based on: 633 | https://tensorflow.org/versions/master/tutorials/mnist/beginners/index.html 634 | 635 | Args: 636 | class_count: Integer of how many categories of things we're trying to 637 | recognize. 638 | final_tensor_name: Name string for the new final node that produces results. 639 | bottleneck_tensor: The output of the main CNN graph. 640 | 641 | Returns: 642 | The tensors for the training and cross entropy results, and tensors for the 643 | bottleneck input and ground truth input. 644 | """ 645 | with tf.name_scope('input'): 646 | bottleneck_input = tf.placeholder_with_default( 647 | bottleneck_tensor, shape=[None, BOTTLENECK_TENSOR_SIZE], 648 | name='BottleneckInputPlaceholder') 649 | 650 | ground_truth_input = tf.placeholder(tf.float32, 651 | [None, class_count], 652 | name='GroundTruthInput') 653 | 654 | # Organizing the following ops as `final_training_ops` so they're easier 655 | # to see in TensorBoard 656 | layer_name = 'final_training_ops' 657 | with tf.name_scope(layer_name): 658 | with tf.name_scope('weights'): 659 | layer_weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, class_count], stddev=0.001), name='final_weights') 660 | variable_summaries(layer_weights) 661 | with tf.name_scope('biases'): 662 | layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases') 663 | variable_summaries(layer_biases) 664 | with tf.name_scope('Wx_plus_b'): 665 | logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases 666 | tf.summary.histogram('pre_activations', logits) 667 | 668 | final_tensor = tf.nn.softmax(logits, name=final_tensor_name) 669 | tf.summary.histogram('activations', final_tensor) 670 | 671 | with tf.name_scope('cross_entropy'): 672 | cross_entropy = tf.nn.softmax_cross_entropy_with_logits( 673 | labels=ground_truth_input, logits=logits) 674 | with tf.name_scope('total'): 675 | cross_entropy_mean = tf.reduce_mean(cross_entropy) 676 | tf.summary.scalar('cross_entropy', cross_entropy_mean) 677 | 678 | with tf.name_scope('train'): 679 | train_step = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize( 680 | cross_entropy_mean) 681 | 682 | return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input, 683 | final_tensor) 684 | 685 | 686 | def add_evaluation_step(result_tensor, ground_truth_tensor): 687 | """Inserts the operations we need to evaluate the accuracy of our results. 688 | 689 | Args: 690 | result_tensor: The new final node that produces results. 691 | ground_truth_tensor: The node we feed ground truth data 692 | into. 693 | 694 | Returns: 695 | Tuple of (evaluation step, prediction). 696 | """ 697 | with tf.name_scope('accuracy'): 698 | with tf.name_scope('correct_prediction'): 699 | prediction = tf.argmax(result_tensor, 1) 700 | correct_prediction = tf.equal( 701 | prediction, tf.argmax(ground_truth_tensor, 1)) 702 | with tf.name_scope('accuracy'): 703 | evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 704 | tf.summary.scalar('accuracy', evaluation_step) 705 | return evaluation_step, prediction 706 | 707 | 708 | def main(_): 709 | # Setup the directory we'll write summaries to for TensorBoard 710 | if tf.gfile.Exists(FLAGS.summaries_dir): 711 | tf.gfile.DeleteRecursively(FLAGS.summaries_dir) 712 | tf.gfile.MakeDirs(FLAGS.summaries_dir) 713 | 714 | # Set up the pre-trained graph. 715 | maybe_download_and_extract() 716 | graph, bottleneck_tensor, jpeg_data_tensor, resized_image_tensor = ( 717 | create_inception_graph()) 718 | 719 | # Look at the folder structure, and create lists of all the images. 720 | image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage, 721 | FLAGS.validation_percentage) 722 | class_count = len(image_lists.keys()) 723 | if class_count == 0: 724 | print('No valid folders of images found at ' + FLAGS.image_dir) 725 | return -1 726 | if class_count == 1: 727 | print('Only one valid folder of images found at ' + FLAGS.image_dir + 728 | ' - multiple classes are needed for classification.') 729 | return -1 730 | 731 | # See if the command-line flags mean we're applying any distortions. 732 | do_distort_images = should_distort_images( 733 | FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale, 734 | FLAGS.random_brightness) 735 | sess = tf.Session() 736 | 737 | if do_distort_images: 738 | # We will be applying distortions, so setup the operations we'll need. 739 | distorted_jpeg_data_tensor, distorted_image_tensor = add_input_distortions( 740 | FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale, 741 | FLAGS.random_brightness) 742 | else: 743 | # We'll make sure we've calculated the 'bottleneck' image summaries and 744 | # cached them on disk. 745 | cache_bottlenecks(sess, image_lists, FLAGS.image_dir, FLAGS.bottleneck_dir, 746 | jpeg_data_tensor, bottleneck_tensor) 747 | 748 | # Add the new layer that we'll be training. 749 | (train_step, cross_entropy, bottleneck_input, ground_truth_input, 750 | final_tensor) = add_final_training_ops(len(image_lists.keys()), 751 | FLAGS.final_tensor_name, 752 | bottleneck_tensor) 753 | 754 | # Create the operations we need to evaluate the accuracy of our new layer. 755 | evaluation_step, prediction = add_evaluation_step( 756 | final_tensor, ground_truth_input) 757 | 758 | # Merge all the summaries and write them out to /tmp/retrain_logs (by default) 759 | merged = tf.summary.merge_all() 760 | train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train', 761 | sess.graph) 762 | validation_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/validation') 763 | 764 | # Set up all our weights to their initial default values. 765 | init = tf.global_variables_initializer() 766 | sess.run(init) 767 | 768 | # Run the training for as many cycles as requested on the command line. 769 | for i in range(FLAGS.how_many_training_steps): 770 | # Get a batch of input bottleneck values, either calculated fresh every time 771 | # with distortions applied, or from the cache stored on disk. 772 | if do_distort_images: 773 | train_bottlenecks, train_ground_truth = get_random_distorted_bottlenecks( 774 | sess, image_lists, FLAGS.train_batch_size, 'training', 775 | FLAGS.image_dir, distorted_jpeg_data_tensor, 776 | distorted_image_tensor, resized_image_tensor, bottleneck_tensor) 777 | else: 778 | train_bottlenecks, train_ground_truth, _ = get_random_cached_bottlenecks( 779 | sess, image_lists, FLAGS.train_batch_size, 'training', 780 | FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor, 781 | bottleneck_tensor) 782 | # Feed the bottlenecks and ground truth into the graph, and run a training 783 | # step. Capture training summaries for TensorBoard with the `merged` op. 784 | train_summary, _ = sess.run([merged, train_step], 785 | feed_dict={bottleneck_input: train_bottlenecks, 786 | ground_truth_input: train_ground_truth}) 787 | train_writer.add_summary(train_summary, i) 788 | 789 | # Every so often, print out how well the graph is training. 790 | is_last_step = (i + 1 == FLAGS.how_many_training_steps) 791 | if (i % FLAGS.eval_step_interval) == 0 or is_last_step: 792 | train_accuracy, cross_entropy_value = sess.run( 793 | [evaluation_step, cross_entropy], 794 | feed_dict={bottleneck_input: train_bottlenecks, 795 | ground_truth_input: train_ground_truth}) 796 | print('%s: Step %d: Train accuracy = %.1f%%' % (datetime.now(), i, 797 | train_accuracy * 100)) 798 | print('%s: Step %d: Cross entropy = %f' % (datetime.now(), i, 799 | cross_entropy_value)) 800 | validation_bottlenecks, validation_ground_truth, _ = ( 801 | get_random_cached_bottlenecks( 802 | sess, image_lists, FLAGS.validation_batch_size, 'validation', 803 | FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor, 804 | bottleneck_tensor)) 805 | # Run a validation step and capture training summaries for TensorBoard 806 | # with the `merged` op. 807 | validation_summary, validation_accuracy = sess.run( 808 | [merged, evaluation_step], 809 | feed_dict={bottleneck_input: validation_bottlenecks, 810 | ground_truth_input: validation_ground_truth}) 811 | validation_writer.add_summary(validation_summary, i) 812 | print('%s: Step %d: Validation accuracy = %.1f%% (N=%d)' % 813 | (datetime.now(), i, validation_accuracy * 100, 814 | len(validation_bottlenecks))) 815 | 816 | # We've completed all our training, so run a final test evaluation on 817 | # some new images we haven't used before. 818 | test_bottlenecks, test_ground_truth, test_filenames = ( 819 | get_random_cached_bottlenecks(sess, image_lists, FLAGS.test_batch_size, 820 | 'testing', FLAGS.bottleneck_dir, 821 | FLAGS.image_dir, jpeg_data_tensor, 822 | bottleneck_tensor)) 823 | test_accuracy, predictions = sess.run( 824 | [evaluation_step, prediction], 825 | feed_dict={bottleneck_input: test_bottlenecks, 826 | ground_truth_input: test_ground_truth}) 827 | print('Final test accuracy = %.1f%% (N=%d)' % ( 828 | test_accuracy * 100, len(test_bottlenecks))) 829 | 830 | if FLAGS.print_misclassified_test_images: 831 | print('=== MISCLASSIFIED TEST IMAGES ===') 832 | for i, test_filename in enumerate(test_filenames): 833 | if predictions[i] != test_ground_truth[i].argmax(): 834 | print('%70s %s' % (test_filename, 835 | list(image_lists.keys())[predictions[i]])) 836 | 837 | # Write out the trained graph and labels with the weights stored as constants. 838 | output_graph_def = graph_util.convert_variables_to_constants( 839 | sess, graph.as_graph_def(), [FLAGS.final_tensor_name]) 840 | with gfile.FastGFile(FLAGS.output_graph, 'wb') as f: 841 | f.write(output_graph_def.SerializeToString()) 842 | with gfile.FastGFile(FLAGS.output_labels, 'w') as f: 843 | f.write('\n'.join(image_lists.keys()) + '\n') 844 | 845 | 846 | if __name__ == '__main__': 847 | parser = argparse.ArgumentParser() 848 | parser.add_argument( 849 | '--image_dir', 850 | type=str, 851 | default='', 852 | help='Path to folders of labeled images.' 853 | ) 854 | parser.add_argument( 855 | '--output_graph', 856 | type=str, 857 | default='/tmp/output_graph.pb', 858 | help='Where to save the trained graph.' 859 | ) 860 | parser.add_argument( 861 | '--output_labels', 862 | type=str, 863 | default='/tmp/output_labels.txt', 864 | help='Where to save the trained graph\'s labels.' 865 | ) 866 | parser.add_argument( 867 | '--summaries_dir', 868 | type=str, 869 | default='/tmp/retrain_logs', 870 | help='Where to save summary logs for TensorBoard.' 871 | ) 872 | parser.add_argument( 873 | '--how_many_training_steps', 874 | type=int, 875 | default=4000, 876 | help='How many training steps to run before ending.' 877 | ) 878 | parser.add_argument( 879 | '--learning_rate', 880 | type=float, 881 | default=0.01, 882 | help='How large a learning rate to use when training.' 883 | ) 884 | parser.add_argument( 885 | '--testing_percentage', 886 | type=int, 887 | default=10, 888 | help='What percentage of images to use as a test set.' 889 | ) 890 | parser.add_argument( 891 | '--validation_percentage', 892 | type=int, 893 | default=10, 894 | help='What percentage of images to use as a validation set.' 895 | ) 896 | parser.add_argument( 897 | '--eval_step_interval', 898 | type=int, 899 | default=10, 900 | help='How often to evaluate the training results.' 901 | ) 902 | parser.add_argument( 903 | '--train_batch_size', 904 | type=int, 905 | default=100, 906 | help='How many images to train on at a time.' 907 | ) 908 | parser.add_argument( 909 | '--test_batch_size', 910 | type=int, 911 | default=-1, 912 | help="""\ 913 | How many images to test on. This test set is only used once, to evaluate 914 | the final accuracy of the model after training completes. 915 | A value of -1 causes the entire test set to be used, which leads to more 916 | stable results across runs.\ 917 | """ 918 | ) 919 | parser.add_argument( 920 | '--validation_batch_size', 921 | type=int, 922 | default=100, 923 | help="""\ 924 | How many images to use in an evaluation batch. This validation set is 925 | used much more often than the test set, and is an early indicator of how 926 | accurate the model is during training. 927 | A value of -1 causes the entire validation set to be used, which leads to 928 | more stable results across training iterations, but may be slower on large 929 | training sets.\ 930 | """ 931 | ) 932 | parser.add_argument( 933 | '--print_misclassified_test_images', 934 | default=False, 935 | help="""\ 936 | Whether to print out a list of all misclassified test images.\ 937 | """, 938 | action='store_true' 939 | ) 940 | parser.add_argument( 941 | '--model_dir', 942 | type=str, 943 | default='/tmp/imagenet', 944 | help="""\ 945 | Path to classify_image_graph_def.pb, 946 | imagenet_synset_to_human_label_map.txt, and 947 | imagenet_2012_challenge_label_map_proto.pbtxt.\ 948 | """ 949 | ) 950 | parser.add_argument( 951 | '--bottleneck_dir', 952 | type=str, 953 | default='/tmp/bottleneck', 954 | help='Path to cache bottleneck layer values as files.' 955 | ) 956 | parser.add_argument( 957 | '--final_tensor_name', 958 | type=str, 959 | default='final_result', 960 | help="""\ 961 | The name of the output classification layer in the retrained graph.\ 962 | """ 963 | ) 964 | parser.add_argument( 965 | '--flip_left_right', 966 | default=False, 967 | help="""\ 968 | Whether to randomly flip half of the training images horizontally.\ 969 | """, 970 | action='store_true' 971 | ) 972 | parser.add_argument( 973 | '--random_crop', 974 | type=int, 975 | default=0, 976 | help="""\ 977 | A percentage determining how much of a margin to randomly crop off the 978 | training images.\ 979 | """ 980 | ) 981 | parser.add_argument( 982 | '--random_scale', 983 | type=int, 984 | default=0, 985 | help="""\ 986 | A percentage determining how much to randomly scale up the size of the 987 | training images by.\ 988 | """ 989 | ) 990 | parser.add_argument( 991 | '--random_brightness', 992 | type=int, 993 | default=0, 994 | help="""\ 995 | A percentage determining how much to randomly multiply the training image 996 | input pixels up or down by.\ 997 | """ 998 | ) 999 | FLAGS, unparsed = parser.parse_known_args() 1000 | tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 1001 | -------------------------------------------------------------------------------- /retrained_labels.txt: -------------------------------------------------------------------------------- 1 | benign 2 | normal 3 | malevolent 4 | --------------------------------------------------------------------------------