python_code
stringlengths
0
679k
repo_name
stringlengths
9
41
file_path
stringlengths
6
149
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/dataset_tools/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test for create_coco_tf_record.py.""" import io import json import os import numpy as np import PIL.Image import tensorflow as tf from object_detection.dataset_tools import create_coco_tf_record class CreateCocoTFRecordTest(tf.test.TestCase): def _assertProtoEqual(self, proto_field, expectation): """Helper function to assert if a proto field equals some value. Args: proto_field: The protobuf field to compare. expectation: The expected value of the protobuf field. """ proto_list = [p for p in proto_field] self.assertListEqual(proto_list, expectation) def test_create_tf_example(self): image_file_name = 'tmp_image.jpg' image_data = np.random.rand(256, 256, 3) tmp_dir = self.get_temp_dir() save_path = os.path.join(tmp_dir, image_file_name) image = PIL.Image.fromarray(image_data, 'RGB') image.save(save_path) image = { 'file_name': image_file_name, 'height': 256, 'width': 256, 'id': 11, } annotations_list = [{ 'area': .5, 'iscrowd': False, 'image_id': 11, 'bbox': [64, 64, 128, 128], 'category_id': 2, 'id': 1000, }] image_dir = tmp_dir category_index = { 1: { 'name': 'dog', 'id': 1 }, 2: { 'name': 'cat', 'id': 2 }, 3: { 'name': 'human', 'id': 3 } } (_, example, num_annotations_skipped) = create_coco_tf_record.create_tf_example( image, annotations_list, image_dir, category_index) self.assertEqual(num_annotations_skipped, 0) self._assertProtoEqual( example.features.feature['image/height'].int64_list.value, [256]) self._assertProtoEqual( example.features.feature['image/width'].int64_list.value, [256]) self._assertProtoEqual( example.features.feature['image/filename'].bytes_list.value, [image_file_name]) self._assertProtoEqual( example.features.feature['image/source_id'].bytes_list.value, [str(image['id'])]) self._assertProtoEqual( example.features.feature['image/format'].bytes_list.value, ['jpeg']) self._assertProtoEqual( example.features.feature['image/object/bbox/xmin'].float_list.value, [0.25]) self._assertProtoEqual( example.features.feature['image/object/bbox/ymin'].float_list.value, [0.25]) self._assertProtoEqual( example.features.feature['image/object/bbox/xmax'].float_list.value, [0.75]) self._assertProtoEqual( example.features.feature['image/object/bbox/ymax'].float_list.value, [0.75]) self._assertProtoEqual( example.features.feature['image/object/class/text'].bytes_list.value, ['cat']) def test_create_tf_example_with_instance_masks(self): image_file_name = 'tmp_image.jpg' image_data = np.random.rand(8, 8, 3) tmp_dir = self.get_temp_dir() save_path = os.path.join(tmp_dir, image_file_name) image = PIL.Image.fromarray(image_data, 'RGB') image.save(save_path) image = { 'file_name': image_file_name, 'height': 8, 'width': 8, 'id': 11, } annotations_list = [{ 'area': .5, 'iscrowd': False, 'image_id': 11, 'bbox': [0, 0, 8, 8], 'segmentation': [[4, 0, 0, 0, 0, 4], [8, 4, 4, 8, 8, 8]], 'category_id': 1, 'id': 1000, }] image_dir = tmp_dir category_index = { 1: { 'name': 'dog', 'id': 1 }, } (_, example, num_annotations_skipped) = create_coco_tf_record.create_tf_example( image, annotations_list, image_dir, category_index, include_masks=True) self.assertEqual(num_annotations_skipped, 0) self._assertProtoEqual( example.features.feature['image/height'].int64_list.value, [8]) self._assertProtoEqual( example.features.feature['image/width'].int64_list.value, [8]) self._assertProtoEqual( example.features.feature['image/filename'].bytes_list.value, [image_file_name]) self._assertProtoEqual( example.features.feature['image/source_id'].bytes_list.value, [str(image['id'])]) self._assertProtoEqual( example.features.feature['image/format'].bytes_list.value, ['jpeg']) self._assertProtoEqual( example.features.feature['image/object/bbox/xmin'].float_list.value, [0]) self._assertProtoEqual( example.features.feature['image/object/bbox/ymin'].float_list.value, [0]) self._assertProtoEqual( example.features.feature['image/object/bbox/xmax'].float_list.value, [1]) self._assertProtoEqual( example.features.feature['image/object/bbox/ymax'].float_list.value, [1]) self._assertProtoEqual( example.features.feature['image/object/class/text'].bytes_list.value, ['dog']) encoded_mask_pngs = [ io.BytesIO(encoded_masks) for encoded_masks in example.features.feature[ 'image/object/mask'].bytes_list.value ] pil_masks = [ np.array(PIL.Image.open(encoded_mask_png)) for encoded_mask_png in encoded_mask_pngs ] self.assertTrue(len(pil_masks) == 1) self.assertAllEqual(pil_masks[0], [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1]]) def test_create_sharded_tf_record(self): tmp_dir = self.get_temp_dir() image_paths = ['tmp1_image.jpg', 'tmp2_image.jpg'] for image_path in image_paths: image_data = np.random.rand(256, 256, 3) save_path = os.path.join(tmp_dir, image_path) image = PIL.Image.fromarray(image_data, 'RGB') image.save(save_path) images = [{ 'file_name': image_paths[0], 'height': 256, 'width': 256, 'id': 11, }, { 'file_name': image_paths[1], 'height': 256, 'width': 256, 'id': 12, }] annotations = [{ 'area': .5, 'iscrowd': False, 'image_id': 11, 'bbox': [64, 64, 128, 128], 'category_id': 2, 'id': 1000, }] category_index = [{ 'name': 'dog', 'id': 1 }, { 'name': 'cat', 'id': 2 }, { 'name': 'human', 'id': 3 }] groundtruth_data = {'images': images, 'annotations': annotations, 'categories': category_index} annotation_file = os.path.join(tmp_dir, 'annotation.json') with open(annotation_file, 'w') as annotation_fid: json.dump(groundtruth_data, annotation_fid) output_path = os.path.join(tmp_dir, 'out.record') create_coco_tf_record._create_tf_record_from_coco_annotations( annotation_file, tmp_dir, output_path, False, 2) self.assertTrue(os.path.exists(output_path + '-00000-of-00002')) self.assertTrue(os.path.exists(output_path + '-00001-of-00002')) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/dataset_tools/create_coco_tf_record_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tf_record_creation_util.py.""" import os import contextlib2 import tensorflow as tf from object_detection.dataset_tools import tf_record_creation_util class OpenOutputTfrecordsTests(tf.test.TestCase): def test_sharded_tfrecord_writes(self): with contextlib2.ExitStack() as tf_record_close_stack: output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords( tf_record_close_stack, os.path.join(tf.test.get_temp_dir(), 'test.tfrec'), 10) for idx in range(10): output_tfrecords[idx].write('test_{}'.format(idx)) for idx in range(10): tf_record_path = '{}-{:05d}-of-00010'.format( os.path.join(tf.test.get_temp_dir(), 'test.tfrec'), idx) records = list(tf.python_io.tf_record_iterator(tf_record_path)) self.assertAllEqual(records, ['test_{}'.format(idx)]) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/dataset_tools/tf_record_creation_util_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for oid_tfrecord_creation.py.""" import pandas as pd import tensorflow as tf from object_detection.dataset_tools import oid_tfrecord_creation def create_test_data(): data = { 'ImageID': ['i1', 'i1', 'i1', 'i1', 'i1', 'i2', 'i2'], 'LabelName': ['a', 'a', 'b', 'b', 'c', 'b', 'c'], 'YMin': [0.3, 0.6, 0.8, 0.1, None, 0.0, 0.0], 'XMin': [0.1, 0.3, 0.7, 0.0, None, 0.1, 0.1], 'XMax': [0.2, 0.3, 0.8, 0.5, None, 0.9, 0.9], 'YMax': [0.3, 0.6, 1, 0.8, None, 0.8, 0.8], 'IsOccluded': [0, 1, 1, 0, None, 0, 0], 'IsTruncated': [0, 0, 0, 1, None, 0, 0], 'IsGroupOf': [0, 0, 0, 0, None, 0, 1], 'IsDepiction': [1, 0, 0, 0, None, 0, 0], 'ConfidenceImageLabel': [None, None, None, None, 0, None, None], } df = pd.DataFrame(data=data) label_map = {'a': 0, 'b': 1, 'c': 2} return label_map, df class TfExampleFromAnnotationsDataFrameTests(tf.test.TestCase): def test_simple(self): label_map, df = create_test_data() tf_example = oid_tfrecord_creation.tf_example_from_annotations_data_frame( df[df.ImageID == 'i1'], label_map, 'encoded_image_test') self.assertProtoEquals( """ features { feature { key: "image/encoded" value { bytes_list { value: "encoded_image_test" } } } feature { key: "image/filename" value { bytes_list { value: "i1.jpg" } } } feature { key: "image/object/bbox/ymin" value { float_list { value: [0.3, 0.6, 0.8, 0.1] } } } feature { key: "image/object/bbox/xmin" value { float_list { value: [0.1, 0.3, 0.7, 0.0] } } } feature { key: "image/object/bbox/ymax" value { float_list { value: [0.3, 0.6, 1.0, 0.8] } } } feature { key: "image/object/bbox/xmax" value { float_list { value: [0.2, 0.3, 0.8, 0.5] } } } feature { key: "image/object/class/label" value { int64_list { value: [0, 0, 1, 1] } } } feature { key: "image/object/class/text" value { bytes_list { value: ["a", "a", "b", "b"] } } } feature { key: "image/source_id" value { bytes_list { value: "i1" } } } feature { key: "image/object/depiction" value { int64_list { value: [1, 0, 0, 0] } } } feature { key: "image/object/group_of" value { int64_list { value: [0, 0, 0, 0] } } } feature { key: "image/object/occluded" value { int64_list { value: [0, 1, 1, 0] } } } feature { key: "image/object/truncated" value { int64_list { value: [0, 0, 0, 1] } } } feature { key: "image/class/label" value { int64_list { value: [2] } } } feature { key: "image/class/text" value { bytes_list { value: ["c"] } } } } """, tf_example) def test_no_attributes(self): label_map, df = create_test_data() del df['IsDepiction'] del df['IsGroupOf'] del df['IsOccluded'] del df['IsTruncated'] del df['ConfidenceImageLabel'] tf_example = oid_tfrecord_creation.tf_example_from_annotations_data_frame( df[df.ImageID == 'i2'], label_map, 'encoded_image_test') self.assertProtoEquals(""" features { feature { key: "image/encoded" value { bytes_list { value: "encoded_image_test" } } } feature { key: "image/filename" value { bytes_list { value: "i2.jpg" } } } feature { key: "image/object/bbox/ymin" value { float_list { value: [0.0, 0.0] } } } feature { key: "image/object/bbox/xmin" value { float_list { value: [0.1, 0.1] } } } feature { key: "image/object/bbox/ymax" value { float_list { value: [0.8, 0.8] } } } feature { key: "image/object/bbox/xmax" value { float_list { value: [0.9, 0.9] } } } feature { key: "image/object/class/label" value { int64_list { value: [1, 2] } } } feature { key: "image/object/class/text" value { bytes_list { value: ["b", "c"] } } } feature { key: "image/source_id" value { bytes_list { value: "i2" } } } } """, tf_example) def test_label_filtering(self): label_map, df = create_test_data() label_map = {'a': 0} tf_example = oid_tfrecord_creation.tf_example_from_annotations_data_frame( df[df.ImageID == 'i1'], label_map, 'encoded_image_test') self.assertProtoEquals( """ features { feature { key: "image/encoded" value { bytes_list { value: "encoded_image_test" } } } feature { key: "image/filename" value { bytes_list { value: "i1.jpg" } } } feature { key: "image/object/bbox/ymin" value { float_list { value: [0.3, 0.6] } } } feature { key: "image/object/bbox/xmin" value { float_list { value: [0.1, 0.3] } } } feature { key: "image/object/bbox/ymax" value { float_list { value: [0.3, 0.6] } } } feature { key: "image/object/bbox/xmax" value { float_list { value: [0.2, 0.3] } } } feature { key: "image/object/class/label" value { int64_list { value: [0, 0] } } } feature { key: "image/object/class/text" value { bytes_list { value: ["a", "a"] } } } feature { key: "image/source_id" value { bytes_list { value: "i1" } } } feature { key: "image/object/depiction" value { int64_list { value: [1, 0] } } } feature { key: "image/object/group_of" value { int64_list { value: [0, 0] } } } feature { key: "image/object/occluded" value { int64_list { value: [0, 1] } } } feature { key: "image/object/truncated" value { int64_list { value: [0, 0] } } } feature { key: "image/class/label" value { int64_list { } } } feature { key: "image/class/text" value { bytes_list { } } } } """, tf_example) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/dataset_tools/oid_tfrecord_creation_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Convert the Oxford pet dataset to TFRecord for object_detection. See: O. M. Parkhi, A. Vedaldi, A. Zisserman, C. V. Jawahar Cats and Dogs IEEE Conference on Computer Vision and Pattern Recognition, 2012 http://www.robots.ox.ac.uk/~vgg/data/pets/ Example usage: python object_detection/dataset_tools/create_pet_tf_record.py \ --data_dir=/home/user/pet \ --output_dir=/home/user/pet/output """ import hashlib import io import logging import os import random import re import contextlib2 from lxml import etree import numpy as np import PIL.Image import tensorflow as tf from object_detection.dataset_tools import tf_record_creation_util from object_detection.utils import dataset_util from object_detection.utils import label_map_util flags = tf.app.flags flags.DEFINE_string('data_dir', '', 'Root directory to raw pet dataset.') flags.DEFINE_string('output_dir', '', 'Path to directory to output TFRecords.') flags.DEFINE_string('label_map_path', 'data/pet_label_map.pbtxt', 'Path to label map proto') flags.DEFINE_boolean('faces_only', True, 'If True, generates bounding boxes ' 'for pet faces. Otherwise generates bounding boxes (as ' 'well as segmentations for full pet bodies). Note that ' 'in the latter case, the resulting files are much larger.') flags.DEFINE_string('mask_type', 'png', 'How to represent instance ' 'segmentation masks. Options are "png" or "numerical".') flags.DEFINE_integer('num_shards', 10, 'Number of TFRecord shards') FLAGS = flags.FLAGS def get_class_name_from_filename(file_name): """Gets the class name from a file. Args: file_name: The file name to get the class name from. ie. "american_pit_bull_terrier_105.jpg" Returns: A string of the class name. """ match = re.match(r'([A-Za-z_]+)(_[0-9]+\.jpg)', file_name, re.I) return match.groups()[0] def dict_to_tf_example(data, mask_path, label_map_dict, image_subdirectory, ignore_difficult_instances=False, faces_only=True, mask_type='png'): """Convert XML derived dict to tf.Example proto. Notice that this function normalizes the bounding box coordinates provided by the raw data. Args: data: dict holding PASCAL XML fields for a single image (obtained by running dataset_util.recursive_parse_xml_to_dict) mask_path: String path to PNG encoded mask. label_map_dict: A map from string label names to integers ids. image_subdirectory: String specifying subdirectory within the Pascal dataset directory holding the actual image data. ignore_difficult_instances: Whether to skip difficult instances in the dataset (default: False). faces_only: If True, generates bounding boxes for pet faces. Otherwise generates bounding boxes (as well as segmentations for full pet bodies). mask_type: 'numerical' or 'png'. 'png' is recommended because it leads to smaller file sizes. Returns: example: The converted tf.Example. Raises: ValueError: if the image pointed to by data['filename'] is not a valid JPEG """ img_path = os.path.join(image_subdirectory, data['filename']) with tf.gfile.GFile(img_path, 'rb') as fid: encoded_jpg = fid.read() encoded_jpg_io = io.BytesIO(encoded_jpg) image = PIL.Image.open(encoded_jpg_io) if image.format != 'JPEG': raise ValueError('Image format not JPEG') key = hashlib.sha256(encoded_jpg).hexdigest() with tf.gfile.GFile(mask_path, 'rb') as fid: encoded_mask_png = fid.read() encoded_png_io = io.BytesIO(encoded_mask_png) mask = PIL.Image.open(encoded_png_io) if mask.format != 'PNG': raise ValueError('Mask format not PNG') mask_np = np.asarray(mask) nonbackground_indices_x = np.any(mask_np != 2, axis=0) nonbackground_indices_y = np.any(mask_np != 2, axis=1) nonzero_x_indices = np.where(nonbackground_indices_x) nonzero_y_indices = np.where(nonbackground_indices_y) width = int(data['size']['width']) height = int(data['size']['height']) xmins = [] ymins = [] xmaxs = [] ymaxs = [] classes = [] classes_text = [] truncated = [] poses = [] difficult_obj = [] masks = [] if 'object' in data: for obj in data['object']: difficult = bool(int(obj['difficult'])) if ignore_difficult_instances and difficult: continue difficult_obj.append(int(difficult)) if faces_only: xmin = float(obj['bndbox']['xmin']) xmax = float(obj['bndbox']['xmax']) ymin = float(obj['bndbox']['ymin']) ymax = float(obj['bndbox']['ymax']) else: xmin = float(np.min(nonzero_x_indices)) xmax = float(np.max(nonzero_x_indices)) ymin = float(np.min(nonzero_y_indices)) ymax = float(np.max(nonzero_y_indices)) xmins.append(xmin / width) ymins.append(ymin / height) xmaxs.append(xmax / width) ymaxs.append(ymax / height) class_name = get_class_name_from_filename(data['filename']) classes_text.append(class_name.encode('utf8')) classes.append(label_map_dict[class_name]) truncated.append(int(obj['truncated'])) poses.append(obj['pose'].encode('utf8')) if not faces_only: mask_remapped = (mask_np != 2).astype(np.uint8) masks.append(mask_remapped) feature_dict = { 'image/height': dataset_util.int64_feature(height), 'image/width': dataset_util.int64_feature(width), 'image/filename': dataset_util.bytes_feature( data['filename'].encode('utf8')), 'image/source_id': dataset_util.bytes_feature( data['filename'].encode('utf8')), 'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')), 'image/encoded': dataset_util.bytes_feature(encoded_jpg), 'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs), 'image/object/class/text': dataset_util.bytes_list_feature(classes_text), 'image/object/class/label': dataset_util.int64_list_feature(classes), 'image/object/difficult': dataset_util.int64_list_feature(difficult_obj), 'image/object/truncated': dataset_util.int64_list_feature(truncated), 'image/object/view': dataset_util.bytes_list_feature(poses), } if not faces_only: if mask_type == 'numerical': mask_stack = np.stack(masks).astype(np.float32) masks_flattened = np.reshape(mask_stack, [-1]) feature_dict['image/object/mask'] = ( dataset_util.float_list_feature(masks_flattened.tolist())) elif mask_type == 'png': encoded_mask_png_list = [] for mask in masks: img = PIL.Image.fromarray(mask) output = io.BytesIO() img.save(output, format='PNG') encoded_mask_png_list.append(output.getvalue()) feature_dict['image/object/mask'] = ( dataset_util.bytes_list_feature(encoded_mask_png_list)) example = tf.train.Example(features=tf.train.Features(feature=feature_dict)) return example def create_tf_record(output_filename, num_shards, label_map_dict, annotations_dir, image_dir, examples, faces_only=True, mask_type='png'): """Creates a TFRecord file from examples. Args: output_filename: Path to where output file is saved. num_shards: Number of shards for output file. label_map_dict: The label map dictionary. annotations_dir: Directory where annotation files are stored. image_dir: Directory where image files are stored. examples: Examples to parse and save to tf record. faces_only: If True, generates bounding boxes for pet faces. Otherwise generates bounding boxes (as well as segmentations for full pet bodies). mask_type: 'numerical' or 'png'. 'png' is recommended because it leads to smaller file sizes. """ with contextlib2.ExitStack() as tf_record_close_stack: output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords( tf_record_close_stack, output_filename, num_shards) for idx, example in enumerate(examples): if idx % 100 == 0: logging.info('On image %d of %d', idx, len(examples)) xml_path = os.path.join(annotations_dir, 'xmls', example + '.xml') mask_path = os.path.join(annotations_dir, 'trimaps', example + '.png') if not os.path.exists(xml_path): logging.warning('Could not find %s, ignoring example.', xml_path) continue with tf.gfile.GFile(xml_path, 'r') as fid: xml_str = fid.read() xml = etree.fromstring(xml_str) data = dataset_util.recursive_parse_xml_to_dict(xml)['annotation'] try: tf_example = dict_to_tf_example( data, mask_path, label_map_dict, image_dir, faces_only=faces_only, mask_type=mask_type) if tf_example: shard_idx = idx % num_shards output_tfrecords[shard_idx].write(tf_example.SerializeToString()) except ValueError: logging.warning('Invalid example: %s, ignoring.', xml_path) # TODO(derekjchow): Add test for pet/PASCAL main files. def main(_): data_dir = FLAGS.data_dir label_map_dict = label_map_util.get_label_map_dict(FLAGS.label_map_path) logging.info('Reading from Pet dataset.') image_dir = os.path.join(data_dir, 'images') annotations_dir = os.path.join(data_dir, 'annotations') examples_path = os.path.join(annotations_dir, 'trainval.txt') examples_list = dataset_util.read_examples_list(examples_path) # Test images are not included in the downloaded data set, so we shall perform # our own split. random.seed(42) random.shuffle(examples_list) num_examples = len(examples_list) num_train = int(0.7 * num_examples) train_examples = examples_list[:num_train] val_examples = examples_list[num_train:] logging.info('%d training and %d validation examples.', len(train_examples), len(val_examples)) train_output_path = os.path.join(FLAGS.output_dir, 'pet_faces_train.record') val_output_path = os.path.join(FLAGS.output_dir, 'pet_faces_val.record') if not FLAGS.faces_only: train_output_path = os.path.join(FLAGS.output_dir, 'pets_fullbody_with_masks_train.record') val_output_path = os.path.join(FLAGS.output_dir, 'pets_fullbody_with_masks_val.record') create_tf_record( train_output_path, FLAGS.num_shards, label_map_dict, annotations_dir, image_dir, train_examples, faces_only=FLAGS.faces_only, mask_type=FLAGS.mask_type) create_tf_record( val_output_path, FLAGS.num_shards, label_map_dict, annotations_dir, image_dir, val_examples, faces_only=FLAGS.faces_only, mask_type=FLAGS.mask_type) if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/dataset_tools/create_pet_tf_record.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Convert raw COCO dataset to TFRecord for object_detection. Please note that this tool creates sharded output files. Example usage: python create_coco_tf_record.py --logtostderr \ --train_image_dir="${TRAIN_IMAGE_DIR}" \ --val_image_dir="${VAL_IMAGE_DIR}" \ --test_image_dir="${TEST_IMAGE_DIR}" \ --train_annotations_file="${TRAIN_ANNOTATIONS_FILE}" \ --val_annotations_file="${VAL_ANNOTATIONS_FILE}" \ --testdev_annotations_file="${TESTDEV_ANNOTATIONS_FILE}" \ --output_dir="${OUTPUT_DIR}" """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import hashlib import io import json import os import contextlib2 import numpy as np import PIL.Image from pycocotools import mask import tensorflow as tf from object_detection.dataset_tools import tf_record_creation_util from object_detection.utils import dataset_util from object_detection.utils import label_map_util flags = tf.app.flags tf.flags.DEFINE_boolean('include_masks', False, 'Whether to include instance segmentations masks ' '(PNG encoded) in the result. default: False.') tf.flags.DEFINE_string('train_image_dir', '', 'Training image directory.') tf.flags.DEFINE_string('val_image_dir', '', 'Validation image directory.') tf.flags.DEFINE_string('test_image_dir', '', 'Test image directory.') tf.flags.DEFINE_string('train_annotations_file', '', 'Training annotations JSON file.') tf.flags.DEFINE_string('val_annotations_file', '', 'Validation annotations JSON file.') tf.flags.DEFINE_string('testdev_annotations_file', '', 'Test-dev annotations JSON file.') tf.flags.DEFINE_string('output_dir', '/tmp/', 'Output data directory.') FLAGS = flags.FLAGS tf.logging.set_verbosity(tf.logging.INFO) def create_tf_example(image, annotations_list, image_dir, category_index, include_masks=False): """Converts image and annotations to a tf.Example proto. Args: image: dict with keys: [u'license', u'file_name', u'coco_url', u'height', u'width', u'date_captured', u'flickr_url', u'id'] annotations_list: list of dicts with keys: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id'] Notice that bounding box coordinates in the official COCO dataset are given as [x, y, width, height] tuples using absolute coordinates where x, y represent the top-left (0-indexed) corner. This function converts to the format expected by the Tensorflow Object Detection API (which is which is [ymin, xmin, ymax, xmax] with coordinates normalized relative to image size). image_dir: directory containing the image files. category_index: a dict containing COCO category information keyed by the 'id' field of each category. See the label_map_util.create_category_index function. include_masks: Whether to include instance segmentations masks (PNG encoded) in the result. default: False. Returns: example: The converted tf.Example num_annotations_skipped: Number of (invalid) annotations that were ignored. Raises: ValueError: if the image pointed to by data['filename'] is not a valid JPEG """ image_height = image['height'] image_width = image['width'] filename = image['file_name'] image_id = image['id'] full_path = os.path.join(image_dir, filename) with tf.gfile.GFile(full_path, 'rb') as fid: encoded_jpg = fid.read() encoded_jpg_io = io.BytesIO(encoded_jpg) image = PIL.Image.open(encoded_jpg_io) key = hashlib.sha256(encoded_jpg).hexdigest() xmin = [] xmax = [] ymin = [] ymax = [] is_crowd = [] category_names = [] category_ids = [] area = [] encoded_mask_png = [] num_annotations_skipped = 0 for object_annotations in annotations_list: (x, y, width, height) = tuple(object_annotations['bbox']) if width <= 0 or height <= 0: num_annotations_skipped += 1 continue if x + width > image_width or y + height > image_height: num_annotations_skipped += 1 continue xmin.append(float(x) / image_width) xmax.append(float(x + width) / image_width) ymin.append(float(y) / image_height) ymax.append(float(y + height) / image_height) is_crowd.append(object_annotations['iscrowd']) category_id = int(object_annotations['category_id']) category_ids.append(category_id) category_names.append(category_index[category_id]['name'].encode('utf8')) area.append(object_annotations['area']) if include_masks: run_len_encoding = mask.frPyObjects(object_annotations['segmentation'], image_height, image_width) binary_mask = mask.decode(run_len_encoding) if not object_annotations['iscrowd']: binary_mask = np.amax(binary_mask, axis=2) pil_image = PIL.Image.fromarray(binary_mask) output_io = io.BytesIO() pil_image.save(output_io, format='PNG') encoded_mask_png.append(output_io.getvalue()) feature_dict = { 'image/height': dataset_util.int64_feature(image_height), 'image/width': dataset_util.int64_feature(image_width), 'image/filename': dataset_util.bytes_feature(filename.encode('utf8')), 'image/source_id': dataset_util.bytes_feature(str(image_id).encode('utf8')), 'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')), 'image/encoded': dataset_util.bytes_feature(encoded_jpg), 'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmin), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmax), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymin), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymax), 'image/object/class/text': dataset_util.bytes_list_feature(category_names), 'image/object/is_crowd': dataset_util.int64_list_feature(is_crowd), 'image/object/area': dataset_util.float_list_feature(area), } if include_masks: feature_dict['image/object/mask'] = ( dataset_util.bytes_list_feature(encoded_mask_png)) example = tf.train.Example(features=tf.train.Features(feature=feature_dict)) return key, example, num_annotations_skipped def _create_tf_record_from_coco_annotations( annotations_file, image_dir, output_path, include_masks, num_shards): """Loads COCO annotation json files and converts to tf.Record format. Args: annotations_file: JSON file containing bounding box annotations. image_dir: Directory containing the image files. output_path: Path to output tf.Record file. include_masks: Whether to include instance segmentations masks (PNG encoded) in the result. default: False. num_shards: number of output file shards. """ with contextlib2.ExitStack() as tf_record_close_stack, \ tf.gfile.GFile(annotations_file, 'r') as fid: output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords( tf_record_close_stack, output_path, num_shards) groundtruth_data = json.load(fid) images = groundtruth_data['images'] category_index = label_map_util.create_category_index( groundtruth_data['categories']) annotations_index = {} if 'annotations' in groundtruth_data: tf.logging.info( 'Found groundtruth annotations. Building annotations index.') for annotation in groundtruth_data['annotations']: image_id = annotation['image_id'] if image_id not in annotations_index: annotations_index[image_id] = [] annotations_index[image_id].append(annotation) missing_annotation_count = 0 for image in images: image_id = image['id'] if image_id not in annotations_index: missing_annotation_count += 1 annotations_index[image_id] = [] tf.logging.info('%d images are missing annotations.', missing_annotation_count) total_num_annotations_skipped = 0 for idx, image in enumerate(images): if idx % 100 == 0: tf.logging.info('On image %d of %d', idx, len(images)) annotations_list = annotations_index[image['id']] _, tf_example, num_annotations_skipped = create_tf_example( image, annotations_list, image_dir, category_index, include_masks) total_num_annotations_skipped += num_annotations_skipped shard_idx = idx % num_shards output_tfrecords[shard_idx].write(tf_example.SerializeToString()) tf.logging.info('Finished writing, skipped %d annotations.', total_num_annotations_skipped) def main(_): assert FLAGS.train_image_dir, '`train_image_dir` missing.' assert FLAGS.val_image_dir, '`val_image_dir` missing.' assert FLAGS.test_image_dir, '`test_image_dir` missing.' assert FLAGS.train_annotations_file, '`train_annotations_file` missing.' assert FLAGS.val_annotations_file, '`val_annotations_file` missing.' assert FLAGS.testdev_annotations_file, '`testdev_annotations_file` missing.' if not tf.gfile.IsDirectory(FLAGS.output_dir): tf.gfile.MakeDirs(FLAGS.output_dir) train_output_path = os.path.join(FLAGS.output_dir, 'coco_train.record') val_output_path = os.path.join(FLAGS.output_dir, 'coco_val.record') testdev_output_path = os.path.join(FLAGS.output_dir, 'coco_testdev.record') _create_tf_record_from_coco_annotations( FLAGS.train_annotations_file, FLAGS.train_image_dir, train_output_path, FLAGS.include_masks, num_shards=100) _create_tf_record_from_coco_annotations( FLAGS.val_annotations_file, FLAGS.val_image_dir, val_output_path, FLAGS.include_masks, num_shards=10) _create_tf_record_from_coco_annotations( FLAGS.testdev_annotations_file, FLAGS.test_image_dir, testdev_output_path, FLAGS.include_masks, num_shards=100) if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/dataset_tools/create_coco_tf_record.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test for create_kitti_tf_record.py.""" import os import numpy as np import PIL.Image import tensorflow as tf from object_detection.dataset_tools import create_kitti_tf_record class CreateKittiTFRecordTest(tf.test.TestCase): def _assertProtoEqual(self, proto_field, expectation): """Helper function to assert if a proto field equals some value. Args: proto_field: The protobuf field to compare. expectation: The expected value of the protobuf field. """ proto_list = [p for p in proto_field] self.assertListEqual(proto_list, expectation) def test_dict_to_tf_example(self): image_file_name = 'tmp_image.jpg' image_data = np.random.rand(256, 256, 3) save_path = os.path.join(self.get_temp_dir(), image_file_name) image = PIL.Image.fromarray(image_data, 'RGB') image.save(save_path) annotations = {} annotations['2d_bbox_left'] = np.array([64]) annotations['2d_bbox_top'] = np.array([64]) annotations['2d_bbox_right'] = np.array([192]) annotations['2d_bbox_bottom'] = np.array([192]) annotations['type'] = ['car'] annotations['truncated'] = np.array([1]) annotations['alpha'] = np.array([2]) annotations['3d_bbox_height'] = np.array([10]) annotations['3d_bbox_width'] = np.array([11]) annotations['3d_bbox_length'] = np.array([12]) annotations['3d_bbox_x'] = np.array([13]) annotations['3d_bbox_y'] = np.array([14]) annotations['3d_bbox_z'] = np.array([15]) annotations['3d_bbox_rot_y'] = np.array([4]) label_map_dict = { 'background': 0, 'car': 1, } example = create_kitti_tf_record.prepare_example( save_path, annotations, label_map_dict) self._assertProtoEqual( example.features.feature['image/height'].int64_list.value, [256]) self._assertProtoEqual( example.features.feature['image/width'].int64_list.value, [256]) self._assertProtoEqual( example.features.feature['image/filename'].bytes_list.value, [save_path]) self._assertProtoEqual( example.features.feature['image/source_id'].bytes_list.value, [save_path]) self._assertProtoEqual( example.features.feature['image/format'].bytes_list.value, ['png']) self._assertProtoEqual( example.features.feature['image/object/bbox/xmin'].float_list.value, [0.25]) self._assertProtoEqual( example.features.feature['image/object/bbox/ymin'].float_list.value, [0.25]) self._assertProtoEqual( example.features.feature['image/object/bbox/xmax'].float_list.value, [0.75]) self._assertProtoEqual( example.features.feature['image/object/bbox/ymax'].float_list.value, [0.75]) self._assertProtoEqual( example.features.feature['image/object/class/text'].bytes_list.value, ['car']) self._assertProtoEqual( example.features.feature['image/object/class/label'].int64_list.value, [1]) self._assertProtoEqual( example.features.feature['image/object/truncated'].float_list.value, [1]) self._assertProtoEqual( example.features.feature['image/object/alpha'].float_list.value, [2]) self._assertProtoEqual(example.features.feature[ 'image/object/3d_bbox/height'].float_list.value, [10]) self._assertProtoEqual( example.features.feature['image/object/3d_bbox/width'].float_list.value, [11]) self._assertProtoEqual(example.features.feature[ 'image/object/3d_bbox/length'].float_list.value, [12]) self._assertProtoEqual( example.features.feature['image/object/3d_bbox/x'].float_list.value, [13]) self._assertProtoEqual( example.features.feature['image/object/3d_bbox/y'].float_list.value, [14]) self._assertProtoEqual( example.features.feature['image/object/3d_bbox/z'].float_list.value, [15]) self._assertProtoEqual( example.features.feature['image/object/3d_bbox/rot_y'].float_list.value, [4]) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/dataset_tools/create_kitti_tf_record_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Tests for detection_inference.py.""" import os import StringIO import numpy as np from PIL import Image import tensorflow as tf from object_detection.core import standard_fields from object_detection.inference import detection_inference from object_detection.utils import dataset_util def get_mock_tfrecord_path(): return os.path.join(tf.test.get_temp_dir(), 'mock.tfrec') def create_mock_tfrecord(): pil_image = Image.fromarray(np.array([[[123, 0, 0]]], dtype=np.uint8), 'RGB') image_output_stream = StringIO.StringIO() pil_image.save(image_output_stream, format='png') encoded_image = image_output_stream.getvalue() feature_map = { 'test_field': dataset_util.float_list_feature([1, 2, 3, 4]), standard_fields.TfExampleFields.image_encoded: dataset_util.bytes_feature(encoded_image), } tf_example = tf.train.Example(features=tf.train.Features(feature=feature_map)) with tf.python_io.TFRecordWriter(get_mock_tfrecord_path()) as writer: writer.write(tf_example.SerializeToString()) def get_mock_graph_path(): return os.path.join(tf.test.get_temp_dir(), 'mock_graph.pb') def create_mock_graph(): g = tf.Graph() with g.as_default(): in_image_tensor = tf.placeholder( tf.uint8, shape=[1, None, None, 3], name='image_tensor') tf.constant([2.0], name='num_detections') tf.constant( [[[0, 0.8, 0.7, 1], [0.1, 0.2, 0.8, 0.9], [0.2, 0.3, 0.4, 0.5]]], name='detection_boxes') tf.constant([[0.1, 0.2, 0.3]], name='detection_scores') tf.identity( tf.constant([[1.0, 2.0, 3.0]]) * tf.reduce_sum(tf.cast(in_image_tensor, dtype=tf.float32)), name='detection_classes') graph_def = g.as_graph_def() with tf.gfile.Open(get_mock_graph_path(), 'w') as fl: fl.write(graph_def.SerializeToString()) class InferDetectionsTests(tf.test.TestCase): def test_simple(self): create_mock_graph() create_mock_tfrecord() serialized_example_tensor, image_tensor = detection_inference.build_input( [get_mock_tfrecord_path()]) self.assertAllEqual(image_tensor.get_shape().as_list(), [1, None, None, 3]) (detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor) = detection_inference.build_inference_graph( image_tensor, get_mock_graph_path()) with self.test_session(use_gpu=False) as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) tf.train.start_queue_runners() tf_example = detection_inference.infer_detections_and_add_to_example( serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor, False) self.assertProtoEquals(r""" features { feature { key: "image/detection/bbox/ymin" value { float_list { value: [0.0, 0.1] } } } feature { key: "image/detection/bbox/xmin" value { float_list { value: [0.8, 0.2] } } } feature { key: "image/detection/bbox/ymax" value { float_list { value: [0.7, 0.8] } } } feature { key: "image/detection/bbox/xmax" value { float_list { value: [1.0, 0.9] } } } feature { key: "image/detection/label" value { int64_list { value: [123, 246] } } } feature { key: "image/detection/score" value { float_list { value: [0.1, 0.2] } } } feature { key: "image/encoded" value { bytes_list { value: "\211PNG\r\n\032\n\000\000\000\rIHDR\000\000\000\001\000\000" "\000\001\010\002\000\000\000\220wS\336\000\000\000\022IDATx" "\234b\250f`\000\000\000\000\377\377\003\000\001u\000|gO\242" "\213\000\000\000\000IEND\256B`\202" } } } feature { key: "test_field" value { float_list { value: [1.0, 2.0, 3.0, 4.0] } } } } """, tf_example) def test_discard_image(self): create_mock_graph() create_mock_tfrecord() serialized_example_tensor, image_tensor = detection_inference.build_input( [get_mock_tfrecord_path()]) (detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor) = detection_inference.build_inference_graph( image_tensor, get_mock_graph_path()) with self.test_session(use_gpu=False) as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) tf.train.start_queue_runners() tf_example = detection_inference.infer_detections_and_add_to_example( serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor, True) self.assertProtoEquals(r""" features { feature { key: "image/detection/bbox/ymin" value { float_list { value: [0.0, 0.1] } } } feature { key: "image/detection/bbox/xmin" value { float_list { value: [0.8, 0.2] } } } feature { key: "image/detection/bbox/ymax" value { float_list { value: [0.7, 0.8] } } } feature { key: "image/detection/bbox/xmax" value { float_list { value: [1.0, 0.9] } } } feature { key: "image/detection/label" value { int64_list { value: [123, 246] } } } feature { key: "image/detection/score" value { float_list { value: [0.1, 0.2] } } } feature { key: "test_field" value { float_list { value: [1.0, 2.0, 3.0, 4.0] } } } } """, tf_example) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/inference/detection_inference_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utility functions for detection inference.""" from __future__ import division import tensorflow as tf from object_detection.core import standard_fields def build_input(tfrecord_paths): """Builds the graph's input. Args: tfrecord_paths: List of paths to the input TFRecords Returns: serialized_example_tensor: The next serialized example. String scalar Tensor image_tensor: The decoded image of the example. Uint8 tensor, shape=[1, None, None,3] """ filename_queue = tf.train.string_input_producer( tfrecord_paths, shuffle=False, num_epochs=1) tf_record_reader = tf.TFRecordReader() _, serialized_example_tensor = tf_record_reader.read(filename_queue) features = tf.parse_single_example( serialized_example_tensor, features={ standard_fields.TfExampleFields.image_encoded: tf.FixedLenFeature([], tf.string), }) encoded_image = features[standard_fields.TfExampleFields.image_encoded] image_tensor = tf.image.decode_image(encoded_image, channels=3) image_tensor.set_shape([None, None, 3]) image_tensor = tf.expand_dims(image_tensor, 0) return serialized_example_tensor, image_tensor def build_inference_graph(image_tensor, inference_graph_path): """Loads the inference graph and connects it to the input image. Args: image_tensor: The input image. uint8 tensor, shape=[1, None, None, 3] inference_graph_path: Path to the inference graph with embedded weights Returns: detected_boxes_tensor: Detected boxes. Float tensor, shape=[num_detections, 4] detected_scores_tensor: Detected scores. Float tensor, shape=[num_detections] detected_labels_tensor: Detected labels. Int64 tensor, shape=[num_detections] """ with tf.gfile.Open(inference_graph_path, 'rb') as graph_def_file: graph_content = graph_def_file.read() graph_def = tf.GraphDef() graph_def.MergeFromString(graph_content) tf.import_graph_def( graph_def, name='', input_map={'image_tensor': image_tensor}) g = tf.get_default_graph() num_detections_tensor = tf.squeeze( g.get_tensor_by_name('num_detections:0'), 0) num_detections_tensor = tf.cast(num_detections_tensor, tf.int32) detected_boxes_tensor = tf.squeeze( g.get_tensor_by_name('detection_boxes:0'), 0) detected_boxes_tensor = detected_boxes_tensor[:num_detections_tensor] detected_scores_tensor = tf.squeeze( g.get_tensor_by_name('detection_scores:0'), 0) detected_scores_tensor = detected_scores_tensor[:num_detections_tensor] detected_labels_tensor = tf.squeeze( g.get_tensor_by_name('detection_classes:0'), 0) detected_labels_tensor = tf.cast(detected_labels_tensor, tf.int64) detected_labels_tensor = detected_labels_tensor[:num_detections_tensor] return detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor def infer_detections_and_add_to_example( serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor, discard_image_pixels): """Runs the supplied tensors and adds the inferred detections to the example. Args: serialized_example_tensor: Serialized TF example. Scalar string tensor detected_boxes_tensor: Detected boxes. Float tensor, shape=[num_detections, 4] detected_scores_tensor: Detected scores. Float tensor, shape=[num_detections] detected_labels_tensor: Detected labels. Int64 tensor, shape=[num_detections] discard_image_pixels: If true, discards the image from the result Returns: The de-serialized TF example augmented with the inferred detections. """ tf_example = tf.train.Example() (serialized_example, detected_boxes, detected_scores, detected_classes) = tf.get_default_session().run([ serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor ]) detected_boxes = detected_boxes.T tf_example.ParseFromString(serialized_example) feature = tf_example.features.feature feature[standard_fields.TfExampleFields. detection_score].float_list.value[:] = detected_scores feature[standard_fields.TfExampleFields. detection_bbox_ymin].float_list.value[:] = detected_boxes[0] feature[standard_fields.TfExampleFields. detection_bbox_xmin].float_list.value[:] = detected_boxes[1] feature[standard_fields.TfExampleFields. detection_bbox_ymax].float_list.value[:] = detected_boxes[2] feature[standard_fields.TfExampleFields. detection_bbox_xmax].float_list.value[:] = detected_boxes[3] feature[standard_fields.TfExampleFields. detection_class_label].int64_list.value[:] = detected_classes if discard_image_pixels: del feature[standard_fields.TfExampleFields.image_encoded] return tf_example
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/inference/detection_inference.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/inference/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Infers detections on a TFRecord of TFExamples given an inference graph. Example usage: ./infer_detections \ --input_tfrecord_paths=/path/to/input/tfrecord1,/path/to/input/tfrecord2 \ --output_tfrecord_path_prefix=/path/to/output/detections.tfrecord \ --inference_graph=/path/to/frozen_weights_inference_graph.pb The output is a TFRecord of TFExamples. Each TFExample from the input is first augmented with detections from the inference graph and then copied to the output. The input and output nodes of the inference graph are expected to have the same types, shapes, and semantics, as the input and output nodes of graphs produced by export_inference_graph.py, when run with --input_type=image_tensor. The script can also discard the image pixels in the output. This greatly reduces the output size and can potentially accelerate reading data in subsequent processing steps that don't require the images (e.g. computing metrics). """ import itertools import tensorflow as tf from object_detection.inference import detection_inference tf.flags.DEFINE_string('input_tfrecord_paths', None, 'A comma separated list of paths to input TFRecords.') tf.flags.DEFINE_string('output_tfrecord_path', None, 'Path to the output TFRecord.') tf.flags.DEFINE_string('inference_graph', None, 'Path to the inference graph with embedded weights.') tf.flags.DEFINE_boolean('discard_image_pixels', False, 'Discards the images in the output TFExamples. This' ' significantly reduces the output size and is useful' ' if the subsequent tools don\'t need access to the' ' images (e.g. when computing evaluation measures).') FLAGS = tf.flags.FLAGS def main(_): tf.logging.set_verbosity(tf.logging.INFO) required_flags = ['input_tfrecord_paths', 'output_tfrecord_path', 'inference_graph'] for flag_name in required_flags: if not getattr(FLAGS, flag_name): raise ValueError('Flag --{} is required'.format(flag_name)) with tf.Session() as sess: input_tfrecord_paths = [ v for v in FLAGS.input_tfrecord_paths.split(',') if v] tf.logging.info('Reading input from %d files', len(input_tfrecord_paths)) serialized_example_tensor, image_tensor = detection_inference.build_input( input_tfrecord_paths) tf.logging.info('Reading graph and building model...') (detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor) = detection_inference.build_inference_graph( image_tensor, FLAGS.inference_graph) tf.logging.info('Running inference and writing output to {}'.format( FLAGS.output_tfrecord_path)) sess.run(tf.local_variables_initializer()) tf.train.start_queue_runners() with tf.python_io.TFRecordWriter( FLAGS.output_tfrecord_path) as tf_record_writer: try: for counter in itertools.count(): tf.logging.log_every_n(tf.logging.INFO, 'Processed %d images...', 10, counter) tf_example = detection_inference.infer_detections_and_add_to_example( serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor, FLAGS.discard_image_pixels) tf_record_writer.write(tf_example.SerializeToString()) except tf.errors.OutOfRangeError: tf.logging.info('Finished processing records') if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/inference/infer_detections.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/data_decoders/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.data_decoders.tf_example_decoder.""" import os import numpy as np import tensorflow as tf from tensorflow.python.framework import test_util from object_detection.core import standard_fields as fields from object_detection.data_decoders import tf_example_decoder from object_detection.protos import input_reader_pb2 from object_detection.utils import dataset_util slim_example_decoder = tf.contrib.slim.tfexample_decoder class TfExampleDecoderTest(tf.test.TestCase): def _EncodeImage(self, image_tensor, encoding_type='jpeg'): with self.test_session(): if encoding_type == 'jpeg': image_encoded = tf.image.encode_jpeg(tf.constant(image_tensor)).eval() elif encoding_type == 'png': image_encoded = tf.image.encode_png(tf.constant(image_tensor)).eval() else: raise ValueError('Invalid encoding type.') return image_encoded def _DecodeImage(self, image_encoded, encoding_type='jpeg'): with self.test_session(): if encoding_type == 'jpeg': image_decoded = tf.image.decode_jpeg(tf.constant(image_encoded)).eval() elif encoding_type == 'png': image_decoded = tf.image.decode_png(tf.constant(image_encoded)).eval() else: raise ValueError('Invalid encoding type.') return image_decoded def testDecodeAdditionalChannels(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) additional_channel_tensor = np.random.randint( 256, size=(4, 5, 1)).astype(np.uint8) encoded_additional_channel = self._EncodeImage(additional_channel_tensor) decoded_additional_channel = self._DecodeImage(encoded_additional_channel) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/additional_channels/encoded': dataset_util.bytes_list_feature( [encoded_additional_channel] * 2), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/source_id': dataset_util.bytes_feature('image_id'), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( num_additional_channels=2) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual( np.concatenate([decoded_additional_channel] * 2, axis=2), tensor_dict[fields.InputDataFields.image_additional_channels]) def testDecodeJpegImage(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) decoded_jpeg = self._DecodeImage(encoded_jpeg) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/source_id': dataset_util.bytes_feature('image_id'), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.image]. get_shape().as_list()), [None, None, 3]) self.assertAllEqual((tensor_dict[fields.InputDataFields. original_image_spatial_shape]. get_shape().as_list()), [2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual(decoded_jpeg, tensor_dict[fields.InputDataFields.image]) self.assertAllEqual([4, 5], tensor_dict[fields.InputDataFields. original_image_spatial_shape]) self.assertEqual('image_id', tensor_dict[fields.InputDataFields.source_id]) def testDecodeImageKeyAndFilename(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/key/sha256': dataset_util.bytes_feature('abc'), 'image/filename': dataset_util.bytes_feature('filename') })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertEqual('abc', tensor_dict[fields.InputDataFields.key]) self.assertEqual('filename', tensor_dict[fields.InputDataFields.filename]) def testDecodePngImage(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_png = self._EncodeImage(image_tensor, encoding_type='png') decoded_png = self._DecodeImage(encoded_png, encoding_type='png') example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_png), 'image/format': dataset_util.bytes_feature('png'), 'image/source_id': dataset_util.bytes_feature('image_id') })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.image]. get_shape().as_list()), [None, None, 3]) self.assertAllEqual((tensor_dict[fields.InputDataFields. original_image_spatial_shape]. get_shape().as_list()), [2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual(decoded_png, tensor_dict[fields.InputDataFields.image]) self.assertAllEqual([4, 5], tensor_dict[fields.InputDataFields. original_image_spatial_shape]) self.assertEqual('image_id', tensor_dict[fields.InputDataFields.source_id]) def testDecodePngInstanceMasks(self): image_tensor = np.random.randint(256, size=(10, 10, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) mask_1 = np.random.randint(0, 2, size=(10, 10, 1)).astype(np.uint8) mask_2 = np.random.randint(0, 2, size=(10, 10, 1)).astype(np.uint8) encoded_png_1 = self._EncodeImage(mask_1, encoding_type='png') decoded_png_1 = np.squeeze(mask_1.astype(np.float32)) encoded_png_2 = self._EncodeImage(mask_2, encoding_type='png') decoded_png_2 = np.squeeze(mask_2.astype(np.float32)) encoded_masks = [encoded_png_1, encoded_png_2] decoded_masks = np.stack([decoded_png_1, decoded_png_2]) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/mask': dataset_util.bytes_list_feature(encoded_masks) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_instance_masks=True, instance_mask_type=input_reader_pb2.PNG_MASKS) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual( decoded_masks, tensor_dict[fields.InputDataFields.groundtruth_instance_masks]) def testDecodeEmptyPngInstanceMasks(self): image_tensor = np.random.randint(256, size=(10, 10, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) encoded_masks = [] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/mask': dataset_util.bytes_list_feature(encoded_masks), 'image/height': dataset_util.int64_feature(10), 'image/width': dataset_util.int64_feature(10), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_instance_masks=True, instance_mask_type=input_reader_pb2.PNG_MASKS) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual( tensor_dict[fields.InputDataFields.groundtruth_instance_masks].shape, [0, 10, 10]) def testDecodeBoundingBox(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_boxes] .get_shape().as_list()), [None, 4]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) expected_boxes = np.vstack([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]).transpose() self.assertAllEqual(expected_boxes, tensor_dict[fields.InputDataFields.groundtruth_boxes]) @test_util.enable_c_shapes def testDecodeKeypoint(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] keypoint_ys = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] keypoint_xs = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), 'image/object/keypoint/y': dataset_util.float_list_feature(keypoint_ys), 'image/object/keypoint/x': dataset_util.float_list_feature(keypoint_xs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder(num_keypoints=3) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_boxes] .get_shape().as_list()), [None, 4]) self.assertAllEqual( (tensor_dict[fields.InputDataFields.groundtruth_keypoints].get_shape() .as_list()), [2, 3, 2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) expected_boxes = np.vstack([bbox_ymins, bbox_xmins, bbox_ymaxs, bbox_xmaxs]).transpose() self.assertAllEqual(expected_boxes, tensor_dict[fields.InputDataFields.groundtruth_boxes]) expected_keypoints = ( np.vstack([keypoint_ys, keypoint_xs]).transpose().reshape((2, 3, 2))) self.assertAllEqual( expected_keypoints, tensor_dict[fields.InputDataFields.groundtruth_keypoints]) def testDecodeDefaultGroundtruthWeights(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_ymins = [0.0, 4.0] bbox_xmins = [1.0, 5.0] bbox_ymaxs = [2.0, 6.0] bbox_xmaxs = [3.0, 7.0] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/bbox/ymin': dataset_util.float_list_feature(bbox_ymins), 'image/object/bbox/xmin': dataset_util.float_list_feature(bbox_xmins), 'image/object/bbox/ymax': dataset_util.float_list_feature(bbox_ymaxs), 'image/object/bbox/xmax': dataset_util.float_list_feature(bbox_xmaxs), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_boxes] .get_shape().as_list()), [None, 4]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllClose(tensor_dict[fields.InputDataFields.groundtruth_weights], np.ones(2, dtype=np.float32)) @test_util.enable_c_shapes def testDecodeObjectLabel(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_classes = [0, 1] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/class/label': dataset_util.int64_list_feature(bbox_classes), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_classes] .get_shape().as_list()), [2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual(bbox_classes, tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelNoText(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_classes = [1, 2] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/class/label': dataset_util.int64_list_feature(bbox_classes), })).SerializeToString() label_map_string = """ item { id:1 name:'cat' } item { id:2 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_classes] .get_shape().as_list()), [None]) init = tf.tables_initializer() with self.test_session() as sess: sess.run(init) tensor_dict = sess.run(tensor_dict) self.assertAllEqual(bbox_classes, tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelUnrecognizedName(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_classes_text = ['cat', 'cheetah'] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), })).SerializeToString() label_map_string = """ item { id:2 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_classes] .get_shape().as_list()), [None]) with self.test_session() as sess: sess.run(tf.tables_initializer()) tensor_dict = sess.run(tensor_dict) self.assertAllEqual([2, -1], tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelWithMappingWithDisplayName(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_classes_text = ['cat', 'dog'] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), })).SerializeToString() label_map_string = """ item { id:3 display_name:'cat' } item { id:1 display_name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_classes] .get_shape().as_list()), [None]) with self.test_session() as sess: sess.run(tf.tables_initializer()) tensor_dict = sess.run(tensor_dict) self.assertAllEqual([3, 1], tensor_dict[fields.InputDataFields.groundtruth_classes]) def testDecodeObjectLabelWithMappingWithName(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) bbox_classes_text = ['cat', 'dog'] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/class/text': dataset_util.bytes_list_feature(bbox_classes_text), })).SerializeToString() label_map_string = """ item { id:3 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_classes] .get_shape().as_list()), [None]) with self.test_session() as sess: sess.run(tf.tables_initializer()) tensor_dict = sess.run(tensor_dict) self.assertAllEqual([3, 1], tensor_dict[fields.InputDataFields.groundtruth_classes]) @test_util.enable_c_shapes def testDecodeObjectArea(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) object_area = [100., 174.] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/area': dataset_util.float_list_feature(object_area), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_area] .get_shape().as_list()), [2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual(object_area, tensor_dict[fields.InputDataFields.groundtruth_area]) @test_util.enable_c_shapes def testDecodeObjectIsCrowd(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) object_is_crowd = [0, 1] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/is_crowd': dataset_util.int64_list_feature(object_is_crowd), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (tensor_dict[fields.InputDataFields.groundtruth_is_crowd].get_shape() .as_list()), [2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual( [bool(item) for item in object_is_crowd], tensor_dict[fields.InputDataFields.groundtruth_is_crowd]) @test_util.enable_c_shapes def testDecodeObjectDifficult(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) object_difficult = [0, 1] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/difficult': dataset_util.int64_list_feature(object_difficult), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (tensor_dict[fields.InputDataFields.groundtruth_difficult].get_shape() .as_list()), [2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual( [bool(item) for item in object_difficult], tensor_dict[fields.InputDataFields.groundtruth_difficult]) @test_util.enable_c_shapes def testDecodeObjectGroupOf(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) object_group_of = [0, 1] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/group_of': dataset_util.int64_list_feature(object_group_of), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (tensor_dict[fields.InputDataFields.groundtruth_group_of].get_shape() .as_list()), [2]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual( [bool(item) for item in object_group_of], tensor_dict[fields.InputDataFields.groundtruth_group_of]) def testDecodeObjectWeight(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) object_weights = [0.75, 1.0] example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/object/weight': dataset_util.float_list_feature(object_weights), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_weights] .get_shape().as_list()), [None]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual(object_weights, tensor_dict[fields.InputDataFields.groundtruth_weights]) @test_util.enable_c_shapes def testDecodeInstanceSegmentation(self): num_instances = 4 image_height = 5 image_width = 3 # Randomly generate image. image_tensor = np.random.randint( 256, size=(image_height, image_width, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) # Randomly generate instance segmentation masks. instance_masks = ( np.random.randint(2, size=(num_instances, image_height, image_width)).astype(np.float32)) instance_masks_flattened = np.reshape(instance_masks, [-1]) # Randomly generate class labels for each instance. object_classes = np.random.randint( 100, size=(num_instances)).astype(np.int64) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/height': dataset_util.int64_feature(image_height), 'image/width': dataset_util.int64_feature(image_width), 'image/object/mask': dataset_util.float_list_feature(instance_masks_flattened), 'image/object/class/label': dataset_util.int64_list_feature(object_classes) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder( load_instance_masks=True) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertAllEqual( (tensor_dict[fields.InputDataFields.groundtruth_instance_masks] .get_shape().as_list()), [4, 5, 3]) self.assertAllEqual((tensor_dict[fields.InputDataFields.groundtruth_classes] .get_shape().as_list()), [4]) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertAllEqual( instance_masks.astype(np.float32), tensor_dict[fields.InputDataFields.groundtruth_instance_masks]) self.assertAllEqual(object_classes, tensor_dict[fields.InputDataFields.groundtruth_classes]) def testInstancesNotAvailableByDefault(self): num_instances = 4 image_height = 5 image_width = 3 # Randomly generate image. image_tensor = np.random.randint( 256, size=(image_height, image_width, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) # Randomly generate instance segmentation masks. instance_masks = ( np.random.randint(2, size=(num_instances, image_height, image_width)).astype(np.float32)) instance_masks_flattened = np.reshape(instance_masks, [-1]) # Randomly generate class labels for each instance. object_classes = np.random.randint( 100, size=(num_instances)).astype(np.int64) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/height': dataset_util.int64_feature(image_height), 'image/width': dataset_util.int64_feature(image_width), 'image/object/mask': dataset_util.float_list_feature(instance_masks_flattened), 'image/object/class/label': dataset_util.int64_list_feature(object_classes) })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) self.assertTrue( fields.InputDataFields.groundtruth_instance_masks not in tensor_dict) def testDecodeImageLabels(self): image_tensor = np.random.randint(256, size=(4, 5, 3)).astype(np.uint8) encoded_jpeg = self._EncodeImage(image_tensor) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/class/label': dataset_util.int64_list_feature([1, 2]), })).SerializeToString() example_decoder = tf_example_decoder.TfExampleDecoder() tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) with self.test_session() as sess: tensor_dict = sess.run(tensor_dict) self.assertTrue( fields.InputDataFields.groundtruth_image_classes in tensor_dict) self.assertAllEqual( tensor_dict[fields.InputDataFields.groundtruth_image_classes], np.array([1, 2])) example = tf.train.Example( features=tf.train.Features( feature={ 'image/encoded': dataset_util.bytes_feature(encoded_jpeg), 'image/format': dataset_util.bytes_feature('jpeg'), 'image/class/text': dataset_util.bytes_list_feature(['dog', 'cat']), })).SerializeToString() label_map_string = """ item { id:3 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) example_decoder = tf_example_decoder.TfExampleDecoder( label_map_proto_file=label_map_path) tensor_dict = example_decoder.decode(tf.convert_to_tensor(example)) with self.test_session() as sess: sess.run(tf.tables_initializer()) tensor_dict = sess.run(tensor_dict) self.assertTrue( fields.InputDataFields.groundtruth_image_classes in tensor_dict) self.assertAllEqual( tensor_dict[fields.InputDataFields.groundtruth_image_classes], np.array([1, 3])) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/data_decoders/tf_example_decoder_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tensorflow Example proto decoder for object detection. A decoder to decode string tensors containing serialized tensorflow.Example protos for object detection. """ import tensorflow as tf from object_detection.core import data_decoder from object_detection.core import standard_fields as fields from object_detection.protos import input_reader_pb2 from object_detection.utils import label_map_util slim_example_decoder = tf.contrib.slim.tfexample_decoder class _ClassTensorHandler(slim_example_decoder.Tensor): """An ItemHandler to fetch class ids from class text.""" def __init__(self, tensor_key, label_map_proto_file, shape_keys=None, shape=None, default_value=''): """Initializes the LookupTensor handler. Simply calls a vocabulary (most often, a label mapping) lookup. Args: tensor_key: the name of the `TFExample` feature to read the tensor from. label_map_proto_file: File path to a text format LabelMapProto message mapping class text to id. shape_keys: Optional name or list of names of the TF-Example feature in which the tensor shape is stored. If a list, then each corresponds to one dimension of the shape. shape: Optional output shape of the `Tensor`. If provided, the `Tensor` is reshaped accordingly. default_value: The value used when the `tensor_key` is not found in a particular `TFExample`. Raises: ValueError: if both `shape_keys` and `shape` are specified. """ name_to_id = label_map_util.get_label_map_dict( label_map_proto_file, use_display_name=False) # We use a default_value of -1, but we expect all labels to be contained # in the label map. name_to_id_table = tf.contrib.lookup.HashTable( initializer=tf.contrib.lookup.KeyValueTensorInitializer( keys=tf.constant(list(name_to_id.keys())), values=tf.constant(list(name_to_id.values()), dtype=tf.int64)), default_value=-1) display_name_to_id = label_map_util.get_label_map_dict( label_map_proto_file, use_display_name=True) # We use a default_value of -1, but we expect all labels to be contained # in the label map. display_name_to_id_table = tf.contrib.lookup.HashTable( initializer=tf.contrib.lookup.KeyValueTensorInitializer( keys=tf.constant(list(display_name_to_id.keys())), values=tf.constant( list(display_name_to_id.values()), dtype=tf.int64)), default_value=-1) self._name_to_id_table = name_to_id_table self._display_name_to_id_table = display_name_to_id_table super(_ClassTensorHandler, self).__init__(tensor_key, shape_keys, shape, default_value) def tensors_to_item(self, keys_to_tensors): unmapped_tensor = super(_ClassTensorHandler, self).tensors_to_item(keys_to_tensors) return tf.maximum(self._name_to_id_table.lookup(unmapped_tensor), self._display_name_to_id_table.lookup(unmapped_tensor)) class _BackupHandler(slim_example_decoder.ItemHandler): """An ItemHandler that tries two ItemHandlers in order.""" def __init__(self, handler, backup): """Initializes the BackupHandler handler. If the first Handler's tensors_to_item returns a Tensor with no elements, the second Handler is used. Args: handler: The primary ItemHandler. backup: The backup ItemHandler. Raises: ValueError: if either is not an ItemHandler. """ if not isinstance(handler, slim_example_decoder.ItemHandler): raise ValueError('Primary handler is of type %s instead of ItemHandler' % type(handler)) if not isinstance(backup, slim_example_decoder.ItemHandler): raise ValueError( 'Backup handler is of type %s instead of ItemHandler' % type(backup)) self._handler = handler self._backup = backup super(_BackupHandler, self).__init__(handler.keys + backup.keys) def tensors_to_item(self, keys_to_tensors): item = self._handler.tensors_to_item(keys_to_tensors) return tf.cond( pred=tf.equal(tf.reduce_prod(tf.shape(item)), 0), true_fn=lambda: self._backup.tensors_to_item(keys_to_tensors), false_fn=lambda: item) class TfExampleDecoder(data_decoder.DataDecoder): """Tensorflow Example proto decoder.""" def __init__(self, load_instance_masks=False, instance_mask_type=input_reader_pb2.NUMERICAL_MASKS, label_map_proto_file=None, use_display_name=False, dct_method='', num_keypoints=0, num_additional_channels=0): """Constructor sets keys_to_features and items_to_handlers. Args: load_instance_masks: whether or not to load and handle instance masks. instance_mask_type: type of instance masks. Options are provided in input_reader.proto. This is only used if `load_instance_masks` is True. label_map_proto_file: a file path to a object_detection.protos.StringIntLabelMap proto. If provided, then the mapped IDs of 'image/object/class/text' will take precedence over the existing 'image/object/class/label' ID. Also, if provided, it is assumed that 'image/object/class/text' will be in the data. use_display_name: whether or not to use the `display_name` for label mapping (instead of `name`). Only used if label_map_proto_file is provided. dct_method: An optional string. Defaults to None. It only takes effect when image format is jpeg, used to specify a hint about the algorithm used for jpeg decompression. Currently valid values are ['INTEGER_FAST', 'INTEGER_ACCURATE']. The hint may be ignored, for example, the jpeg library does not have that specific option. num_keypoints: the number of keypoints per object. num_additional_channels: how many additional channels to use. Raises: ValueError: If `instance_mask_type` option is not one of input_reader_pb2.DEFAULT, input_reader_pb2.NUMERICAL, or input_reader_pb2.PNG_MASKS. """ # TODO(rathodv): delete unused `use_display_name` argument once we change # other decoders to handle label maps similarly. del use_display_name self.keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''), 'image/key/sha256': tf.FixedLenFeature((), tf.string, default_value=''), 'image/source_id': tf.FixedLenFeature((), tf.string, default_value=''), 'image/height': tf.FixedLenFeature((), tf.int64, default_value=1), 'image/width': tf.FixedLenFeature((), tf.int64, default_value=1), # Image-level labels. 'image/class/text': tf.VarLenFeature(tf.string), 'image/class/label': tf.VarLenFeature(tf.int64), # Object boxes and classes. 'image/object/bbox/xmin': tf.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.VarLenFeature(tf.float32), 'image/object/class/label': tf.VarLenFeature(tf.int64), 'image/object/class/text': tf.VarLenFeature(tf.string), 'image/object/area': tf.VarLenFeature(tf.float32), 'image/object/is_crowd': tf.VarLenFeature(tf.int64), 'image/object/difficult': tf.VarLenFeature(tf.int64), 'image/object/group_of': tf.VarLenFeature(tf.int64), 'image/object/weight': tf.VarLenFeature(tf.float32), } # We are checking `dct_method` instead of passing it directly in order to # ensure TF version 1.6 compatibility. if dct_method: image = slim_example_decoder.Image( image_key='image/encoded', format_key='image/format', channels=3, dct_method=dct_method) additional_channel_image = slim_example_decoder.Image( image_key='image/additional_channels/encoded', format_key='image/format', channels=1, repeated=True, dct_method=dct_method) else: image = slim_example_decoder.Image( image_key='image/encoded', format_key='image/format', channels=3) additional_channel_image = slim_example_decoder.Image( image_key='image/additional_channels/encoded', format_key='image/format', channels=1, repeated=True) self.items_to_handlers = { fields.InputDataFields.image: image, fields.InputDataFields.source_id: ( slim_example_decoder.Tensor('image/source_id')), fields.InputDataFields.key: ( slim_example_decoder.Tensor('image/key/sha256')), fields.InputDataFields.filename: ( slim_example_decoder.Tensor('image/filename')), # Object boxes and classes. fields.InputDataFields.groundtruth_boxes: ( slim_example_decoder.BoundingBox(['ymin', 'xmin', 'ymax', 'xmax'], 'image/object/bbox/')), fields.InputDataFields.groundtruth_area: slim_example_decoder.Tensor('image/object/area'), fields.InputDataFields.groundtruth_is_crowd: ( slim_example_decoder.Tensor('image/object/is_crowd')), fields.InputDataFields.groundtruth_difficult: ( slim_example_decoder.Tensor('image/object/difficult')), fields.InputDataFields.groundtruth_group_of: ( slim_example_decoder.Tensor('image/object/group_of')), fields.InputDataFields.groundtruth_weights: ( slim_example_decoder.Tensor('image/object/weight')), } if num_additional_channels > 0: self.keys_to_features[ 'image/additional_channels/encoded'] = tf.FixedLenFeature( (num_additional_channels,), tf.string) self.items_to_handlers[ fields.InputDataFields. image_additional_channels] = additional_channel_image self._num_keypoints = num_keypoints if num_keypoints > 0: self.keys_to_features['image/object/keypoint/x'] = ( tf.VarLenFeature(tf.float32)) self.keys_to_features['image/object/keypoint/y'] = ( tf.VarLenFeature(tf.float32)) self.items_to_handlers[fields.InputDataFields.groundtruth_keypoints] = ( slim_example_decoder.ItemHandlerCallback( ['image/object/keypoint/y', 'image/object/keypoint/x'], self._reshape_keypoints)) if load_instance_masks: if instance_mask_type in (input_reader_pb2.DEFAULT, input_reader_pb2.NUMERICAL_MASKS): self.keys_to_features['image/object/mask'] = ( tf.VarLenFeature(tf.float32)) self.items_to_handlers[ fields.InputDataFields.groundtruth_instance_masks] = ( slim_example_decoder.ItemHandlerCallback( ['image/object/mask', 'image/height', 'image/width'], self._reshape_instance_masks)) elif instance_mask_type == input_reader_pb2.PNG_MASKS: self.keys_to_features['image/object/mask'] = tf.VarLenFeature(tf.string) self.items_to_handlers[ fields.InputDataFields.groundtruth_instance_masks] = ( slim_example_decoder.ItemHandlerCallback( ['image/object/mask', 'image/height', 'image/width'], self._decode_png_instance_masks)) else: raise ValueError('Did not recognize the `instance_mask_type` option.') if label_map_proto_file: # If the label_map_proto is provided, try to use it in conjunction with # the class text, and fall back to a materialized ID. label_handler = _BackupHandler( _ClassTensorHandler( 'image/object/class/text', label_map_proto_file, default_value=''), slim_example_decoder.Tensor('image/object/class/label')) image_label_handler = _BackupHandler( _ClassTensorHandler( fields.TfExampleFields.image_class_text, label_map_proto_file, default_value=''), slim_example_decoder.Tensor(fields.TfExampleFields.image_class_label)) else: label_handler = slim_example_decoder.Tensor('image/object/class/label') image_label_handler = slim_example_decoder.Tensor( fields.TfExampleFields.image_class_label) self.items_to_handlers[ fields.InputDataFields.groundtruth_classes] = label_handler self.items_to_handlers[ fields.InputDataFields.groundtruth_image_classes] = image_label_handler def decode(self, tf_example_string_tensor): """Decodes serialized tensorflow example and returns a tensor dictionary. Args: tf_example_string_tensor: a string tensor holding a serialized tensorflow example proto. Returns: A dictionary of the following tensors. fields.InputDataFields.image - 3D uint8 tensor of shape [None, None, 3] containing image. fields.InputDataFields.original_image_spatial_shape - 1D int32 tensor of shape [2] containing shape of the image. fields.InputDataFields.source_id - string tensor containing original image id. fields.InputDataFields.key - string tensor with unique sha256 hash key. fields.InputDataFields.filename - string tensor with original dataset filename. fields.InputDataFields.groundtruth_boxes - 2D float32 tensor of shape [None, 4] containing box corners. fields.InputDataFields.groundtruth_classes - 1D int64 tensor of shape [None] containing classes for the boxes. fields.InputDataFields.groundtruth_weights - 1D float32 tensor of shape [None] indicating the weights of groundtruth boxes. fields.InputDataFields.groundtruth_area - 1D float32 tensor of shape [None] containing containing object mask area in pixel squared. fields.InputDataFields.groundtruth_is_crowd - 1D bool tensor of shape [None] indicating if the boxes enclose a crowd. Optional: fields.InputDataFields.image_additional_channels - 3D uint8 tensor of shape [None, None, num_additional_channels]. 1st dim is height; 2nd dim is width; 3rd dim is the number of additional channels. fields.InputDataFields.groundtruth_difficult - 1D bool tensor of shape [None] indicating if the boxes represent `difficult` instances. fields.InputDataFields.groundtruth_group_of - 1D bool tensor of shape [None] indicating if the boxes represent `group_of` instances. fields.InputDataFields.groundtruth_keypoints - 3D float32 tensor of shape [None, None, 2] containing keypoints, where the coordinates of the keypoints are ordered (y, x). fields.InputDataFields.groundtruth_instance_masks - 3D float32 tensor of shape [None, None, None] containing instance masks. fields.InputDataFields.groundtruth_image_classes - 1D uint64 of shape [None] containing classes for the boxes. """ serialized_example = tf.reshape(tf_example_string_tensor, shape=[]) decoder = slim_example_decoder.TFExampleDecoder(self.keys_to_features, self.items_to_handlers) keys = decoder.list_items() tensors = decoder.decode(serialized_example, items=keys) tensor_dict = dict(zip(keys, tensors)) is_crowd = fields.InputDataFields.groundtruth_is_crowd tensor_dict[is_crowd] = tf.cast(tensor_dict[is_crowd], dtype=tf.bool) tensor_dict[fields.InputDataFields.image].set_shape([None, None, 3]) tensor_dict[fields.InputDataFields.original_image_spatial_shape] = tf.shape( tensor_dict[fields.InputDataFields.image])[:2] if fields.InputDataFields.image_additional_channels in tensor_dict: channels = tensor_dict[fields.InputDataFields.image_additional_channels] channels = tf.squeeze(channels, axis=3) channels = tf.transpose(channels, perm=[1, 2, 0]) tensor_dict[fields.InputDataFields.image_additional_channels] = channels def default_groundtruth_weights(): return tf.ones( [tf.shape(tensor_dict[fields.InputDataFields.groundtruth_boxes])[0]], dtype=tf.float32) tensor_dict[fields.InputDataFields.groundtruth_weights] = tf.cond( tf.greater( tf.shape( tensor_dict[fields.InputDataFields.groundtruth_weights])[0], 0), lambda: tensor_dict[fields.InputDataFields.groundtruth_weights], default_groundtruth_weights) return tensor_dict def _reshape_keypoints(self, keys_to_tensors): """Reshape keypoints. The instance segmentation masks are reshaped to [num_instances, num_keypoints, 2]. Args: keys_to_tensors: a dictionary from keys to tensors. Returns: A 3-D float tensor of shape [num_instances, num_keypoints, 2] with values in {0, 1}. """ y = keys_to_tensors['image/object/keypoint/y'] if isinstance(y, tf.SparseTensor): y = tf.sparse_tensor_to_dense(y) y = tf.expand_dims(y, 1) x = keys_to_tensors['image/object/keypoint/x'] if isinstance(x, tf.SparseTensor): x = tf.sparse_tensor_to_dense(x) x = tf.expand_dims(x, 1) keypoints = tf.concat([y, x], 1) keypoints = tf.reshape(keypoints, [-1, self._num_keypoints, 2]) return keypoints def _reshape_instance_masks(self, keys_to_tensors): """Reshape instance segmentation masks. The instance segmentation masks are reshaped to [num_instances, height, width]. Args: keys_to_tensors: a dictionary from keys to tensors. Returns: A 3-D float tensor of shape [num_instances, height, width] with values in {0, 1}. """ height = keys_to_tensors['image/height'] width = keys_to_tensors['image/width'] to_shape = tf.cast(tf.stack([-1, height, width]), tf.int32) masks = keys_to_tensors['image/object/mask'] if isinstance(masks, tf.SparseTensor): masks = tf.sparse_tensor_to_dense(masks) masks = tf.reshape(tf.to_float(tf.greater(masks, 0.0)), to_shape) return tf.cast(masks, tf.float32) def _decode_png_instance_masks(self, keys_to_tensors): """Decode PNG instance segmentation masks and stack into dense tensor. The instance segmentation masks are reshaped to [num_instances, height, width]. Args: keys_to_tensors: a dictionary from keys to tensors. Returns: A 3-D float tensor of shape [num_instances, height, width] with values in {0, 1}. """ def decode_png_mask(image_buffer): image = tf.squeeze( tf.image.decode_image(image_buffer, channels=1), axis=2) image.set_shape([None, None]) image = tf.to_float(tf.greater(image, 0)) return image png_masks = keys_to_tensors['image/object/mask'] height = keys_to_tensors['image/height'] width = keys_to_tensors['image/width'] if isinstance(png_masks, tf.SparseTensor): png_masks = tf.sparse_tensor_to_dense(png_masks, default_value='') return tf.cond( tf.greater(tf.size(png_masks), 0), lambda: tf.map_fn(decode_png_mask, png_masks, dtype=tf.float32), lambda: tf.zeros(tf.to_int32(tf.stack([0, height, width]))))
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/data_decoders/tf_example_decoder.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.core.bipartite_matcher.""" import tensorflow as tf from object_detection.matchers import bipartite_matcher class GreedyBipartiteMatcherTest(tf.test.TestCase): def test_get_expected_matches_when_all_rows_are_valid(self): similarity_matrix = tf.constant([[0.50, 0.1, 0.8], [0.15, 0.2, 0.3]]) valid_rows = tf.ones([2], dtype=tf.bool) expected_match_results = [-1, 1, 0] matcher = bipartite_matcher.GreedyBipartiteMatcher() match = matcher.match(similarity_matrix, valid_rows=valid_rows) with self.test_session() as sess: match_results_out = sess.run(match._match_results) self.assertAllEqual(match_results_out, expected_match_results) def test_get_expected_matches_with_all_rows_be_default(self): similarity_matrix = tf.constant([[0.50, 0.1, 0.8], [0.15, 0.2, 0.3]]) expected_match_results = [-1, 1, 0] matcher = bipartite_matcher.GreedyBipartiteMatcher() match = matcher.match(similarity_matrix) with self.test_session() as sess: match_results_out = sess.run(match._match_results) self.assertAllEqual(match_results_out, expected_match_results) def test_get_no_matches_with_zero_valid_rows(self): similarity_matrix = tf.constant([[0.50, 0.1, 0.8], [0.15, 0.2, 0.3]]) valid_rows = tf.zeros([2], dtype=tf.bool) expected_match_results = [-1, -1, -1] matcher = bipartite_matcher.GreedyBipartiteMatcher() match = matcher.match(similarity_matrix, valid_rows) with self.test_session() as sess: match_results_out = sess.run(match._match_results) self.assertAllEqual(match_results_out, expected_match_results) def test_get_expected_matches_with_only_one_valid_row(self): similarity_matrix = tf.constant([[0.50, 0.1, 0.8], [0.15, 0.2, 0.3]]) valid_rows = tf.constant([True, False], dtype=tf.bool) expected_match_results = [-1, -1, 0] matcher = bipartite_matcher.GreedyBipartiteMatcher() match = matcher.match(similarity_matrix, valid_rows) with self.test_session() as sess: match_results_out = sess.run(match._match_results) self.assertAllEqual(match_results_out, expected_match_results) def test_get_expected_matches_with_only_one_valid_row_at_bottom(self): similarity_matrix = tf.constant([[0.15, 0.2, 0.3], [0.50, 0.1, 0.8]]) valid_rows = tf.constant([False, True], dtype=tf.bool) expected_match_results = [-1, -1, 0] matcher = bipartite_matcher.GreedyBipartiteMatcher() match = matcher.match(similarity_matrix, valid_rows) with self.test_session() as sess: match_results_out = sess.run(match._match_results) self.assertAllEqual(match_results_out, expected_match_results) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/matchers/bipartite_matcher_test.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/matchers/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.matchers.argmax_matcher.""" import numpy as np import tensorflow as tf from object_detection.matchers import argmax_matcher from object_detection.utils import test_case class ArgMaxMatcherTest(test_case.TestCase): def test_return_correct_matches_with_default_thresholds(self): def graph_fn(similarity_matrix): matcher = argmax_matcher.ArgMaxMatcher(matched_threshold=None) match = matcher.match(similarity_matrix) matched_cols = match.matched_column_indicator() unmatched_cols = match.unmatched_column_indicator() match_results = match.match_results return (matched_cols, unmatched_cols, match_results) similarity = np.array([[1., 1, 1, 3, 1], [2, -1, 2, 0, 4], [3, 0, -1, 0, 0]], dtype=np.float32) expected_matched_rows = np.array([2, 0, 1, 0, 1]) (res_matched_cols, res_unmatched_cols, res_match_results) = self.execute(graph_fn, [similarity]) self.assertAllEqual(res_match_results[res_matched_cols], expected_matched_rows) self.assertAllEqual(np.nonzero(res_matched_cols)[0], [0, 1, 2, 3, 4]) self.assertFalse(np.all(res_unmatched_cols)) def test_return_correct_matches_with_empty_rows(self): def graph_fn(similarity_matrix): matcher = argmax_matcher.ArgMaxMatcher(matched_threshold=None) match = matcher.match(similarity_matrix) return match.unmatched_column_indicator() similarity = 0.2 * np.ones([0, 5], dtype=np.float32) res_unmatched_cols = self.execute(graph_fn, [similarity]) self.assertAllEqual(np.nonzero(res_unmatched_cols)[0], np.arange(5)) def test_return_correct_matches_with_matched_threshold(self): def graph_fn(similarity): matcher = argmax_matcher.ArgMaxMatcher(matched_threshold=3.) match = matcher.match(similarity) matched_cols = match.matched_column_indicator() unmatched_cols = match.unmatched_column_indicator() match_results = match.match_results return (matched_cols, unmatched_cols, match_results) similarity = np.array([[1, 1, 1, 3, 1], [2, -1, 2, 0, 4], [3, 0, -1, 0, 0]], dtype=np.float32) expected_matched_cols = np.array([0, 3, 4]) expected_matched_rows = np.array([2, 0, 1]) expected_unmatched_cols = np.array([1, 2]) (res_matched_cols, res_unmatched_cols, match_results) = self.execute(graph_fn, [similarity]) self.assertAllEqual(match_results[res_matched_cols], expected_matched_rows) self.assertAllEqual(np.nonzero(res_matched_cols)[0], expected_matched_cols) self.assertAllEqual(np.nonzero(res_unmatched_cols)[0], expected_unmatched_cols) def test_return_correct_matches_with_matched_and_unmatched_threshold(self): def graph_fn(similarity): matcher = argmax_matcher.ArgMaxMatcher(matched_threshold=3., unmatched_threshold=2.) match = matcher.match(similarity) matched_cols = match.matched_column_indicator() unmatched_cols = match.unmatched_column_indicator() match_results = match.match_results return (matched_cols, unmatched_cols, match_results) similarity = np.array([[1, 1, 1, 3, 1], [2, -1, 2, 0, 4], [3, 0, -1, 0, 0]], dtype=np.float32) expected_matched_cols = np.array([0, 3, 4]) expected_matched_rows = np.array([2, 0, 1]) expected_unmatched_cols = np.array([1]) # col 2 has too high maximum val (res_matched_cols, res_unmatched_cols, match_results) = self.execute(graph_fn, [similarity]) self.assertAllEqual(match_results[res_matched_cols], expected_matched_rows) self.assertAllEqual(np.nonzero(res_matched_cols)[0], expected_matched_cols) self.assertAllEqual(np.nonzero(res_unmatched_cols)[0], expected_unmatched_cols) def test_return_correct_matches_negatives_lower_than_unmatched_false(self): def graph_fn(similarity): matcher = argmax_matcher.ArgMaxMatcher( matched_threshold=3., unmatched_threshold=2., negatives_lower_than_unmatched=False) match = matcher.match(similarity) matched_cols = match.matched_column_indicator() unmatched_cols = match.unmatched_column_indicator() match_results = match.match_results return (matched_cols, unmatched_cols, match_results) similarity = np.array([[1, 1, 1, 3, 1], [2, -1, 2, 0, 4], [3, 0, -1, 0, 0]], dtype=np.float32) expected_matched_cols = np.array([0, 3, 4]) expected_matched_rows = np.array([2, 0, 1]) expected_unmatched_cols = np.array([2]) # col 1 has too low maximum val (res_matched_cols, res_unmatched_cols, match_results) = self.execute(graph_fn, [similarity]) self.assertAllEqual(match_results[res_matched_cols], expected_matched_rows) self.assertAllEqual(np.nonzero(res_matched_cols)[0], expected_matched_cols) self.assertAllEqual(np.nonzero(res_unmatched_cols)[0], expected_unmatched_cols) def test_return_correct_matches_unmatched_row_not_using_force_match(self): def graph_fn(similarity): matcher = argmax_matcher.ArgMaxMatcher(matched_threshold=3., unmatched_threshold=2.) match = matcher.match(similarity) matched_cols = match.matched_column_indicator() unmatched_cols = match.unmatched_column_indicator() match_results = match.match_results return (matched_cols, unmatched_cols, match_results) similarity = np.array([[1, 1, 1, 3, 1], [-1, 0, -2, -2, -1], [3, 0, -1, 2, 0]], dtype=np.float32) expected_matched_cols = np.array([0, 3]) expected_matched_rows = np.array([2, 0]) expected_unmatched_cols = np.array([1, 2, 4]) (res_matched_cols, res_unmatched_cols, match_results) = self.execute(graph_fn, [similarity]) self.assertAllEqual(match_results[res_matched_cols], expected_matched_rows) self.assertAllEqual(np.nonzero(res_matched_cols)[0], expected_matched_cols) self.assertAllEqual(np.nonzero(res_unmatched_cols)[0], expected_unmatched_cols) def test_return_correct_matches_unmatched_row_while_using_force_match(self): def graph_fn(similarity): matcher = argmax_matcher.ArgMaxMatcher(matched_threshold=3., unmatched_threshold=2., force_match_for_each_row=True) match = matcher.match(similarity) matched_cols = match.matched_column_indicator() unmatched_cols = match.unmatched_column_indicator() match_results = match.match_results return (matched_cols, unmatched_cols, match_results) similarity = np.array([[1, 1, 1, 3, 1], [-1, 0, -2, -2, -1], [3, 0, -1, 2, 0]], dtype=np.float32) expected_matched_cols = np.array([0, 1, 3]) expected_matched_rows = np.array([2, 1, 0]) expected_unmatched_cols = np.array([2, 4]) # col 2 has too high max val (res_matched_cols, res_unmatched_cols, match_results) = self.execute(graph_fn, [similarity]) self.assertAllEqual(match_results[res_matched_cols], expected_matched_rows) self.assertAllEqual(np.nonzero(res_matched_cols)[0], expected_matched_cols) self.assertAllEqual(np.nonzero(res_unmatched_cols)[0], expected_unmatched_cols) def test_return_correct_matches_using_force_match_padded_groundtruth(self): def graph_fn(similarity, valid_rows): matcher = argmax_matcher.ArgMaxMatcher(matched_threshold=3., unmatched_threshold=2., force_match_for_each_row=True) match = matcher.match(similarity, valid_rows) matched_cols = match.matched_column_indicator() unmatched_cols = match.unmatched_column_indicator() match_results = match.match_results return (matched_cols, unmatched_cols, match_results) similarity = np.array([[1, 1, 1, 3, 1], [-1, 0, -2, -2, -1], [0, 0, 0, 0, 0], [3, 0, -1, 2, 0], [0, 0, 0, 0, 0]], dtype=np.float32) valid_rows = np.array([True, True, False, True, False]) expected_matched_cols = np.array([0, 1, 3]) expected_matched_rows = np.array([3, 1, 0]) expected_unmatched_cols = np.array([2, 4]) # col 2 has too high max val (res_matched_cols, res_unmatched_cols, match_results) = self.execute(graph_fn, [similarity, valid_rows]) self.assertAllEqual(match_results[res_matched_cols], expected_matched_rows) self.assertAllEqual(np.nonzero(res_matched_cols)[0], expected_matched_cols) self.assertAllEqual(np.nonzero(res_unmatched_cols)[0], expected_unmatched_cols) def test_valid_arguments_corner_case(self): argmax_matcher.ArgMaxMatcher(matched_threshold=1, unmatched_threshold=1) def test_invalid_arguments_corner_case_negatives_lower_than_thres_false(self): with self.assertRaises(ValueError): argmax_matcher.ArgMaxMatcher(matched_threshold=1, unmatched_threshold=1, negatives_lower_than_unmatched=False) def test_invalid_arguments_no_matched_threshold(self): with self.assertRaises(ValueError): argmax_matcher.ArgMaxMatcher(matched_threshold=None, unmatched_threshold=4) def test_invalid_arguments_unmatched_thres_larger_than_matched_thres(self): with self.assertRaises(ValueError): argmax_matcher.ArgMaxMatcher(matched_threshold=1, unmatched_threshold=2) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/matchers/argmax_matcher_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Bipartite matcher implementation.""" import tensorflow as tf from tensorflow.contrib.image.python.ops import image_ops from object_detection.core import matcher class GreedyBipartiteMatcher(matcher.Matcher): """Wraps a Tensorflow greedy bipartite matcher.""" def __init__(self, use_matmul_gather=False): """Constructs a Matcher. Args: use_matmul_gather: Force constructed match objects to use matrix multiplication based gather instead of standard tf.gather. (Default: False). """ super(GreedyBipartiteMatcher, self).__init__( use_matmul_gather=use_matmul_gather) def _match(self, similarity_matrix, valid_rows): """Bipartite matches a collection rows and columns. A greedy bi-partite. TODO(rathodv): Add num_valid_columns options to match only that many columns with all the rows. Args: similarity_matrix: Float tensor of shape [N, M] with pairwise similarity where higher values mean more similar. valid_rows: A boolean tensor of shape [N] indicating the rows that are valid. Returns: match_results: int32 tensor of shape [M] with match_results[i]=-1 meaning that column i is not matched and otherwise that it is matched to row match_results[i]. """ valid_row_sim_matrix = tf.gather(similarity_matrix, tf.squeeze(tf.where(valid_rows), axis=-1)) invalid_row_sim_matrix = tf.gather( similarity_matrix, tf.squeeze(tf.where(tf.logical_not(valid_rows)), axis=-1)) similarity_matrix = tf.concat( [valid_row_sim_matrix, invalid_row_sim_matrix], axis=0) # Convert similarity matrix to distance matrix as tf.image.bipartite tries # to find minimum distance matches. distance_matrix = -1 * similarity_matrix num_valid_rows = tf.reduce_sum(tf.to_float(valid_rows)) _, match_results = image_ops.bipartite_match( distance_matrix, num_valid_rows=num_valid_rows) match_results = tf.reshape(match_results, [-1]) match_results = tf.cast(match_results, tf.int32) return match_results
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/matchers/bipartite_matcher.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Argmax matcher implementation. This class takes a similarity matrix and matches columns to rows based on the maximum value per column. One can specify matched_thresholds and to prevent columns from matching to rows (generally resulting in a negative training example) and unmatched_theshold to ignore the match (generally resulting in neither a positive or negative training example). This matcher is used in Fast(er)-RCNN. Note: matchers are used in TargetAssigners. There is a create_target_assigner factory function for popular implementations. """ import tensorflow as tf from object_detection.core import matcher from object_detection.utils import shape_utils class ArgMaxMatcher(matcher.Matcher): """Matcher based on highest value. This class computes matches from a similarity matrix. Each column is matched to a single row. To support object detection target assignment this class enables setting both matched_threshold (upper threshold) and unmatched_threshold (lower thresholds) defining three categories of similarity which define whether examples are positive, negative, or ignored: (1) similarity >= matched_threshold: Highest similarity. Matched/Positive! (2) matched_threshold > similarity >= unmatched_threshold: Medium similarity. Depending on negatives_lower_than_unmatched, this is either Unmatched/Negative OR Ignore. (3) unmatched_threshold > similarity: Lowest similarity. Depending on flag negatives_lower_than_unmatched, either Unmatched/Negative OR Ignore. For ignored matches this class sets the values in the Match object to -2. """ def __init__(self, matched_threshold, unmatched_threshold=None, negatives_lower_than_unmatched=True, force_match_for_each_row=False, use_matmul_gather=False): """Construct ArgMaxMatcher. Args: matched_threshold: Threshold for positive matches. Positive if sim >= matched_threshold, where sim is the maximum value of the similarity matrix for a given column. Set to None for no threshold. unmatched_threshold: Threshold for negative matches. Negative if sim < unmatched_threshold. Defaults to matched_threshold when set to None. negatives_lower_than_unmatched: Boolean which defaults to True. If True then negative matches are the ones below the unmatched_threshold, whereas ignored matches are in between the matched and umatched threshold. If False, then negative matches are in between the matched and unmatched threshold, and everything lower than unmatched is ignored. force_match_for_each_row: If True, ensures that each row is matched to at least one column (which is not guaranteed otherwise if the matched_threshold is high). Defaults to False. See argmax_matcher_test.testMatcherForceMatch() for an example. use_matmul_gather: Force constructed match objects to use matrix multiplication based gather instead of standard tf.gather. (Default: False). Raises: ValueError: if unmatched_threshold is set but matched_threshold is not set or if unmatched_threshold > matched_threshold. """ super(ArgMaxMatcher, self).__init__(use_matmul_gather=use_matmul_gather) if (matched_threshold is None) and (unmatched_threshold is not None): raise ValueError('Need to also define matched_threshold when' 'unmatched_threshold is defined') self._matched_threshold = matched_threshold if unmatched_threshold is None: self._unmatched_threshold = matched_threshold else: if unmatched_threshold > matched_threshold: raise ValueError('unmatched_threshold needs to be smaller or equal' 'to matched_threshold') self._unmatched_threshold = unmatched_threshold if not negatives_lower_than_unmatched: if self._unmatched_threshold == self._matched_threshold: raise ValueError('When negatives are in between matched and ' 'unmatched thresholds, these cannot be of equal ' 'value. matched: {}, unmatched: {}'.format( self._matched_threshold, self._unmatched_threshold)) self._force_match_for_each_row = force_match_for_each_row self._negatives_lower_than_unmatched = negatives_lower_than_unmatched def _match(self, similarity_matrix, valid_rows): """Tries to match each column of the similarity matrix to a row. Args: similarity_matrix: tensor of shape [N, M] representing any similarity metric. valid_rows: a boolean tensor of shape [N] indicating valid rows. Returns: Match object with corresponding matches for each of M columns. """ def _match_when_rows_are_empty(): """Performs matching when the rows of similarity matrix are empty. When the rows are empty, all detections are false positives. So we return a tensor of -1's to indicate that the columns do not match to any rows. Returns: matches: int32 tensor indicating the row each column matches to. """ similarity_matrix_shape = shape_utils.combined_static_and_dynamic_shape( similarity_matrix) return -1 * tf.ones([similarity_matrix_shape[1]], dtype=tf.int32) def _match_when_rows_are_non_empty(): """Performs matching when the rows of similarity matrix are non empty. Returns: matches: int32 tensor indicating the row each column matches to. """ # Matches for each column matches = tf.argmax(similarity_matrix, 0, output_type=tf.int32) # Deal with matched and unmatched threshold if self._matched_threshold is not None: # Get logical indices of ignored and unmatched columns as tf.int64 matched_vals = tf.reduce_max(similarity_matrix, 0) below_unmatched_threshold = tf.greater(self._unmatched_threshold, matched_vals) between_thresholds = tf.logical_and( tf.greater_equal(matched_vals, self._unmatched_threshold), tf.greater(self._matched_threshold, matched_vals)) if self._negatives_lower_than_unmatched: matches = self._set_values_using_indicator(matches, below_unmatched_threshold, -1) matches = self._set_values_using_indicator(matches, between_thresholds, -2) else: matches = self._set_values_using_indicator(matches, below_unmatched_threshold, -2) matches = self._set_values_using_indicator(matches, between_thresholds, -1) if self._force_match_for_each_row: similarity_matrix_shape = shape_utils.combined_static_and_dynamic_shape( similarity_matrix) force_match_column_ids = tf.argmax(similarity_matrix, 1, output_type=tf.int32) force_match_column_indicators = ( tf.one_hot( force_match_column_ids, depth=similarity_matrix_shape[1]) * tf.cast(tf.expand_dims(valid_rows, axis=-1), dtype=tf.float32)) force_match_row_ids = tf.argmax(force_match_column_indicators, 0, output_type=tf.int32) force_match_column_mask = tf.cast( tf.reduce_max(force_match_column_indicators, 0), tf.bool) final_matches = tf.where(force_match_column_mask, force_match_row_ids, matches) return final_matches else: return matches if similarity_matrix.shape.is_fully_defined(): if similarity_matrix.shape[0].value == 0: return _match_when_rows_are_empty() else: return _match_when_rows_are_non_empty() else: return tf.cond( tf.greater(tf.shape(similarity_matrix)[0], 0), _match_when_rows_are_non_empty, _match_when_rows_are_empty) def _set_values_using_indicator(self, x, indicator, val): """Set the indicated fields of x to val. Args: x: tensor. indicator: boolean with same shape as x. val: scalar with value to set. Returns: modified tensor. """ indicator = tf.cast(indicator, x.dtype) return tf.add(tf.multiply(x, 1 - indicator), val * indicator)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/matchers/argmax_matcher.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Faster RCNN box coder. Faster RCNN box coder follows the coding schema described below: ty = (y - ya) / ha tx = (x - xa) / wa th = log(h / ha) tw = log(w / wa) where x, y, w, h denote the box's center coordinates, width and height respectively. Similarly, xa, ya, wa, ha denote the anchor's center coordinates, width and height. tx, ty, tw and th denote the anchor-encoded center, width and height respectively. See http://arxiv.org/abs/1506.01497 for details. """ import tensorflow as tf from object_detection.core import box_coder from object_detection.core import box_list EPSILON = 1e-8 class FasterRcnnBoxCoder(box_coder.BoxCoder): """Faster RCNN box coder.""" def __init__(self, scale_factors=None): """Constructor for FasterRcnnBoxCoder. Args: scale_factors: List of 4 positive scalars to scale ty, tx, th and tw. If set to None, does not perform scaling. For Faster RCNN, the open-source implementation recommends using [10.0, 10.0, 5.0, 5.0]. """ if scale_factors: assert len(scale_factors) == 4 for scalar in scale_factors: assert scalar > 0 self._scale_factors = scale_factors @property def code_size(self): return 4 def _encode(self, boxes, anchors): """Encode a box collection with respect to anchor collection. Args: boxes: BoxList holding N boxes to be encoded. anchors: BoxList of anchors. Returns: a tensor representing N anchor-encoded boxes of the format [ty, tx, th, tw]. """ # Convert anchors to the center coordinate representation. ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes() ycenter, xcenter, h, w = boxes.get_center_coordinates_and_sizes() # Avoid NaN in division and log below. ha += EPSILON wa += EPSILON h += EPSILON w += EPSILON tx = (xcenter - xcenter_a) / wa ty = (ycenter - ycenter_a) / ha tw = tf.log(w / wa) th = tf.log(h / ha) # Scales location targets as used in paper for joint training. if self._scale_factors: ty *= self._scale_factors[0] tx *= self._scale_factors[1] th *= self._scale_factors[2] tw *= self._scale_factors[3] return tf.transpose(tf.stack([ty, tx, th, tw])) def _decode(self, rel_codes, anchors): """Decode relative codes to boxes. Args: rel_codes: a tensor representing N anchor-encoded boxes. anchors: BoxList of anchors. Returns: boxes: BoxList holding N bounding boxes. """ ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes() ty, tx, th, tw = tf.unstack(tf.transpose(rel_codes)) if self._scale_factors: ty /= self._scale_factors[0] tx /= self._scale_factors[1] th /= self._scale_factors[2] tw /= self._scale_factors[3] w = tf.exp(tw) * wa h = tf.exp(th) * ha ycenter = ty * ha + ycenter_a xcenter = tx * wa + xcenter_a ymin = ycenter - h / 2. xmin = xcenter - w / 2. ymax = ycenter + h / 2. xmax = xcenter + w / 2. return box_list.BoxList(tf.transpose(tf.stack([ymin, xmin, ymax, xmax])))
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/faster_rcnn_box_coder.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.box_coder.keypoint_box_coder.""" import tensorflow as tf from object_detection.box_coders import keypoint_box_coder from object_detection.core import box_list from object_detection.core import standard_fields as fields class KeypointBoxCoderTest(tf.test.TestCase): def test_get_correct_relative_codes_after_encoding(self): boxes = [[10., 10., 20., 15.], [0.2, 0.1, 0.5, 0.4]] keypoints = [[[15., 12.], [10., 15.]], [[0.5, 0.3], [0.2, 0.4]]] num_keypoints = len(keypoints[0]) anchors = [[15., 12., 30., 18.], [0.1, 0.0, 0.7, 0.9]] expected_rel_codes = [ [-0.5, -0.416666, -0.405465, -0.182321, -0.5, -0.5, -0.833333, 0.], [-0.083333, -0.222222, -0.693147, -1.098612, 0.166667, -0.166667, -0.333333, -0.055556] ] boxes = box_list.BoxList(tf.constant(boxes)) boxes.add_field(fields.BoxListFields.keypoints, tf.constant(keypoints)) anchors = box_list.BoxList(tf.constant(anchors)) coder = keypoint_box_coder.KeypointBoxCoder(num_keypoints) rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: rel_codes_out, = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) def test_get_correct_relative_codes_after_encoding_with_scaling(self): boxes = [[10., 10., 20., 15.], [0.2, 0.1, 0.5, 0.4]] keypoints = [[[15., 12.], [10., 15.]], [[0.5, 0.3], [0.2, 0.4]]] num_keypoints = len(keypoints[0]) anchors = [[15., 12., 30., 18.], [0.1, 0.0, 0.7, 0.9]] scale_factors = [2, 3, 4, 5] expected_rel_codes = [ [-1., -1.25, -1.62186, -0.911608, -1.0, -1.5, -1.666667, 0.], [-0.166667, -0.666667, -2.772588, -5.493062, 0.333333, -0.5, -0.666667, -0.166667] ] boxes = box_list.BoxList(tf.constant(boxes)) boxes.add_field(fields.BoxListFields.keypoints, tf.constant(keypoints)) anchors = box_list.BoxList(tf.constant(anchors)) coder = keypoint_box_coder.KeypointBoxCoder( num_keypoints, scale_factors=scale_factors) rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: rel_codes_out, = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) def test_get_correct_boxes_after_decoding(self): anchors = [[15., 12., 30., 18.], [0.1, 0.0, 0.7, 0.9]] rel_codes = [ [-0.5, -0.416666, -0.405465, -0.182321, -0.5, -0.5, -0.833333, 0.], [-0.083333, -0.222222, -0.693147, -1.098612, 0.166667, -0.166667, -0.333333, -0.055556] ] expected_boxes = [[10., 10., 20., 15.], [0.2, 0.1, 0.5, 0.4]] expected_keypoints = [[[15., 12.], [10., 15.]], [[0.5, 0.3], [0.2, 0.4]]] num_keypoints = len(expected_keypoints[0]) anchors = box_list.BoxList(tf.constant(anchors)) coder = keypoint_box_coder.KeypointBoxCoder(num_keypoints) boxes = coder.decode(rel_codes, anchors) with self.test_session() as sess: boxes_out, keypoints_out = sess.run( [boxes.get(), boxes.get_field(fields.BoxListFields.keypoints)]) self.assertAllClose(boxes_out, expected_boxes) self.assertAllClose(keypoints_out, expected_keypoints) def test_get_correct_boxes_after_decoding_with_scaling(self): anchors = [[15., 12., 30., 18.], [0.1, 0.0, 0.7, 0.9]] rel_codes = [ [-1., -1.25, -1.62186, -0.911608, -1.0, -1.5, -1.666667, 0.], [-0.166667, -0.666667, -2.772588, -5.493062, 0.333333, -0.5, -0.666667, -0.166667] ] scale_factors = [2, 3, 4, 5] expected_boxes = [[10., 10., 20., 15.], [0.2, 0.1, 0.5, 0.4]] expected_keypoints = [[[15., 12.], [10., 15.]], [[0.5, 0.3], [0.2, 0.4]]] num_keypoints = len(expected_keypoints[0]) anchors = box_list.BoxList(tf.constant(anchors)) coder = keypoint_box_coder.KeypointBoxCoder( num_keypoints, scale_factors=scale_factors) boxes = coder.decode(rel_codes, anchors) with self.test_session() as sess: boxes_out, keypoints_out = sess.run( [boxes.get(), boxes.get_field(fields.BoxListFields.keypoints)]) self.assertAllClose(boxes_out, expected_boxes) self.assertAllClose(keypoints_out, expected_keypoints) def test_very_small_width_nan_after_encoding(self): boxes = [[10., 10., 10.0000001, 20.]] keypoints = [[[10., 10.], [10.0000001, 20.]]] anchors = [[15., 12., 30., 18.]] expected_rel_codes = [[-0.833333, 0., -21.128731, 0.510826, -0.833333, -0.833333, -0.833333, 0.833333]] boxes = box_list.BoxList(tf.constant(boxes)) boxes.add_field(fields.BoxListFields.keypoints, tf.constant(keypoints)) anchors = box_list.BoxList(tf.constant(anchors)) coder = keypoint_box_coder.KeypointBoxCoder(2) rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: rel_codes_out, = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/keypoint_box_coder_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Square box coder. Square box coder follows the coding schema described below: l = sqrt(h * w) la = sqrt(ha * wa) ty = (y - ya) / la tx = (x - xa) / la tl = log(l / la) where x, y, w, h denote the box's center coordinates, width, and height, respectively. Similarly, xa, ya, wa, ha denote the anchor's center coordinates, width and height. tx, ty, tl denote the anchor-encoded center, and length, respectively. Because the encoded box is a square, only one length is encoded. This has shown to provide performance improvements over the Faster RCNN box coder when the objects being detected tend to be square (e.g. faces) and when the input images are not distorted via resizing. """ import tensorflow as tf from object_detection.core import box_coder from object_detection.core import box_list EPSILON = 1e-8 class SquareBoxCoder(box_coder.BoxCoder): """Encodes a 3-scalar representation of a square box.""" def __init__(self, scale_factors=None): """Constructor for SquareBoxCoder. Args: scale_factors: List of 3 positive scalars to scale ty, tx, and tl. If set to None, does not perform scaling. For faster RCNN, the open-source implementation recommends using [10.0, 10.0, 5.0]. Raises: ValueError: If scale_factors is not length 3 or contains values less than or equal to 0. """ if scale_factors: if len(scale_factors) != 3: raise ValueError('The argument scale_factors must be a list of length ' '3.') if any(scalar <= 0 for scalar in scale_factors): raise ValueError('The values in scale_factors must all be greater ' 'than 0.') self._scale_factors = scale_factors @property def code_size(self): return 3 def _encode(self, boxes, anchors): """Encodes a box collection with respect to an anchor collection. Args: boxes: BoxList holding N boxes to be encoded. anchors: BoxList of anchors. Returns: a tensor representing N anchor-encoded boxes of the format [ty, tx, tl]. """ # Convert anchors to the center coordinate representation. ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes() la = tf.sqrt(ha * wa) ycenter, xcenter, h, w = boxes.get_center_coordinates_and_sizes() l = tf.sqrt(h * w) # Avoid NaN in division and log below. la += EPSILON l += EPSILON tx = (xcenter - xcenter_a) / la ty = (ycenter - ycenter_a) / la tl = tf.log(l / la) # Scales location targets for joint training. if self._scale_factors: ty *= self._scale_factors[0] tx *= self._scale_factors[1] tl *= self._scale_factors[2] return tf.transpose(tf.stack([ty, tx, tl])) def _decode(self, rel_codes, anchors): """Decodes relative codes to boxes. Args: rel_codes: a tensor representing N anchor-encoded boxes. anchors: BoxList of anchors. Returns: boxes: BoxList holding N bounding boxes. """ ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes() la = tf.sqrt(ha * wa) ty, tx, tl = tf.unstack(tf.transpose(rel_codes)) if self._scale_factors: ty /= self._scale_factors[0] tx /= self._scale_factors[1] tl /= self._scale_factors[2] l = tf.exp(tl) * la ycenter = ty * la + ycenter_a xcenter = tx * la + xcenter_a ymin = ycenter - l / 2. xmin = xcenter - l / 2. ymax = ycenter + l / 2. xmax = xcenter + l / 2. return box_list.BoxList(tf.transpose(tf.stack([ymin, xmin, ymax, xmax])))
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/square_box_coder.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.box_coder.square_box_coder.""" import tensorflow as tf from object_detection.box_coders import square_box_coder from object_detection.core import box_list class SquareBoxCoderTest(tf.test.TestCase): def test_correct_relative_codes_with_default_scale(self): boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]] anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] scale_factors = None expected_rel_codes = [[-0.790569, -0.263523, -0.293893], [-0.068041, -0.272166, -0.89588]] boxes = box_list.BoxList(tf.constant(boxes)) anchors = box_list.BoxList(tf.constant(anchors)) coder = square_box_coder.SquareBoxCoder(scale_factors=scale_factors) rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: (rel_codes_out,) = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) def test_correct_relative_codes_with_non_default_scale(self): boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]] anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] scale_factors = [2, 3, 4] expected_rel_codes = [[-1.581139, -0.790569, -1.175573], [-0.136083, -0.816497, -3.583519]] boxes = box_list.BoxList(tf.constant(boxes)) anchors = box_list.BoxList(tf.constant(anchors)) coder = square_box_coder.SquareBoxCoder(scale_factors=scale_factors) rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: (rel_codes_out,) = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) def test_correct_relative_codes_with_small_width(self): boxes = [[10.0, 10.0, 10.0000001, 20.0]] anchors = [[15.0, 12.0, 30.0, 18.0]] scale_factors = None expected_rel_codes = [[-1.317616, 0., -20.670586]] boxes = box_list.BoxList(tf.constant(boxes)) anchors = box_list.BoxList(tf.constant(anchors)) coder = square_box_coder.SquareBoxCoder(scale_factors=scale_factors) rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: (rel_codes_out,) = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) def test_correct_boxes_with_default_scale(self): anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] rel_codes = [[-0.5, -0.416666, -0.405465], [-0.083333, -0.222222, -0.693147]] scale_factors = None expected_boxes = [[14.594306, 7.884875, 20.918861, 14.209432], [0.155051, 0.102989, 0.522474, 0.470412]] anchors = box_list.BoxList(tf.constant(anchors)) coder = square_box_coder.SquareBoxCoder(scale_factors=scale_factors) boxes = coder.decode(rel_codes, anchors) with self.test_session() as sess: (boxes_out,) = sess.run([boxes.get()]) self.assertAllClose(boxes_out, expected_boxes) def test_correct_boxes_with_non_default_scale(self): anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] rel_codes = [[-1., -1.25, -1.62186], [-0.166667, -0.666667, -2.772588]] scale_factors = [2, 3, 4] expected_boxes = [[14.594306, 7.884875, 20.918861, 14.209432], [0.155051, 0.102989, 0.522474, 0.470412]] anchors = box_list.BoxList(tf.constant(anchors)) coder = square_box_coder.SquareBoxCoder(scale_factors=scale_factors) boxes = coder.decode(rel_codes, anchors) with self.test_session() as sess: (boxes_out,) = sess.run([boxes.get()]) self.assertAllClose(boxes_out, expected_boxes) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/square_box_coder_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keypoint box coder. The keypoint box coder follows the coding schema described below (this is similar to the FasterRcnnBoxCoder, except that it encodes keypoints in addition to box coordinates): ty = (y - ya) / ha tx = (x - xa) / wa th = log(h / ha) tw = log(w / wa) tky0 = (ky0 - ya) / ha tkx0 = (kx0 - xa) / wa tky1 = (ky1 - ya) / ha tkx1 = (kx1 - xa) / wa ... where x, y, w, h denote the box's center coordinates, width and height respectively. Similarly, xa, ya, wa, ha denote the anchor's center coordinates, width and height. tx, ty, tw and th denote the anchor-encoded center, width and height respectively. ky0, kx0, ky1, kx1, ... denote the keypoints' coordinates, and tky0, tkx0, tky1, tkx1, ... denote the anchor-encoded keypoint coordinates. """ import tensorflow as tf from object_detection.core import box_coder from object_detection.core import box_list from object_detection.core import standard_fields as fields EPSILON = 1e-8 class KeypointBoxCoder(box_coder.BoxCoder): """Keypoint box coder.""" def __init__(self, num_keypoints, scale_factors=None): """Constructor for KeypointBoxCoder. Args: num_keypoints: Number of keypoints to encode/decode. scale_factors: List of 4 positive scalars to scale ty, tx, th and tw. In addition to scaling ty and tx, the first 2 scalars are used to scale the y and x coordinates of the keypoints as well. If set to None, does not perform scaling. """ self._num_keypoints = num_keypoints if scale_factors: assert len(scale_factors) == 4 for scalar in scale_factors: assert scalar > 0 self._scale_factors = scale_factors self._keypoint_scale_factors = None if scale_factors is not None: self._keypoint_scale_factors = tf.expand_dims(tf.tile( [tf.to_float(scale_factors[0]), tf.to_float(scale_factors[1])], [num_keypoints]), 1) @property def code_size(self): return 4 + self._num_keypoints * 2 def _encode(self, boxes, anchors): """Encode a box and keypoint collection with respect to anchor collection. Args: boxes: BoxList holding N boxes and keypoints to be encoded. Boxes are tensors with the shape [N, 4], and keypoints are tensors with the shape [N, num_keypoints, 2]. anchors: BoxList of anchors. Returns: a tensor representing N anchor-encoded boxes of the format [ty, tx, th, tw, tky0, tkx0, tky1, tkx1, ...] where tky0 and tkx0 represent the y and x coordinates of the first keypoint, tky1 and tkx1 represent the y and x coordinates of the second keypoint, and so on. """ # Convert anchors to the center coordinate representation. ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes() ycenter, xcenter, h, w = boxes.get_center_coordinates_and_sizes() keypoints = boxes.get_field(fields.BoxListFields.keypoints) keypoints = tf.transpose(tf.reshape(keypoints, [-1, self._num_keypoints * 2])) num_boxes = boxes.num_boxes() # Avoid NaN in division and log below. ha += EPSILON wa += EPSILON h += EPSILON w += EPSILON tx = (xcenter - xcenter_a) / wa ty = (ycenter - ycenter_a) / ha tw = tf.log(w / wa) th = tf.log(h / ha) tiled_anchor_centers = tf.tile( tf.stack([ycenter_a, xcenter_a]), [self._num_keypoints, 1]) tiled_anchor_sizes = tf.tile( tf.stack([ha, wa]), [self._num_keypoints, 1]) tkeypoints = (keypoints - tiled_anchor_centers) / tiled_anchor_sizes # Scales location targets as used in paper for joint training. if self._scale_factors: ty *= self._scale_factors[0] tx *= self._scale_factors[1] th *= self._scale_factors[2] tw *= self._scale_factors[3] tkeypoints *= tf.tile(self._keypoint_scale_factors, [1, num_boxes]) tboxes = tf.stack([ty, tx, th, tw]) return tf.transpose(tf.concat([tboxes, tkeypoints], 0)) def _decode(self, rel_codes, anchors): """Decode relative codes to boxes and keypoints. Args: rel_codes: a tensor with shape [N, 4 + 2 * num_keypoints] representing N anchor-encoded boxes and keypoints anchors: BoxList of anchors. Returns: boxes: BoxList holding N bounding boxes and keypoints. """ ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes() num_codes = tf.shape(rel_codes)[0] result = tf.unstack(tf.transpose(rel_codes)) ty, tx, th, tw = result[:4] tkeypoints = result[4:] if self._scale_factors: ty /= self._scale_factors[0] tx /= self._scale_factors[1] th /= self._scale_factors[2] tw /= self._scale_factors[3] tkeypoints /= tf.tile(self._keypoint_scale_factors, [1, num_codes]) w = tf.exp(tw) * wa h = tf.exp(th) * ha ycenter = ty * ha + ycenter_a xcenter = tx * wa + xcenter_a ymin = ycenter - h / 2. xmin = xcenter - w / 2. ymax = ycenter + h / 2. xmax = xcenter + w / 2. decoded_boxes_keypoints = box_list.BoxList( tf.transpose(tf.stack([ymin, xmin, ymax, xmax]))) tiled_anchor_centers = tf.tile( tf.stack([ycenter_a, xcenter_a]), [self._num_keypoints, 1]) tiled_anchor_sizes = tf.tile( tf.stack([ha, wa]), [self._num_keypoints, 1]) keypoints = tkeypoints * tiled_anchor_sizes + tiled_anchor_centers keypoints = tf.reshape(tf.transpose(keypoints), [-1, self._num_keypoints, 2]) decoded_boxes_keypoints.add_field(fields.BoxListFields.keypoints, keypoints) return decoded_boxes_keypoints
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/keypoint_box_coder.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.box_coder.faster_rcnn_box_coder.""" import tensorflow as tf from object_detection.box_coders import faster_rcnn_box_coder from object_detection.core import box_list class FasterRcnnBoxCoderTest(tf.test.TestCase): def test_get_correct_relative_codes_after_encoding(self): boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]] anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] expected_rel_codes = [[-0.5, -0.416666, -0.405465, -0.182321], [-0.083333, -0.222222, -0.693147, -1.098612]] boxes = box_list.BoxList(tf.constant(boxes)) anchors = box_list.BoxList(tf.constant(anchors)) coder = faster_rcnn_box_coder.FasterRcnnBoxCoder() rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: rel_codes_out, = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) def test_get_correct_relative_codes_after_encoding_with_scaling(self): boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]] anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] scale_factors = [2, 3, 4, 5] expected_rel_codes = [[-1., -1.25, -1.62186, -0.911608], [-0.166667, -0.666667, -2.772588, -5.493062]] boxes = box_list.BoxList(tf.constant(boxes)) anchors = box_list.BoxList(tf.constant(anchors)) coder = faster_rcnn_box_coder.FasterRcnnBoxCoder( scale_factors=scale_factors) rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: rel_codes_out, = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) def test_get_correct_boxes_after_decoding(self): anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] rel_codes = [[-0.5, -0.416666, -0.405465, -0.182321], [-0.083333, -0.222222, -0.693147, -1.098612]] expected_boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]] anchors = box_list.BoxList(tf.constant(anchors)) coder = faster_rcnn_box_coder.FasterRcnnBoxCoder() boxes = coder.decode(rel_codes, anchors) with self.test_session() as sess: boxes_out, = sess.run([boxes.get()]) self.assertAllClose(boxes_out, expected_boxes) def test_get_correct_boxes_after_decoding_with_scaling(self): anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] rel_codes = [[-1., -1.25, -1.62186, -0.911608], [-0.166667, -0.666667, -2.772588, -5.493062]] scale_factors = [2, 3, 4, 5] expected_boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]] anchors = box_list.BoxList(tf.constant(anchors)) coder = faster_rcnn_box_coder.FasterRcnnBoxCoder( scale_factors=scale_factors) boxes = coder.decode(rel_codes, anchors) with self.test_session() as sess: boxes_out, = sess.run([boxes.get()]) self.assertAllClose(boxes_out, expected_boxes) def test_very_small_Width_nan_after_encoding(self): boxes = [[10.0, 10.0, 10.0000001, 20.0]] anchors = [[15.0, 12.0, 30.0, 18.0]] expected_rel_codes = [[-0.833333, 0., -21.128731, 0.510826]] boxes = box_list.BoxList(tf.constant(boxes)) anchors = box_list.BoxList(tf.constant(anchors)) coder = faster_rcnn_box_coder.FasterRcnnBoxCoder() rel_codes = coder.encode(boxes, anchors) with self.test_session() as sess: rel_codes_out, = sess.run([rel_codes]) self.assertAllClose(rel_codes_out, expected_rel_codes) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/faster_rcnn_box_coder_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Mean stddev box coder. This box coder use the following coding schema to encode boxes: rel_code = (box_corner - anchor_corner_mean) / anchor_corner_stddev. """ from object_detection.core import box_coder from object_detection.core import box_list class MeanStddevBoxCoder(box_coder.BoxCoder): """Mean stddev box coder.""" def __init__(self, stddev=0.01): """Constructor for MeanStddevBoxCoder. Args: stddev: The standard deviation used to encode and decode boxes. """ self._stddev = stddev @property def code_size(self): return 4 def _encode(self, boxes, anchors): """Encode a box collection with respect to anchor collection. Args: boxes: BoxList holding N boxes to be encoded. anchors: BoxList of N anchors. Returns: a tensor representing N anchor-encoded boxes Raises: ValueError: if the anchors still have deprecated stddev field. """ box_corners = boxes.get() if anchors.has_field('stddev'): raise ValueError("'stddev' is a parameter of MeanStddevBoxCoder and " "should not be specified in the box list.") means = anchors.get() return (box_corners - means) / self._stddev def _decode(self, rel_codes, anchors): """Decode. Args: rel_codes: a tensor representing N anchor-encoded boxes. anchors: BoxList of anchors. Returns: boxes: BoxList holding N bounding boxes Raises: ValueError: if the anchors still have deprecated stddev field and expects the decode method to use stddev value from that field. """ means = anchors.get() if anchors.has_field('stddev'): raise ValueError("'stddev' is a parameter of MeanStddevBoxCoder and " "should not be specified in the box list.") box_corners = rel_codes * self._stddev + means return box_list.BoxList(box_corners)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/mean_stddev_box_coder.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.box_coder.mean_stddev_boxcoder.""" import tensorflow as tf from object_detection.box_coders import mean_stddev_box_coder from object_detection.core import box_list class MeanStddevBoxCoderTest(tf.test.TestCase): def testGetCorrectRelativeCodesAfterEncoding(self): box_corners = [[0.0, 0.0, 0.5, 0.5], [0.0, 0.0, 0.5, 0.5]] boxes = box_list.BoxList(tf.constant(box_corners)) expected_rel_codes = [[0.0, 0.0, 0.0, 0.0], [-5.0, -5.0, -5.0, -3.0]] prior_means = tf.constant([[0.0, 0.0, 0.5, 0.5], [0.5, 0.5, 1.0, 0.8]]) priors = box_list.BoxList(prior_means) coder = mean_stddev_box_coder.MeanStddevBoxCoder(stddev=0.1) rel_codes = coder.encode(boxes, priors) with self.test_session() as sess: rel_codes_out = sess.run(rel_codes) self.assertAllClose(rel_codes_out, expected_rel_codes) def testGetCorrectBoxesAfterDecoding(self): rel_codes = tf.constant([[0.0, 0.0, 0.0, 0.0], [-5.0, -5.0, -5.0, -3.0]]) expected_box_corners = [[0.0, 0.0, 0.5, 0.5], [0.0, 0.0, 0.5, 0.5]] prior_means = tf.constant([[0.0, 0.0, 0.5, 0.5], [0.5, 0.5, 1.0, 0.8]]) priors = box_list.BoxList(prior_means) coder = mean_stddev_box_coder.MeanStddevBoxCoder(stddev=0.1) decoded_boxes = coder.decode(rel_codes, priors) decoded_box_corners = decoded_boxes.get() with self.test_session() as sess: decoded_out = sess.run(decoded_box_corners) self.assertAllClose(decoded_out, expected_box_corners) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/object_detection/box_coders/mean_stddev_box_coder_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Downloads and converts a particular dataset. Usage: ```shell $ python download_and_convert_data.py \ --dataset_name=mnist \ --dataset_dir=/tmp/mnist $ python download_and_convert_data.py \ --dataset_name=cifar10 \ --dataset_dir=/tmp/cifar10 $ python download_and_convert_data.py \ --dataset_name=flowers \ --dataset_dir=/tmp/flowers ``` """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from datasets import download_and_convert_cifar10 from datasets import download_and_convert_flowers from datasets import download_and_convert_mnist FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string( 'dataset_name', None, 'The name of the dataset to convert, one of "cifar10", "flowers", "mnist".') tf.app.flags.DEFINE_string( 'dataset_dir', None, 'The directory where the output TFRecords and temporary files are saved.') def main(_): if not FLAGS.dataset_name: raise ValueError('You must supply the dataset name with --dataset_name') if not FLAGS.dataset_dir: raise ValueError('You must supply the dataset directory with --dataset_dir') if FLAGS.dataset_name == 'cifar10': download_and_convert_cifar10.run(FLAGS.dataset_dir) elif FLAGS.dataset_name == 'flowers': download_and_convert_flowers.run(FLAGS.dataset_dir) elif FLAGS.dataset_name == 'mnist': download_and_convert_mnist.run(FLAGS.dataset_dir) else: raise ValueError( 'dataset_name [%s] was not recognized.' % FLAGS.dataset_name) if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/download_and_convert_data.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Generic training script that trains a model using a given dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from datasets import dataset_factory from deployment import model_deploy from nets import nets_factory from preprocessing import preprocessing_factory slim = tf.contrib.slim tf.app.flags.DEFINE_string( 'master', '', 'The address of the TensorFlow master to use.') tf.app.flags.DEFINE_string( 'train_dir', '/tmp/tfmodel/', 'Directory where checkpoints and event logs are written to.') tf.app.flags.DEFINE_integer('num_clones', 1, 'Number of model clones to deploy. Note For ' 'historical reasons loss from all clones averaged ' 'out and learning rate decay happen per clone ' 'epochs') tf.app.flags.DEFINE_boolean('clone_on_cpu', False, 'Use CPUs to deploy clones.') tf.app.flags.DEFINE_integer('worker_replicas', 1, 'Number of worker replicas.') tf.app.flags.DEFINE_integer( 'num_ps_tasks', 0, 'The number of parameter servers. If the value is 0, then the parameters ' 'are handled locally by the worker.') tf.app.flags.DEFINE_integer( 'num_readers', 4, 'The number of parallel readers that read data from the dataset.') tf.app.flags.DEFINE_integer( 'num_preprocessing_threads', 4, 'The number of threads used to create the batches.') tf.app.flags.DEFINE_integer( 'log_every_n_steps', 10, 'The frequency with which logs are print.') tf.app.flags.DEFINE_integer( 'save_summaries_secs', 600, 'The frequency with which summaries are saved, in seconds.') tf.app.flags.DEFINE_integer( 'save_interval_secs', 600, 'The frequency with which the model is saved, in seconds.') tf.app.flags.DEFINE_integer( 'task', 0, 'Task id of the replica running the training.') ###################### # Optimization Flags # ###################### tf.app.flags.DEFINE_float( 'weight_decay', 0.00004, 'The weight decay on the model weights.') tf.app.flags.DEFINE_string( 'optimizer', 'rmsprop', 'The name of the optimizer, one of "adadelta", "adagrad", "adam",' '"ftrl", "momentum", "sgd" or "rmsprop".') tf.app.flags.DEFINE_float( 'adadelta_rho', 0.95, 'The decay rate for adadelta.') tf.app.flags.DEFINE_float( 'adagrad_initial_accumulator_value', 0.1, 'Starting value for the AdaGrad accumulators.') tf.app.flags.DEFINE_float( 'adam_beta1', 0.9, 'The exponential decay rate for the 1st moment estimates.') tf.app.flags.DEFINE_float( 'adam_beta2', 0.999, 'The exponential decay rate for the 2nd moment estimates.') tf.app.flags.DEFINE_float('opt_epsilon', 1.0, 'Epsilon term for the optimizer.') tf.app.flags.DEFINE_float('ftrl_learning_rate_power', -0.5, 'The learning rate power.') tf.app.flags.DEFINE_float( 'ftrl_initial_accumulator_value', 0.1, 'Starting value for the FTRL accumulators.') tf.app.flags.DEFINE_float( 'ftrl_l1', 0.0, 'The FTRL l1 regularization strength.') tf.app.flags.DEFINE_float( 'ftrl_l2', 0.0, 'The FTRL l2 regularization strength.') tf.app.flags.DEFINE_float( 'momentum', 0.9, 'The momentum for the MomentumOptimizer and RMSPropOptimizer.') tf.app.flags.DEFINE_float('rmsprop_momentum', 0.9, 'Momentum.') tf.app.flags.DEFINE_float('rmsprop_decay', 0.9, 'Decay term for RMSProp.') tf.app.flags.DEFINE_integer( 'quantize_delay', -1, 'Number of steps to start quantized training. Set to -1 would disable ' 'quantized training.') ####################### # Learning Rate Flags # ####################### tf.app.flags.DEFINE_string( 'learning_rate_decay_type', 'exponential', 'Specifies how the learning rate is decayed. One of "fixed", "exponential",' ' or "polynomial"') tf.app.flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.') tf.app.flags.DEFINE_float( 'end_learning_rate', 0.0001, 'The minimal end learning rate used by a polynomial decay learning rate.') tf.app.flags.DEFINE_float( 'label_smoothing', 0.0, 'The amount of label smoothing.') tf.app.flags.DEFINE_float( 'learning_rate_decay_factor', 0.94, 'Learning rate decay factor.') tf.app.flags.DEFINE_float( 'num_epochs_per_decay', 2.0, 'Number of epochs after which learning rate decays. Note: this flag counts ' 'epochs per clone but aggregates per sync replicas. So 1.0 means that ' 'each clone will go over full epoch individually, but replicas will go ' 'once across all replicas.') tf.app.flags.DEFINE_bool( 'sync_replicas', False, 'Whether or not to synchronize the replicas during training.') tf.app.flags.DEFINE_integer( 'replicas_to_aggregate', 1, 'The Number of gradients to collect before updating params.') tf.app.flags.DEFINE_float( 'moving_average_decay', None, 'The decay to use for the moving average.' 'If left as None, then moving averages are not used.') ####################### # Dataset Flags # ####################### tf.app.flags.DEFINE_string( 'dataset_name', 'imagenet', 'The name of the dataset to load.') tf.app.flags.DEFINE_string( 'dataset_split_name', 'train', 'The name of the train/test split.') tf.app.flags.DEFINE_string( 'dataset_dir', None, 'The directory where the dataset files are stored.') tf.app.flags.DEFINE_integer( 'labels_offset', 0, 'An offset for the labels in the dataset. This flag is primarily used to ' 'evaluate the VGG and ResNet architectures which do not use a background ' 'class for the ImageNet dataset.') tf.app.flags.DEFINE_string( 'model_name', 'inception_v3', 'The name of the architecture to train.') tf.app.flags.DEFINE_string( 'preprocessing_name', None, 'The name of the preprocessing to use. If left ' 'as `None`, then the model_name flag is used.') tf.app.flags.DEFINE_integer( 'batch_size', 32, 'The number of samples in each batch.') tf.app.flags.DEFINE_integer( 'train_image_size', None, 'Train image size') tf.app.flags.DEFINE_integer('max_number_of_steps', None, 'The maximum number of training steps.') ##################### # Fine-Tuning Flags # ##################### tf.app.flags.DEFINE_string( 'checkpoint_path', None, 'The path to a checkpoint from which to fine-tune.') tf.app.flags.DEFINE_string( 'checkpoint_exclude_scopes', None, 'Comma-separated list of scopes of variables to exclude when restoring ' 'from a checkpoint.') tf.app.flags.DEFINE_string( 'trainable_scopes', None, 'Comma-separated list of scopes to filter the set of variables to train.' 'By default, None would train all the variables.') tf.app.flags.DEFINE_boolean( 'ignore_missing_vars', False, 'When restoring a checkpoint would ignore missing variables.') FLAGS = tf.app.flags.FLAGS def _configure_learning_rate(num_samples_per_epoch, global_step): """Configures the learning rate. Args: num_samples_per_epoch: The number of samples in each epoch of training. global_step: The global_step tensor. Returns: A `Tensor` representing the learning rate. Raises: ValueError: if """ # Note: when num_clones is > 1, this will actually have each clone to go # over each epoch FLAGS.num_epochs_per_decay times. This is different # behavior from sync replicas and is expected to produce different results. decay_steps = int(num_samples_per_epoch * FLAGS.num_epochs_per_decay / FLAGS.batch_size) if FLAGS.sync_replicas: decay_steps /= FLAGS.replicas_to_aggregate if FLAGS.learning_rate_decay_type == 'exponential': return tf.train.exponential_decay(FLAGS.learning_rate, global_step, decay_steps, FLAGS.learning_rate_decay_factor, staircase=True, name='exponential_decay_learning_rate') elif FLAGS.learning_rate_decay_type == 'fixed': return tf.constant(FLAGS.learning_rate, name='fixed_learning_rate') elif FLAGS.learning_rate_decay_type == 'polynomial': return tf.train.polynomial_decay(FLAGS.learning_rate, global_step, decay_steps, FLAGS.end_learning_rate, power=1.0, cycle=False, name='polynomial_decay_learning_rate') else: raise ValueError('learning_rate_decay_type [%s] was not recognized' % FLAGS.learning_rate_decay_type) def _configure_optimizer(learning_rate): """Configures the optimizer used for training. Args: learning_rate: A scalar or `Tensor` learning rate. Returns: An instance of an optimizer. Raises: ValueError: if FLAGS.optimizer is not recognized. """ if FLAGS.optimizer == 'adadelta': optimizer = tf.train.AdadeltaOptimizer( learning_rate, rho=FLAGS.adadelta_rho, epsilon=FLAGS.opt_epsilon) elif FLAGS.optimizer == 'adagrad': optimizer = tf.train.AdagradOptimizer( learning_rate, initial_accumulator_value=FLAGS.adagrad_initial_accumulator_value) elif FLAGS.optimizer == 'adam': optimizer = tf.train.AdamOptimizer( learning_rate, beta1=FLAGS.adam_beta1, beta2=FLAGS.adam_beta2, epsilon=FLAGS.opt_epsilon) elif FLAGS.optimizer == 'ftrl': optimizer = tf.train.FtrlOptimizer( learning_rate, learning_rate_power=FLAGS.ftrl_learning_rate_power, initial_accumulator_value=FLAGS.ftrl_initial_accumulator_value, l1_regularization_strength=FLAGS.ftrl_l1, l2_regularization_strength=FLAGS.ftrl_l2) elif FLAGS.optimizer == 'momentum': optimizer = tf.train.MomentumOptimizer( learning_rate, momentum=FLAGS.momentum, name='Momentum') elif FLAGS.optimizer == 'rmsprop': optimizer = tf.train.RMSPropOptimizer( learning_rate, decay=FLAGS.rmsprop_decay, momentum=FLAGS.rmsprop_momentum, epsilon=FLAGS.opt_epsilon) elif FLAGS.optimizer == 'sgd': optimizer = tf.train.GradientDescentOptimizer(learning_rate) else: raise ValueError('Optimizer [%s] was not recognized' % FLAGS.optimizer) return optimizer def _get_init_fn(): """Returns a function run by the chief worker to warm-start the training. Note that the init_fn is only run when initializing the model during the very first global step. Returns: An init function run by the supervisor. """ if FLAGS.checkpoint_path is None: return None # Warn the user if a checkpoint exists in the train_dir. Then we'll be # ignoring the checkpoint anyway. if tf.train.latest_checkpoint(FLAGS.train_dir): tf.logging.info( 'Ignoring --checkpoint_path because a checkpoint already exists in %s' % FLAGS.train_dir) return None exclusions = [] if FLAGS.checkpoint_exclude_scopes: exclusions = [scope.strip() for scope in FLAGS.checkpoint_exclude_scopes.split(',')] # TODO(sguada) variables.filter_variables() variables_to_restore = [] for var in slim.get_model_variables(): for exclusion in exclusions: if var.op.name.startswith(exclusion): break else: variables_to_restore.append(var) if tf.gfile.IsDirectory(FLAGS.checkpoint_path): checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path) else: checkpoint_path = FLAGS.checkpoint_path tf.logging.info('Fine-tuning from %s' % checkpoint_path) return slim.assign_from_checkpoint_fn( checkpoint_path, variables_to_restore, ignore_missing_vars=FLAGS.ignore_missing_vars) def _get_variables_to_train(): """Returns a list of variables to train. Returns: A list of variables to train by the optimizer. """ if FLAGS.trainable_scopes is None: return tf.trainable_variables() else: scopes = [scope.strip() for scope in FLAGS.trainable_scopes.split(',')] variables_to_train = [] for scope in scopes: variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope) variables_to_train.extend(variables) return variables_to_train def main(_): if not FLAGS.dataset_dir: raise ValueError('You must supply the dataset directory with --dataset_dir') tf.logging.set_verbosity(tf.logging.INFO) with tf.Graph().as_default(): ####################### # Config model_deploy # ####################### deploy_config = model_deploy.DeploymentConfig( num_clones=FLAGS.num_clones, clone_on_cpu=FLAGS.clone_on_cpu, replica_id=FLAGS.task, num_replicas=FLAGS.worker_replicas, num_ps_tasks=FLAGS.num_ps_tasks) # Create global_step with tf.device(deploy_config.variables_device()): global_step = slim.create_global_step() ###################### # Select the dataset # ###################### dataset = dataset_factory.get_dataset( FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir) ###################### # Select the network # ###################### network_fn = nets_factory.get_network_fn( FLAGS.model_name, num_classes=(dataset.num_classes - FLAGS.labels_offset), weight_decay=FLAGS.weight_decay, is_training=True) ##################################### # Select the preprocessing function # ##################################### preprocessing_name = FLAGS.preprocessing_name or FLAGS.model_name image_preprocessing_fn = preprocessing_factory.get_preprocessing( preprocessing_name, is_training=True) ############################################################## # Create a dataset provider that loads data from the dataset # ############################################################## with tf.device(deploy_config.inputs_device()): provider = slim.dataset_data_provider.DatasetDataProvider( dataset, num_readers=FLAGS.num_readers, common_queue_capacity=20 * FLAGS.batch_size, common_queue_min=10 * FLAGS.batch_size) [image, label] = provider.get(['image', 'label']) label -= FLAGS.labels_offset train_image_size = FLAGS.train_image_size or network_fn.default_image_size image = image_preprocessing_fn(image, train_image_size, train_image_size) images, labels = tf.train.batch( [image, label], batch_size=FLAGS.batch_size, num_threads=FLAGS.num_preprocessing_threads, capacity=5 * FLAGS.batch_size) labels = slim.one_hot_encoding( labels, dataset.num_classes - FLAGS.labels_offset) batch_queue = slim.prefetch_queue.prefetch_queue( [images, labels], capacity=2 * deploy_config.num_clones) #################### # Define the model # #################### def clone_fn(batch_queue): """Allows data parallelism by creating multiple clones of network_fn.""" images, labels = batch_queue.dequeue() logits, end_points = network_fn(images) ############################# # Specify the loss function # ############################# if 'AuxLogits' in end_points: slim.losses.softmax_cross_entropy( end_points['AuxLogits'], labels, label_smoothing=FLAGS.label_smoothing, weights=0.4, scope='aux_loss') slim.losses.softmax_cross_entropy( logits, labels, label_smoothing=FLAGS.label_smoothing, weights=1.0) return end_points # Gather initial summaries. summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES)) clones = model_deploy.create_clones(deploy_config, clone_fn, [batch_queue]) first_clone_scope = deploy_config.clone_scope(0) # Gather update_ops from the first clone. These contain, for example, # the updates for the batch_norm variables created by network_fn. update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone_scope) # Add summaries for end_points. end_points = clones[0].outputs for end_point in end_points: x = end_points[end_point] summaries.add(tf.summary.histogram('activations/' + end_point, x)) summaries.add(tf.summary.scalar('sparsity/' + end_point, tf.nn.zero_fraction(x))) # Add summaries for losses. for loss in tf.get_collection(tf.GraphKeys.LOSSES, first_clone_scope): summaries.add(tf.summary.scalar('losses/%s' % loss.op.name, loss)) # Add summaries for variables. for variable in slim.get_model_variables(): summaries.add(tf.summary.histogram(variable.op.name, variable)) ################################# # Configure the moving averages # ################################# if FLAGS.moving_average_decay: moving_average_variables = slim.get_model_variables() variable_averages = tf.train.ExponentialMovingAverage( FLAGS.moving_average_decay, global_step) else: moving_average_variables, variable_averages = None, None if FLAGS.quantize_delay >= 0: tf.contrib.quantize.create_training_graph( quant_delay=FLAGS.quantize_delay) ######################################### # Configure the optimization procedure. # ######################################### with tf.device(deploy_config.optimizer_device()): learning_rate = _configure_learning_rate(dataset.num_samples, global_step) optimizer = _configure_optimizer(learning_rate) summaries.add(tf.summary.scalar('learning_rate', learning_rate)) if FLAGS.sync_replicas: # If sync_replicas is enabled, the averaging will be done in the chief # queue runner. optimizer = tf.train.SyncReplicasOptimizer( opt=optimizer, replicas_to_aggregate=FLAGS.replicas_to_aggregate, total_num_replicas=FLAGS.worker_replicas, variable_averages=variable_averages, variables_to_average=moving_average_variables) elif FLAGS.moving_average_decay: # Update ops executed locally by trainer. update_ops.append(variable_averages.apply(moving_average_variables)) # Variables to train. variables_to_train = _get_variables_to_train() # and returns a train_tensor and summary_op total_loss, clones_gradients = model_deploy.optimize_clones( clones, optimizer, var_list=variables_to_train) # Add total_loss to summary. summaries.add(tf.summary.scalar('total_loss', total_loss)) # Create gradient updates. grad_updates = optimizer.apply_gradients(clones_gradients, global_step=global_step) update_ops.append(grad_updates) update_op = tf.group(*update_ops) with tf.control_dependencies([update_op]): train_tensor = tf.identity(total_loss, name='train_op') # Add the summaries from the first clone. These contain the summaries # created by model_fn and either optimize_clones() or _gather_clone_loss(). summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES, first_clone_scope)) # Merge all summaries together. summary_op = tf.summary.merge(list(summaries), name='summary_op') ########################### # Kicks off the training. # ########################### slim.learning.train( train_tensor, logdir=FLAGS.train_dir, master=FLAGS.master, is_chief=(FLAGS.task == 0), init_fn=_get_init_fn(), summary_op=summary_op, number_of_steps=FLAGS.max_number_of_steps, log_every_n_steps=FLAGS.log_every_n_steps, save_summaries_secs=FLAGS.save_summaries_secs, save_interval_secs=FLAGS.save_interval_secs, sync_optimizer=optimizer if FLAGS.sync_replicas else None) if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/train_image_classifier.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Generic evaluation script that evaluates a model using a given dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from datasets import dataset_factory from nets import nets_factory from preprocessing import preprocessing_factory slim = tf.contrib.slim tf.app.flags.DEFINE_integer( 'batch_size', 100, 'The number of samples in each batch.') tf.app.flags.DEFINE_integer( 'max_num_batches', None, 'Max number of batches to evaluate by default use all.') tf.app.flags.DEFINE_string( 'master', '', 'The address of the TensorFlow master to use.') tf.app.flags.DEFINE_string( 'checkpoint_path', '/tmp/tfmodel/', 'The directory where the model was written to or an absolute path to a ' 'checkpoint file.') tf.app.flags.DEFINE_string( 'eval_dir', '/tmp/tfmodel/', 'Directory where the results are saved to.') tf.app.flags.DEFINE_integer( 'num_preprocessing_threads', 4, 'The number of threads used to create the batches.') tf.app.flags.DEFINE_string( 'dataset_name', 'imagenet', 'The name of the dataset to load.') tf.app.flags.DEFINE_string( 'dataset_split_name', 'test', 'The name of the train/test split.') tf.app.flags.DEFINE_string( 'dataset_dir', None, 'The directory where the dataset files are stored.') tf.app.flags.DEFINE_integer( 'labels_offset', 0, 'An offset for the labels in the dataset. This flag is primarily used to ' 'evaluate the VGG and ResNet architectures which do not use a background ' 'class for the ImageNet dataset.') tf.app.flags.DEFINE_string( 'model_name', 'inception_v3', 'The name of the architecture to evaluate.') tf.app.flags.DEFINE_string( 'preprocessing_name', None, 'The name of the preprocessing to use. If left ' 'as `None`, then the model_name flag is used.') tf.app.flags.DEFINE_float( 'moving_average_decay', None, 'The decay to use for the moving average.' 'If left as None, then moving averages are not used.') tf.app.flags.DEFINE_integer( 'eval_image_size', None, 'Eval image size') tf.app.flags.DEFINE_bool( 'quantize', False, 'whether to use quantized graph or not.') FLAGS = tf.app.flags.FLAGS def main(_): if not FLAGS.dataset_dir: raise ValueError('You must supply the dataset directory with --dataset_dir') tf.logging.set_verbosity(tf.logging.INFO) with tf.Graph().as_default(): tf_global_step = slim.get_or_create_global_step() ###################### # Select the dataset # ###################### dataset = dataset_factory.get_dataset( FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir) #################### # Select the model # #################### network_fn = nets_factory.get_network_fn( FLAGS.model_name, num_classes=(dataset.num_classes - FLAGS.labels_offset), is_training=False) ############################################################## # Create a dataset provider that loads data from the dataset # ############################################################## provider = slim.dataset_data_provider.DatasetDataProvider( dataset, shuffle=False, common_queue_capacity=2 * FLAGS.batch_size, common_queue_min=FLAGS.batch_size) [image, label] = provider.get(['image', 'label']) label -= FLAGS.labels_offset ##################################### # Select the preprocessing function # ##################################### preprocessing_name = FLAGS.preprocessing_name or FLAGS.model_name image_preprocessing_fn = preprocessing_factory.get_preprocessing( preprocessing_name, is_training=False) eval_image_size = FLAGS.eval_image_size or network_fn.default_image_size image = image_preprocessing_fn(image, eval_image_size, eval_image_size) images, labels = tf.train.batch( [image, label], batch_size=FLAGS.batch_size, num_threads=FLAGS.num_preprocessing_threads, capacity=5 * FLAGS.batch_size) #################### # Define the model # #################### logits, _ = network_fn(images) if FLAGS.quantize: tf.contrib.quantize.create_eval_graph() if FLAGS.moving_average_decay: variable_averages = tf.train.ExponentialMovingAverage( FLAGS.moving_average_decay, tf_global_step) variables_to_restore = variable_averages.variables_to_restore( slim.get_model_variables()) variables_to_restore[tf_global_step.op.name] = tf_global_step else: variables_to_restore = slim.get_variables_to_restore() predictions = tf.argmax(logits, 1) labels = tf.squeeze(labels) # Define the metrics: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ 'Accuracy': slim.metrics.streaming_accuracy(predictions, labels), 'Recall_5': slim.metrics.streaming_recall_at_k( logits, labels, 5), }) # Print the summaries to screen. for name, value in names_to_values.items(): summary_name = 'eval/%s' % name op = tf.summary.scalar(summary_name, value, collections=[]) op = tf.Print(op, [value], summary_name) tf.add_to_collection(tf.GraphKeys.SUMMARIES, op) # TODO(sguada) use num_epochs=1 if FLAGS.max_num_batches: num_batches = FLAGS.max_num_batches else: # This ensures that we make a single pass over all of the data. num_batches = math.ceil(dataset.num_samples / float(FLAGS.batch_size)) if tf.gfile.IsDirectory(FLAGS.checkpoint_path): checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path) else: checkpoint_path = FLAGS.checkpoint_path tf.logging.info('Evaluating %s' % checkpoint_path) slim.evaluation.evaluate_once( master=FLAGS.master, checkpoint_path=checkpoint_path, logdir=FLAGS.eval_dir, num_evals=num_batches, eval_op=list(names_to_updates.values()), variables_to_restore=variables_to_restore) if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/eval_image_classifier.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Setup script for slim.""" from setuptools import find_packages from setuptools import setup setup( name='slim', version='0.1', include_package_data=True, packages=find_packages(), description='tf-slim', )
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/setup.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Saves out a GraphDef containing the architecture of the model. To use it, run something like this, with a model name defined by slim: bazel build tensorflow_models/research/slim:export_inference_graph bazel-bin/tensorflow_models/research/slim/export_inference_graph \ --model_name=inception_v3 --output_file=/tmp/inception_v3_inf_graph.pb If you then want to use the resulting model with your own or pretrained checkpoints as part of a mobile model, you can run freeze_graph to get a graph def with the variables inlined as constants using: bazel build tensorflow/python/tools:freeze_graph bazel-bin/tensorflow/python/tools/freeze_graph \ --input_graph=/tmp/inception_v3_inf_graph.pb \ --input_checkpoint=/tmp/checkpoints/inception_v3.ckpt \ --input_binary=true --output_graph=/tmp/frozen_inception_v3.pb \ --output_node_names=InceptionV3/Predictions/Reshape_1 The output node names will vary depending on the model, but you can inspect and estimate them using the summarize_graph tool: bazel build tensorflow/tools/graph_transforms:summarize_graph bazel-bin/tensorflow/tools/graph_transforms/summarize_graph \ --in_graph=/tmp/inception_v3_inf_graph.pb To run the resulting graph in C++, you can look at the label_image sample code: bazel build tensorflow/examples/label_image:label_image bazel-bin/tensorflow/examples/label_image/label_image \ --image=${HOME}/Pictures/flowers.jpg \ --input_layer=input \ --output_layer=InceptionV3/Predictions/Reshape_1 \ --graph=/tmp/frozen_inception_v3.pb \ --labels=/tmp/imagenet_slim_labels.txt \ --input_mean=0 \ --input_std=255 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from tensorflow.python.platform import gfile from datasets import dataset_factory from nets import nets_factory slim = tf.contrib.slim tf.app.flags.DEFINE_string( 'model_name', 'inception_v3', 'The name of the architecture to save.') tf.app.flags.DEFINE_boolean( 'is_training', False, 'Whether to save out a training-focused version of the model.') tf.app.flags.DEFINE_integer( 'image_size', None, 'The image size to use, otherwise use the model default_image_size.') tf.app.flags.DEFINE_integer( 'batch_size', None, 'Batch size for the exported model. Defaulted to "None" so batch size can ' 'be specified at model runtime.') tf.app.flags.DEFINE_string('dataset_name', 'imagenet', 'The name of the dataset to use with the model.') tf.app.flags.DEFINE_integer( 'labels_offset', 0, 'An offset for the labels in the dataset. This flag is primarily used to ' 'evaluate the VGG and ResNet architectures which do not use a background ' 'class for the ImageNet dataset.') tf.app.flags.DEFINE_string( 'output_file', '', 'Where to save the resulting file to.') tf.app.flags.DEFINE_string( 'dataset_dir', '', 'Directory to save intermediate dataset files to') tf.app.flags.DEFINE_bool( 'quantize', False, 'whether to use quantized graph or not.') tf.app.flags.DEFINE_bool( 'is_video_model', False, 'whether to use 5-D inputs for video model.') tf.app.flags.DEFINE_integer( 'num_frames', None, 'The number of frames to use. Only used if is_video_model is True.') tf.app.flags.DEFINE_bool('write_text_graphdef', False, 'Whether to write a text version of graphdef.') FLAGS = tf.app.flags.FLAGS def main(_): if not FLAGS.output_file: raise ValueError('You must supply the path to save to with --output_file') if FLAGS.is_video_model and not FLAGS.num_frames: raise ValueError( 'Number of frames must be specified for video models with --num_frames') tf.logging.set_verbosity(tf.logging.INFO) with tf.Graph().as_default() as graph: dataset = dataset_factory.get_dataset(FLAGS.dataset_name, 'train', FLAGS.dataset_dir) network_fn = nets_factory.get_network_fn( FLAGS.model_name, num_classes=(dataset.num_classes - FLAGS.labels_offset), is_training=FLAGS.is_training) image_size = FLAGS.image_size or network_fn.default_image_size if FLAGS.is_video_model: input_shape = [FLAGS.batch_size, FLAGS.num_frames, image_size, image_size, 3] else: input_shape = [FLAGS.batch_size, image_size, image_size, 3] placeholder = tf.placeholder(name='input', dtype=tf.float32, shape=input_shape) network_fn(placeholder) if FLAGS.quantize: tf.contrib.quantize.create_eval_graph() graph_def = graph.as_graph_def() if FLAGS.write_text_graphdef: tf.io.write_graph( graph_def, os.path.dirname(FLAGS.output_file), os.path.basename(FLAGS.output_file), as_text=True) else: with gfile.GFile(FLAGS.output_file, 'wb') as f: f.write(graph_def.SerializeToString()) if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/export_inference_graph.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for export_inference_graph.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from tensorflow.python.platform import gfile import export_inference_graph class ExportInferenceGraphTest(tf.test.TestCase): def testExportInferenceGraph(self): tmpdir = self.get_temp_dir() output_file = os.path.join(tmpdir, 'inception_v3.pb') flags = tf.app.flags.FLAGS flags.output_file = output_file flags.model_name = 'inception_v3' flags.dataset_dir = tmpdir export_inference_graph.main(None) self.assertTrue(gfile.Exists(output_file)) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/export_inference_graph_test.py
#!/usr/bin/python # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Process the ImageNet Challenge bounding boxes for TensorFlow model training. Associate the ImageNet 2012 Challenge validation data set with labels. The raw ImageNet validation data set is expected to reside in JPEG files located in the following directory structure. data_dir/ILSVRC2012_val_00000001.JPEG data_dir/ILSVRC2012_val_00000002.JPEG ... data_dir/ILSVRC2012_val_00050000.JPEG This script moves the files into a directory structure like such: data_dir/n01440764/ILSVRC2012_val_00000293.JPEG data_dir/n01440764/ILSVRC2012_val_00000543.JPEG ... where 'n01440764' is the unique synset label associated with these images. This directory reorganization requires a mapping from validation image number (i.e. suffix of the original file) to the associated label. This is provided in the ImageNet development kit via a Matlab file. In order to make life easier and divorce ourselves from Matlab, we instead supply a custom text file that provides this mapping for us. Sample usage: ./preprocess_imagenet_validation_data.py ILSVRC2012_img_val \ imagenet_2012_validation_synset_labels.txt """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys from six.moves import xrange # pylint: disable=redefined-builtin if __name__ == '__main__': if len(sys.argv) < 3: print('Invalid usage\n' 'usage: preprocess_imagenet_validation_data.py ' '<validation data dir> <validation labels file>') sys.exit(-1) data_dir = sys.argv[1] validation_labels_file = sys.argv[2] # Read in the 50000 synsets associated with the validation data set. labels = [l.strip() for l in open(validation_labels_file).readlines()] unique_labels = set(labels) # Make all sub-directories in the validation data dir. for label in unique_labels: labeled_data_dir = os.path.join(data_dir, label) os.makedirs(labeled_data_dir) # Move all of the image to the appropriate sub-directory. for i in xrange(len(labels)): basename = 'ILSVRC2012_val_000%.5d.JPEG' % (i + 1) original_filename = os.path.join(data_dir, basename) if not os.path.exists(original_filename): print('Failed to find: ', original_filename) sys.exit(-1) new_filename = os.path.join(data_dir, labels[i], basename) os.rename(original_filename, new_filename)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/preprocess_imagenet_validation_data.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Provides data for the ImageNet ILSVRC 2012 Dataset plus some bounding boxes. Some images have one or more bounding boxes associated with the label of the image. See details here: http://image-net.org/download-bboxes ImageNet is based upon WordNet 3.0. To uniquely identify a synset, we use "WordNet ID" (wnid), which is a concatenation of POS ( i.e. part of speech ) and SYNSET OFFSET of WordNet. For more information, please refer to the WordNet documentation[http://wordnet.princeton.edu/wordnet/documentation/]. "There are bounding boxes for over 3000 popular synsets available. For each synset, there are on average 150 images with bounding boxes." WARNING: Don't use for object detection, in this case all the bounding boxes of the image belong to just one class. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from six.moves import urllib import tensorflow as tf from datasets import dataset_utils slim = tf.contrib.slim # TODO(nsilberman): Add tfrecord file type once the script is updated. _FILE_PATTERN = '%s-*' _SPLITS_TO_SIZES = { 'train': 1281167, 'validation': 50000, } _ITEMS_TO_DESCRIPTIONS = { 'image': 'A color image of varying height and width.', 'label': 'The label id of the image, integer between 0 and 999', 'label_text': 'The text of the label.', 'object/bbox': 'A list of bounding boxes.', 'object/label': 'A list of labels, one per each object.', } _NUM_CLASSES = 1001 # If set to false, will not try to set label_to_names in dataset # by reading them from labels.txt or github. LOAD_READABLE_NAMES = True def create_readable_names_for_imagenet_labels(): """Create a dict mapping label id to human readable string. Returns: labels_to_names: dictionary where keys are integers from to 1000 and values are human-readable names. We retrieve a synset file, which contains a list of valid synset labels used by ILSVRC competition. There is one synset one per line, eg. # n01440764 # n01443537 We also retrieve a synset_to_human_file, which contains a mapping from synsets to human-readable names for every synset in Imagenet. These are stored in a tsv format, as follows: # n02119247 black fox # n02119359 silver fox We assign each synset (in alphabetical order) an integer, starting from 1 (since 0 is reserved for the background class). Code is based on https://github.com/tensorflow/models/blob/master/research/inception/inception/data/build_imagenet_data.py#L463 """ # pylint: disable=g-line-too-long base_url = 'https://raw.githubusercontent.com/tensorflow/models/master/research/inception/inception/data/' synset_url = '{}/imagenet_lsvrc_2015_synsets.txt'.format(base_url) synset_to_human_url = '{}/imagenet_metadata.txt'.format(base_url) filename, _ = urllib.request.urlretrieve(synset_url) synset_list = [s.strip() for s in open(filename).readlines()] num_synsets_in_ilsvrc = len(synset_list) assert num_synsets_in_ilsvrc == 1000 filename, _ = urllib.request.urlretrieve(synset_to_human_url) synset_to_human_list = open(filename).readlines() num_synsets_in_all_imagenet = len(synset_to_human_list) assert num_synsets_in_all_imagenet == 21842 synset_to_human = {} for s in synset_to_human_list: parts = s.strip().split('\t') assert len(parts) == 2 synset = parts[0] human = parts[1] synset_to_human[synset] = human label_index = 1 labels_to_names = {0: 'background'} for synset in synset_list: name = synset_to_human[synset] labels_to_names[label_index] = name label_index += 1 return labels_to_names def get_split(split_name, dataset_dir, file_pattern=None, reader=None): """Gets a dataset tuple with instructions for reading ImageNet. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources. file_pattern: The file pattern to use when matching the dataset sources. It is assumed that the pattern contains a '%s' string so that the split name can be inserted. reader: The TensorFlow reader type. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split. """ if split_name not in _SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if reader is None: reader = tf.TFRecordReader keys_to_features = { 'image/encoded': tf.FixedLenFeature( (), tf.string, default_value=''), 'image/format': tf.FixedLenFeature( (), tf.string, default_value='jpeg'), 'image/class/label': tf.FixedLenFeature( [], dtype=tf.int64, default_value=-1), 'image/class/text': tf.FixedLenFeature( [], dtype=tf.string, default_value=''), 'image/object/bbox/xmin': tf.VarLenFeature( dtype=tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature( dtype=tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature( dtype=tf.float32), 'image/object/bbox/ymax': tf.VarLenFeature( dtype=tf.float32), 'image/object/class/label': tf.VarLenFeature( dtype=tf.int64), } items_to_handlers = { 'image': slim.tfexample_decoder.Image('image/encoded', 'image/format'), 'label': slim.tfexample_decoder.Tensor('image/class/label'), 'label_text': slim.tfexample_decoder.Tensor('image/class/text'), 'object/bbox': slim.tfexample_decoder.BoundingBox( ['ymin', 'xmin', 'ymax', 'xmax'], 'image/object/bbox/'), 'object/label': slim.tfexample_decoder.Tensor('image/object/class/label'), } decoder = slim.tfexample_decoder.TFExampleDecoder( keys_to_features, items_to_handlers) labels_to_names = None if LOAD_READABLE_NAMES: if dataset_utils.has_labels(dataset_dir): labels_to_names = dataset_utils.read_label_file(dataset_dir) else: labels_to_names = create_readable_names_for_imagenet_labels() dataset_utils.write_label_file(labels_to_names, dataset_dir) return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=_SPLITS_TO_SIZES[split_name], items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, num_classes=_NUM_CLASSES, labels_to_names=labels_to_names)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/imagenet.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains utilities for downloading and converting datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import tarfile from six.moves import urllib import tensorflow as tf LABELS_FILENAME = 'labels.txt' def int64_feature(values): """Returns a TF-Feature of int64s. Args: values: A scalar or list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def bytes_feature(values): """Returns a TF-Feature of bytes. Args: values: A string. Returns: A TF-Feature. """ return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values])) def float_feature(values): """Returns a TF-Feature of floats. Args: values: A scalar of list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def image_to_tfexample(image_data, image_format, height, width, class_id): return tf.train.Example(features=tf.train.Features(feature={ 'image/encoded': bytes_feature(image_data), 'image/format': bytes_feature(image_format), 'image/class/label': int64_feature(class_id), 'image/height': int64_feature(height), 'image/width': int64_feature(width), })) def download_and_uncompress_tarball(tarball_url, dataset_dir): """Downloads the `tarball_url` and uncompresses it locally. Args: tarball_url: The URL of a tarball file. dataset_dir: The directory where the temporary files are stored. """ filename = tarball_url.split('/')[-1] filepath = os.path.join(dataset_dir, filename) def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % ( filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = urllib.request.urlretrieve(tarball_url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') tarfile.open(filepath, 'r:gz').extractall(dataset_dir) def write_label_file(labels_to_class_names, dataset_dir, filename=LABELS_FILENAME): """Writes a file with the list of class names. Args: labels_to_class_names: A map of (integer) labels to class names. dataset_dir: The directory in which the labels file should be written. filename: The filename where the class names are written. """ labels_filename = os.path.join(dataset_dir, filename) with tf.gfile.Open(labels_filename, 'w') as f: for label in labels_to_class_names: class_name = labels_to_class_names[label] f.write('%d:%s\n' % (label, class_name)) def has_labels(dataset_dir, filename=LABELS_FILENAME): """Specifies whether or not the dataset directory contains a label map file. Args: dataset_dir: The directory in which the labels file is found. filename: The filename where the class names are written. Returns: `True` if the labels file exists and `False` otherwise. """ return tf.gfile.Exists(os.path.join(dataset_dir, filename)) def read_label_file(dataset_dir, filename=LABELS_FILENAME): """Reads the labels file and returns a mapping from ID to class name. Args: dataset_dir: The directory in which the labels file is found. filename: The filename where the class names are written. Returns: A map from a label (integer) to class name. """ labels_filename = os.path.join(dataset_dir, filename) with tf.gfile.Open(labels_filename, 'rb') as f: lines = f.read().decode() lines = lines.split('\n') lines = filter(None, lines) labels_to_class_names = {} for line in lines: index = line.index(':') labels_to_class_names[int(line[:index])] = line[index+1:] return labels_to_class_names
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/dataset_utils.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converts ImageNet data to TFRecords file format with Example protos. The raw ImageNet data set is expected to reside in JPEG files located in the following directory structure. data_dir/n01440764/ILSVRC2012_val_00000293.JPEG data_dir/n01440764/ILSVRC2012_val_00000543.JPEG ... where 'n01440764' is the unique synset label associated with these images. The training data set consists of 1000 sub-directories (i.e. labels) each containing 1200 JPEG images for a total of 1.2M JPEG images. The evaluation data set consists of 1000 sub-directories (i.e. labels) each containing 50 JPEG images for a total of 50K JPEG images. This TensorFlow script converts the training and evaluation data into a sharded data set consisting of 1024 and 128 TFRecord files, respectively. train_directory/train-00000-of-01024 train_directory/train-00001-of-01024 ... train_directory/train-00127-of-01024 and validation_directory/validation-00000-of-00128 validation_directory/validation-00001-of-00128 ... validation_directory/validation-00127-of-00128 Each validation TFRecord file contains ~390 records. Each training TFREcord file contains ~1250 records. Each record within the TFRecord file is a serialized Example proto. The Example proto contains the following fields: image/encoded: string containing JPEG encoded image in RGB colorspace image/height: integer, image height in pixels image/width: integer, image width in pixels image/colorspace: string, specifying the colorspace, always 'RGB' image/channels: integer, specifying the number of channels, always 3 image/format: string, specifying the format, always'JPEG' image/filename: string containing the basename of the image file e.g. 'n01440764_10026.JPEG' or 'ILSVRC2012_val_00000293.JPEG' image/class/label: integer specifying the index in a classification layer. The label ranges from [1, 1000] where 0 is not used. image/class/synset: string specifying the unique ID of the label, e.g. 'n01440764' image/class/text: string specifying the human-readable version of the label e.g. 'red fox, Vulpes vulpes' image/object/bbox/xmin: list of integers specifying the 0+ human annotated bounding boxes image/object/bbox/xmax: list of integers specifying the 0+ human annotated bounding boxes image/object/bbox/ymin: list of integers specifying the 0+ human annotated bounding boxes image/object/bbox/ymax: list of integers specifying the 0+ human annotated bounding boxes image/object/bbox/label: integer specifying the index in a classification layer. The label ranges from [1, 1000] where 0 is not used. Note this is always identical to the image label. Note that the length of xmin is identical to the length of xmax, ymin and ymax for each example. Running this script using 16 threads may take around ~2.5 hours on a HP Z420. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import os import random import sys import threading import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf tf.app.flags.DEFINE_string('train_directory', '/tmp/', 'Training data directory') tf.app.flags.DEFINE_string('validation_directory', '/tmp/', 'Validation data directory') tf.app.flags.DEFINE_string('output_directory', '/tmp/', 'Output data directory') tf.app.flags.DEFINE_integer('train_shards', 1024, 'Number of shards in training TFRecord files.') tf.app.flags.DEFINE_integer('validation_shards', 128, 'Number of shards in validation TFRecord files.') tf.app.flags.DEFINE_integer('num_threads', 8, 'Number of threads to preprocess the images.') # The labels file contains a list of valid labels are held in this file. # Assumes that the file contains entries as such: # n01440764 # n01443537 # n01484850 # where each line corresponds to a label expressed as a synset. We map # each synset contained in the file to an integer (based on the alphabetical # ordering). See below for details. tf.app.flags.DEFINE_string('labels_file', 'imagenet_lsvrc_2015_synsets.txt', 'Labels file') # This file containing mapping from synset to human-readable label. # Assumes each line of the file looks like: # # n02119247 black fox # n02119359 silver fox # n02119477 red fox, Vulpes fulva # # where each line corresponds to a unique mapping. Note that each line is # formatted as <synset>\t<human readable label>. tf.app.flags.DEFINE_string('imagenet_metadata_file', 'imagenet_metadata.txt', 'ImageNet metadata file') # This file is the output of process_bounding_box.py # Assumes each line of the file looks like: # # n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940 # # where each line corresponds to one bounding box annotation associated # with an image. Each line can be parsed as: # # <JPEG file name>, <xmin>, <ymin>, <xmax>, <ymax> # # Note that there might exist mulitple bounding box annotations associated # with an image file. tf.app.flags.DEFINE_string('bounding_box_file', './imagenet_2012_bounding_boxes.csv', 'Bounding box file') FLAGS = tf.app.flags.FLAGS def _int64_feature(value): """Wrapper for inserting int64 features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) def _float_feature(value): """Wrapper for inserting float features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value)) def _bytes_feature(value): """Wrapper for inserting bytes features into Example proto.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _convert_to_example(filename, image_buffer, label, synset, human, bbox, height, width): """Build an Example proto for an example. Args: filename: string, path to an image file, e.g., '/path/to/example.JPG' image_buffer: string, JPEG encoding of RGB image label: integer, identifier for the ground truth for the network synset: string, unique WordNet ID specifying the label, e.g., 'n02323233' human: string, human-readable label, e.g., 'red fox, Vulpes vulpes' bbox: list of bounding boxes; each box is a list of integers specifying [xmin, ymin, xmax, ymax]. All boxes are assumed to belong to the same label as the image label. height: integer, image height in pixels width: integer, image width in pixels Returns: Example proto """ xmin = [] ymin = [] xmax = [] ymax = [] for b in bbox: assert len(b) == 4 # pylint: disable=expression-not-assigned [l.append(point) for l, point in zip([xmin, ymin, xmax, ymax], b)] # pylint: enable=expression-not-assigned colorspace = 'RGB' channels = 3 image_format = 'JPEG' example = tf.train.Example(features=tf.train.Features(feature={ 'image/height': _int64_feature(height), 'image/width': _int64_feature(width), 'image/colorspace': _bytes_feature(colorspace), 'image/channels': _int64_feature(channels), 'image/class/label': _int64_feature(label), 'image/class/synset': _bytes_feature(synset), 'image/class/text': _bytes_feature(human), 'image/object/bbox/xmin': _float_feature(xmin), 'image/object/bbox/xmax': _float_feature(xmax), 'image/object/bbox/ymin': _float_feature(ymin), 'image/object/bbox/ymax': _float_feature(ymax), 'image/object/bbox/label': _int64_feature([label] * len(xmin)), 'image/format': _bytes_feature(image_format), 'image/filename': _bytes_feature(os.path.basename(filename)), 'image/encoded': _bytes_feature(image_buffer)})) return example class ImageCoder(object): """Helper class that provides TensorFlow image coding utilities.""" def __init__(self): # Create a single Session to run all image coding calls. self._sess = tf.Session() # Initializes function that converts PNG to JPEG data. self._png_data = tf.placeholder(dtype=tf.string) image = tf.image.decode_png(self._png_data, channels=3) self._png_to_jpeg = tf.image.encode_jpeg(image, format='rgb', quality=100) # Initializes function that converts CMYK JPEG data to RGB JPEG data. self._cmyk_data = tf.placeholder(dtype=tf.string) image = tf.image.decode_jpeg(self._cmyk_data, channels=0) self._cmyk_to_rgb = tf.image.encode_jpeg(image, format='rgb', quality=100) # Initializes function that decodes RGB JPEG data. self._decode_jpeg_data = tf.placeholder(dtype=tf.string) self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3) def png_to_jpeg(self, image_data): return self._sess.run(self._png_to_jpeg, feed_dict={self._png_data: image_data}) def cmyk_to_rgb(self, image_data): return self._sess.run(self._cmyk_to_rgb, feed_dict={self._cmyk_data: image_data}) def decode_jpeg(self, image_data): image = self._sess.run(self._decode_jpeg, feed_dict={self._decode_jpeg_data: image_data}) assert len(image.shape) == 3 assert image.shape[2] == 3 return image def _is_png(filename): """Determine if a file contains a PNG format image. Args: filename: string, path of the image file. Returns: boolean indicating if the image is a PNG. """ # File list from: # https://groups.google.com/forum/embed/?place=forum/torch7#!topic/torch7/fOSTXHIESSU return 'n02105855_2933.JPEG' in filename def _is_cmyk(filename): """Determine if file contains a CMYK JPEG format image. Args: filename: string, path of the image file. Returns: boolean indicating if the image is a JPEG encoded with CMYK color space. """ # File list from: # https://github.com/cytsai/ilsvrc-cmyk-image-list blacklist = ['n01739381_1309.JPEG', 'n02077923_14822.JPEG', 'n02447366_23489.JPEG', 'n02492035_15739.JPEG', 'n02747177_10752.JPEG', 'n03018349_4028.JPEG', 'n03062245_4620.JPEG', 'n03347037_9675.JPEG', 'n03467068_12171.JPEG', 'n03529860_11437.JPEG', 'n03544143_17228.JPEG', 'n03633091_5218.JPEG', 'n03710637_5125.JPEG', 'n03961711_5286.JPEG', 'n04033995_2932.JPEG', 'n04258138_17003.JPEG', 'n04264628_27969.JPEG', 'n04336792_7448.JPEG', 'n04371774_5854.JPEG', 'n04596742_4225.JPEG', 'n07583066_647.JPEG', 'n13037406_4650.JPEG'] return filename.split('/')[-1] in blacklist def _process_image(filename, coder): """Process a single image file. Args: filename: string, path to an image file e.g., '/path/to/example.JPG'. coder: instance of ImageCoder to provide TensorFlow image coding utils. Returns: image_buffer: string, JPEG encoding of RGB image. height: integer, image height in pixels. width: integer, image width in pixels. """ # Read the image file. image_data = tf.gfile.FastGFile(filename, 'r').read() # Clean the dirty data. if _is_png(filename): # 1 image is a PNG. print('Converting PNG to JPEG for %s' % filename) image_data = coder.png_to_jpeg(image_data) elif _is_cmyk(filename): # 22 JPEG images are in CMYK colorspace. print('Converting CMYK to RGB for %s' % filename) image_data = coder.cmyk_to_rgb(image_data) # Decode the RGB JPEG. image = coder.decode_jpeg(image_data) # Check that image converted to RGB assert len(image.shape) == 3 height = image.shape[0] width = image.shape[1] assert image.shape[2] == 3 return image_data, height, width def _process_image_files_batch(coder, thread_index, ranges, name, filenames, synsets, labels, humans, bboxes, num_shards): """Processes and saves list of images as TFRecord in 1 thread. Args: coder: instance of ImageCoder to provide TensorFlow image coding utils. thread_index: integer, unique batch to run index is within [0, len(ranges)). ranges: list of pairs of integers specifying ranges of each batches to analyze in parallel. name: string, unique identifier specifying the data set filenames: list of strings; each string is a path to an image file synsets: list of strings; each string is a unique WordNet ID labels: list of integer; each integer identifies the ground truth humans: list of strings; each string is a human-readable label bboxes: list of bounding boxes for each image. Note that each entry in this list might contain from 0+ entries corresponding to the number of bounding box annotations for the image. num_shards: integer number of shards for this data set. """ # Each thread produces N shards where N = int(num_shards / num_threads). # For instance, if num_shards = 128, and the num_threads = 2, then the first # thread would produce shards [0, 64). num_threads = len(ranges) assert not num_shards % num_threads num_shards_per_batch = int(num_shards / num_threads) shard_ranges = np.linspace(ranges[thread_index][0], ranges[thread_index][1], num_shards_per_batch + 1).astype(int) num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0] counter = 0 for s in xrange(num_shards_per_batch): # Generate a sharded version of the file name, e.g. 'train-00002-of-00010' shard = thread_index * num_shards_per_batch + s output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards) output_file = os.path.join(FLAGS.output_directory, output_filename) writer = tf.python_io.TFRecordWriter(output_file) shard_counter = 0 files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int) for i in files_in_shard: filename = filenames[i] label = labels[i] synset = synsets[i] human = humans[i] bbox = bboxes[i] image_buffer, height, width = _process_image(filename, coder) example = _convert_to_example(filename, image_buffer, label, synset, human, bbox, height, width) writer.write(example.SerializeToString()) shard_counter += 1 counter += 1 if not counter % 1000: print('%s [thread %d]: Processed %d of %d images in thread batch.' % (datetime.now(), thread_index, counter, num_files_in_thread)) sys.stdout.flush() writer.close() print('%s [thread %d]: Wrote %d images to %s' % (datetime.now(), thread_index, shard_counter, output_file)) sys.stdout.flush() shard_counter = 0 print('%s [thread %d]: Wrote %d images to %d shards.' % (datetime.now(), thread_index, counter, num_files_in_thread)) sys.stdout.flush() def _process_image_files(name, filenames, synsets, labels, humans, bboxes, num_shards): """Process and save list of images as TFRecord of Example protos. Args: name: string, unique identifier specifying the data set filenames: list of strings; each string is a path to an image file synsets: list of strings; each string is a unique WordNet ID labels: list of integer; each integer identifies the ground truth humans: list of strings; each string is a human-readable label bboxes: list of bounding boxes for each image. Note that each entry in this list might contain from 0+ entries corresponding to the number of bounding box annotations for the image. num_shards: integer number of shards for this data set. """ assert len(filenames) == len(synsets) assert len(filenames) == len(labels) assert len(filenames) == len(humans) assert len(filenames) == len(bboxes) # Break all images into batches with a [ranges[i][0], ranges[i][1]]. spacing = np.linspace(0, len(filenames), FLAGS.num_threads + 1).astype(np.int) ranges = [] threads = [] for i in xrange(len(spacing) - 1): ranges.append([spacing[i], spacing[i+1]]) # Launch a thread for each batch. print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges)) sys.stdout.flush() # Create a mechanism for monitoring when all threads are finished. coord = tf.train.Coordinator() # Create a generic TensorFlow-based utility for converting all image codings. coder = ImageCoder() threads = [] for thread_index in xrange(len(ranges)): args = (coder, thread_index, ranges, name, filenames, synsets, labels, humans, bboxes, num_shards) t = threading.Thread(target=_process_image_files_batch, args=args) t.start() threads.append(t) # Wait for all the threads to terminate. coord.join(threads) print('%s: Finished writing all %d images in data set.' % (datetime.now(), len(filenames))) sys.stdout.flush() def _find_image_files(data_dir, labels_file): """Build a list of all images files and labels in the data set. Args: data_dir: string, path to the root directory of images. Assumes that the ImageNet data set resides in JPEG files located in the following directory structure. data_dir/n01440764/ILSVRC2012_val_00000293.JPEG data_dir/n01440764/ILSVRC2012_val_00000543.JPEG where 'n01440764' is the unique synset label associated with these images. labels_file: string, path to the labels file. The list of valid labels are held in this file. Assumes that the file contains entries as such: n01440764 n01443537 n01484850 where each line corresponds to a label expressed as a synset. We map each synset contained in the file to an integer (based on the alphabetical ordering) starting with the integer 1 corresponding to the synset contained in the first line. The reason we start the integer labels at 1 is to reserve label 0 as an unused background class. Returns: filenames: list of strings; each string is a path to an image file. synsets: list of strings; each string is a unique WordNet ID. labels: list of integer; each integer identifies the ground truth. """ print('Determining list of input files and labels from %s.' % data_dir) challenge_synsets = [l.strip() for l in tf.gfile.FastGFile(labels_file, 'r').readlines()] labels = [] filenames = [] synsets = [] # Leave label index 0 empty as a background class. label_index = 1 # Construct the list of JPEG files and labels. for synset in challenge_synsets: jpeg_file_path = '%s/%s/*.JPEG' % (data_dir, synset) matching_files = tf.gfile.Glob(jpeg_file_path) labels.extend([label_index] * len(matching_files)) synsets.extend([synset] * len(matching_files)) filenames.extend(matching_files) if not label_index % 100: print('Finished finding files in %d of %d classes.' % ( label_index, len(challenge_synsets))) label_index += 1 # Shuffle the ordering of all image files in order to guarantee # random ordering of the images with respect to label in the # saved TFRecord files. Make the randomization repeatable. shuffled_index = range(len(filenames)) random.seed(12345) random.shuffle(shuffled_index) filenames = [filenames[i] for i in shuffled_index] synsets = [synsets[i] for i in shuffled_index] labels = [labels[i] for i in shuffled_index] print('Found %d JPEG files across %d labels inside %s.' % (len(filenames), len(challenge_synsets), data_dir)) return filenames, synsets, labels def _find_human_readable_labels(synsets, synset_to_human): """Build a list of human-readable labels. Args: synsets: list of strings; each string is a unique WordNet ID. synset_to_human: dict of synset to human labels, e.g., 'n02119022' --> 'red fox, Vulpes vulpes' Returns: List of human-readable strings corresponding to each synset. """ humans = [] for s in synsets: assert s in synset_to_human, ('Failed to find: %s' % s) humans.append(synset_to_human[s]) return humans def _find_image_bounding_boxes(filenames, image_to_bboxes): """Find the bounding boxes for a given image file. Args: filenames: list of strings; each string is a path to an image file. image_to_bboxes: dictionary mapping image file names to a list of bounding boxes. This list contains 0+ bounding boxes. Returns: List of bounding boxes for each image. Note that each entry in this list might contain from 0+ entries corresponding to the number of bounding box annotations for the image. """ num_image_bbox = 0 bboxes = [] for f in filenames: basename = os.path.basename(f) if basename in image_to_bboxes: bboxes.append(image_to_bboxes[basename]) num_image_bbox += 1 else: bboxes.append([]) print('Found %d images with bboxes out of %d images' % ( num_image_bbox, len(filenames))) return bboxes def _process_dataset(name, directory, num_shards, synset_to_human, image_to_bboxes): """Process a complete data set and save it as a TFRecord. Args: name: string, unique identifier specifying the data set. directory: string, root path to the data set. num_shards: integer number of shards for this data set. synset_to_human: dict of synset to human labels, e.g., 'n02119022' --> 'red fox, Vulpes vulpes' image_to_bboxes: dictionary mapping image file names to a list of bounding boxes. This list contains 0+ bounding boxes. """ filenames, synsets, labels = _find_image_files(directory, FLAGS.labels_file) humans = _find_human_readable_labels(synsets, synset_to_human) bboxes = _find_image_bounding_boxes(filenames, image_to_bboxes) _process_image_files(name, filenames, synsets, labels, humans, bboxes, num_shards) def _build_synset_lookup(imagenet_metadata_file): """Build lookup for synset to human-readable label. Args: imagenet_metadata_file: string, path to file containing mapping from synset to human-readable label. Assumes each line of the file looks like: n02119247 black fox n02119359 silver fox n02119477 red fox, Vulpes fulva where each line corresponds to a unique mapping. Note that each line is formatted as <synset>\t<human readable label>. Returns: Dictionary of synset to human labels, such as: 'n02119022' --> 'red fox, Vulpes vulpes' """ lines = tf.gfile.FastGFile(imagenet_metadata_file, 'r').readlines() synset_to_human = {} for l in lines: if l: parts = l.strip().split('\t') assert len(parts) == 2 synset = parts[0] human = parts[1] synset_to_human[synset] = human return synset_to_human def _build_bounding_box_lookup(bounding_box_file): """Build a lookup from image file to bounding boxes. Args: bounding_box_file: string, path to file with bounding boxes annotations. Assumes each line of the file looks like: n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940 where each line corresponds to one bounding box annotation associated with an image. Each line can be parsed as: <JPEG file name>, <xmin>, <ymin>, <xmax>, <ymax> Note that there might exist mulitple bounding box annotations associated with an image file. This file is the output of process_bounding_boxes.py. Returns: Dictionary mapping image file names to a list of bounding boxes. This list contains 0+ bounding boxes. """ lines = tf.gfile.FastGFile(bounding_box_file, 'r').readlines() images_to_bboxes = {} num_bbox = 0 num_image = 0 for l in lines: if l: parts = l.split(',') assert len(parts) == 5, ('Failed to parse: %s' % l) filename = parts[0] xmin = float(parts[1]) ymin = float(parts[2]) xmax = float(parts[3]) ymax = float(parts[4]) box = [xmin, ymin, xmax, ymax] if filename not in images_to_bboxes: images_to_bboxes[filename] = [] num_image += 1 images_to_bboxes[filename].append(box) num_bbox += 1 print('Successfully read %d bounding boxes ' 'across %d images.' % (num_bbox, num_image)) return images_to_bboxes def main(unused_argv): assert not FLAGS.train_shards % FLAGS.num_threads, ( 'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards') assert not FLAGS.validation_shards % FLAGS.num_threads, ( 'Please make the FLAGS.num_threads commensurate with ' 'FLAGS.validation_shards') print('Saving results to %s' % FLAGS.output_directory) # Build a map from synset to human-readable label. synset_to_human = _build_synset_lookup(FLAGS.imagenet_metadata_file) image_to_bboxes = _build_bounding_box_lookup(FLAGS.bounding_box_file) # Run it! _process_dataset('validation', FLAGS.validation_directory, FLAGS.validation_shards, synset_to_human, image_to_bboxes) _process_dataset('train', FLAGS.train_directory, FLAGS.train_shards, synset_to_human, image_to_bboxes) if __name__ == '__main__': tf.app.run()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/build_imagenet_data.py
#!/usr/bin/python # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Process the ImageNet Challenge bounding boxes for TensorFlow model training. This script is called as process_bounding_boxes.py <dir> [synsets-file] Where <dir> is a directory containing the downloaded and unpacked bounding box data. If [synsets-file] is supplied, then only the bounding boxes whose synstes are contained within this file are returned. Note that the [synsets-file] file contains synset ids, one per line. The script dumps out a CSV text file in which each line contains an entry. n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940 The entry can be read as: <JPEG file name>, <xmin>, <ymin>, <xmax>, <ymax> The bounding box for <JPEG file name> contains two points (xmin, ymin) and (xmax, ymax) specifying the lower-left corner and upper-right corner of a bounding box in *relative* coordinates. The user supplies a directory where the XML files reside. The directory structure in the directory <dir> is assumed to look like this: <dir>/nXXXXXXXX/nXXXXXXXX_YYYY.xml Each XML file contains a bounding box annotation. The script: (1) Parses the XML file and extracts the filename, label and bounding box info. (2) The bounding box is specified in the XML files as integer (xmin, ymin) and (xmax, ymax) *relative* to image size displayed to the human annotator. The size of the image displayed to the human annotator is stored in the XML file as integer (height, width). Note that the displayed size will differ from the actual size of the image downloaded from image-net.org. To make the bounding box annotation useable, we convert bounding box to floating point numbers relative to displayed height and width of the image. Note that each XML file might contain N bounding box annotations. Note that the points are all clamped at a range of [0.0, 1.0] because some human annotations extend outside the range of the supplied image. See details here: http://image-net.org/download-bboxes (3) By default, the script outputs all valid bounding boxes. If a [synsets-file] is supplied, only the subset of bounding boxes associated with those synsets are outputted. Importantly, one can supply a list of synsets in the ImageNet Challenge and output the list of bounding boxes associated with the training images of the ILSVRC. We use these bounding boxes to inform the random distortion of images supplied to the network. If you run this script successfully, you will see the following output to stderr: > Finished processing 544546 XML files. > Skipped 0 XML files not in ImageNet Challenge. > Skipped 0 bounding boxes not in ImageNet Challenge. > Wrote 615299 bounding boxes from 544546 annotated images. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os.path import sys import xml.etree.ElementTree as ET from six.moves import xrange # pylint: disable=redefined-builtin class BoundingBox(object): pass def GetItem(name, root, index=0): count = 0 for item in root.iter(name): if count == index: return item.text count += 1 # Failed to find "index" occurrence of item. return -1 def GetInt(name, root, index=0): return int(GetItem(name, root, index)) def FindNumberBoundingBoxes(root): index = 0 while True: if GetInt('xmin', root, index) == -1: break index += 1 return index def ProcessXMLAnnotation(xml_file): """Process a single XML file containing a bounding box.""" # pylint: disable=broad-except try: tree = ET.parse(xml_file) except Exception: print('Failed to parse: ' + xml_file, file=sys.stderr) return None # pylint: enable=broad-except root = tree.getroot() num_boxes = FindNumberBoundingBoxes(root) boxes = [] for index in xrange(num_boxes): box = BoundingBox() # Grab the 'index' annotation. box.xmin = GetInt('xmin', root, index) box.ymin = GetInt('ymin', root, index) box.xmax = GetInt('xmax', root, index) box.ymax = GetInt('ymax', root, index) box.width = GetInt('width', root) box.height = GetInt('height', root) box.filename = GetItem('filename', root) + '.JPEG' box.label = GetItem('name', root) xmin = float(box.xmin) / float(box.width) xmax = float(box.xmax) / float(box.width) ymin = float(box.ymin) / float(box.height) ymax = float(box.ymax) / float(box.height) # Some images contain bounding box annotations that # extend outside of the supplied image. See, e.g. # n03127925/n03127925_147.xml # Additionally, for some bounding boxes, the min > max # or the box is entirely outside of the image. min_x = min(xmin, xmax) max_x = max(xmin, xmax) box.xmin_scaled = min(max(min_x, 0.0), 1.0) box.xmax_scaled = min(max(max_x, 0.0), 1.0) min_y = min(ymin, ymax) max_y = max(ymin, ymax) box.ymin_scaled = min(max(min_y, 0.0), 1.0) box.ymax_scaled = min(max(max_y, 0.0), 1.0) boxes.append(box) return boxes if __name__ == '__main__': if len(sys.argv) < 2 or len(sys.argv) > 3: print('Invalid usage\n' 'usage: process_bounding_boxes.py <dir> [synsets-file]', file=sys.stderr) sys.exit(-1) xml_files = glob.glob(sys.argv[1] + '/*/*.xml') print('Identified %d XML files in %s' % (len(xml_files), sys.argv[1]), file=sys.stderr) if len(sys.argv) == 3: labels = set([l.strip() for l in open(sys.argv[2]).readlines()]) print('Identified %d synset IDs in %s' % (len(labels), sys.argv[2]), file=sys.stderr) else: labels = None skipped_boxes = 0 skipped_files = 0 saved_boxes = 0 saved_files = 0 for file_index, one_file in enumerate(xml_files): # Example: <...>/n06470073/n00141669_6790.xml label = os.path.basename(os.path.dirname(one_file)) # Determine if the annotation is from an ImageNet Challenge label. if labels is not None and label not in labels: skipped_files += 1 continue bboxes = ProcessXMLAnnotation(one_file) assert bboxes is not None, 'No bounding boxes found in ' + one_file found_box = False for bbox in bboxes: if labels is not None: if bbox.label != label: # Note: There is a slight bug in the bounding box annotation data. # Many of the dog labels have the human label 'Scottish_deerhound' # instead of the synset ID 'n02092002' in the bbox.label field. As a # simple hack to overcome this issue, we only exclude bbox labels # *which are synset ID's* that do not match original synset label for # the XML file. if bbox.label in labels: skipped_boxes += 1 continue # Guard against improperly specified boxes. if (bbox.xmin_scaled >= bbox.xmax_scaled or bbox.ymin_scaled >= bbox.ymax_scaled): skipped_boxes += 1 continue # Note bbox.filename occasionally contains '%s' in the name. This is # data set noise that is fixed by just using the basename of the XML file. image_filename = os.path.splitext(os.path.basename(one_file))[0] print('%s.JPEG,%.4f,%.4f,%.4f,%.4f' % (image_filename, bbox.xmin_scaled, bbox.ymin_scaled, bbox.xmax_scaled, bbox.ymax_scaled)) saved_boxes += 1 found_box = True if found_box: saved_files += 1 else: skipped_files += 1 if not file_index % 5000: print('--> processed %d of %d XML files.' % (file_index + 1, len(xml_files)), file=sys.stderr) print('--> skipped %d boxes and %d XML files.' % (skipped_boxes, skipped_files), file=sys.stderr) print('Finished processing %d XML files.' % len(xml_files), file=sys.stderr) print('Skipped %d XML files not in ImageNet Challenge.' % skipped_files, file=sys.stderr) print('Skipped %d bounding boxes not in ImageNet Challenge.' % skipped_boxes, file=sys.stderr) print('Wrote %d bounding boxes from %d annotated images.' % (saved_boxes, saved_files), file=sys.stderr) print('Finished.', file=sys.stderr)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/process_bounding_boxes.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A factory-pattern class which returns classification image/label pairs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from datasets import cifar10 from datasets import flowers from datasets import imagenet from datasets import mnist datasets_map = { 'cifar10': cifar10, 'flowers': flowers, 'imagenet': imagenet, 'mnist': mnist, } def get_dataset(name, split_name, dataset_dir, file_pattern=None, reader=None): """Given a dataset name and a split_name returns a Dataset. Args: name: String, the name of the dataset. split_name: A train/test split name. dataset_dir: The directory where the dataset files are stored. file_pattern: The file pattern to use for matching the dataset source files. reader: The subclass of tf.ReaderBase. If left as `None`, then the default reader defined by each dataset is used. Returns: A `Dataset` class. Raises: ValueError: If the dataset `name` is unknown. """ if name not in datasets_map: raise ValueError('Name of dataset unknown %s' % name) return datasets_map[name].get_split( split_name, dataset_dir, file_pattern, reader)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/dataset_factory.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Provides data for the Cifar10 dataset. The dataset scripts used to create the dataset can be found at: tensorflow/models/research/slim/datasets/download_and_convert_cifar10.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from datasets import dataset_utils slim = tf.contrib.slim _FILE_PATTERN = 'cifar10_%s.tfrecord' SPLITS_TO_SIZES = {'train': 50000, 'test': 10000} _NUM_CLASSES = 10 _ITEMS_TO_DESCRIPTIONS = { 'image': 'A [32 x 32 x 3] color image.', 'label': 'A single integer between 0 and 9', } def get_split(split_name, dataset_dir, file_pattern=None, reader=None): """Gets a dataset tuple with instructions for reading cifar10. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources. file_pattern: The file pattern to use when matching the dataset sources. It is assumed that the pattern contains a '%s' string so that the split name can be inserted. reader: The TensorFlow reader type. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split. """ if split_name not in SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if not reader: reader = tf.TFRecordReader keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='png'), 'image/class/label': tf.FixedLenFeature( [], tf.int64, default_value=tf.zeros([], dtype=tf.int64)), } items_to_handlers = { 'image': slim.tfexample_decoder.Image(shape=[32, 32, 3]), 'label': slim.tfexample_decoder.Tensor('image/class/label'), } decoder = slim.tfexample_decoder.TFExampleDecoder( keys_to_features, items_to_handlers) labels_to_names = None if dataset_utils.has_labels(dataset_dir): labels_to_names = dataset_utils.read_label_file(dataset_dir) return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=SPLITS_TO_SIZES[split_name], items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, num_classes=_NUM_CLASSES, labels_to_names=labels_to_names)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/cifar10.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Downloads and converts cifar10 data to TFRecords of TF-Example protos. This module downloads the cifar10 data, uncompresses it, reads the files that make up the cifar10 data and creates two TFRecord datasets: one for train and one for test. Each TFRecord dataset is comprised of a set of TF-Example protocol buffers, each of which contain a single image and label. The script should take several minutes to run. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import tarfile import numpy as np from six.moves import cPickle from six.moves import urllib import tensorflow as tf from datasets import dataset_utils # The URL where the CIFAR data can be downloaded. _DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' # The number of training files. _NUM_TRAIN_FILES = 5 # The height and width of each image. _IMAGE_SIZE = 32 # The names of the classes. _CLASS_NAMES = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck', ] def _add_to_tfrecord(filename, tfrecord_writer, offset=0): """Loads data from the cifar10 pickle files and writes files to a TFRecord. Args: filename: The filename of the cifar10 pickle file. tfrecord_writer: The TFRecord writer to use for writing. offset: An offset into the absolute number of images previously written. Returns: The new offset. """ with tf.gfile.Open(filename, 'rb') as f: if sys.version_info < (3,): data = cPickle.load(f) else: data = cPickle.load(f, encoding='bytes') images = data[b'data'] num_images = images.shape[0] images = images.reshape((num_images, 3, 32, 32)) labels = data[b'labels'] with tf.Graph().as_default(): image_placeholder = tf.placeholder(dtype=tf.uint8) encoded_image = tf.image.encode_png(image_placeholder) with tf.Session('') as sess: for j in range(num_images): sys.stdout.write('\r>> Reading file [%s] image %d/%d' % ( filename, offset + j + 1, offset + num_images)) sys.stdout.flush() image = np.squeeze(images[j]).transpose((1, 2, 0)) label = labels[j] png_string = sess.run(encoded_image, feed_dict={image_placeholder: image}) example = dataset_utils.image_to_tfexample( png_string, b'png', _IMAGE_SIZE, _IMAGE_SIZE, label) tfrecord_writer.write(example.SerializeToString()) return offset + num_images def _get_output_filename(dataset_dir, split_name): """Creates the output filename. Args: dataset_dir: The dataset directory where the dataset is stored. split_name: The name of the train/test split. Returns: An absolute file path. """ return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name) def _download_and_uncompress_dataset(dataset_dir): """Downloads cifar10 and uncompresses it locally. Args: dataset_dir: The directory where the temporary files are stored. """ filename = _DATA_URL.split('/')[-1] filepath = os.path.join(dataset_dir, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % ( filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = urllib.request.urlretrieve(_DATA_URL, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') tarfile.open(filepath, 'r:gz').extractall(dataset_dir) def _clean_up_temporary_files(dataset_dir): """Removes temporary files used to create the dataset. Args: dataset_dir: The directory where the temporary files are stored. """ filename = _DATA_URL.split('/')[-1] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py') tf.gfile.DeleteRecursively(tmp_dir) def run(dataset_dir): """Runs the download and conversion operation. Args: dataset_dir: The dataset directory where the dataset is stored. """ if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) training_filename = _get_output_filename(dataset_dir, 'train') testing_filename = _get_output_filename(dataset_dir, 'test') if tf.gfile.Exists(training_filename) and tf.gfile.Exists(testing_filename): print('Dataset files already exist. Exiting without re-creating them.') return dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir) # First, process the training data: with tf.python_io.TFRecordWriter(training_filename) as tfrecord_writer: offset = 0 for i in range(_NUM_TRAIN_FILES): filename = os.path.join(dataset_dir, 'cifar-10-batches-py', 'data_batch_%d' % (i + 1)) # 1-indexed. offset = _add_to_tfrecord(filename, tfrecord_writer, offset) # Next, process the testing data: with tf.python_io.TFRecordWriter(testing_filename) as tfrecord_writer: filename = os.path.join(dataset_dir, 'cifar-10-batches-py', 'test_batch') _add_to_tfrecord(filename, tfrecord_writer) # Finally, write the labels file: labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES)) dataset_utils.write_label_file(labels_to_class_names, dataset_dir) _clean_up_temporary_files(dataset_dir) print('\nFinished converting the Cifar10 dataset!')
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/download_and_convert_cifar10.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Downloads and converts Flowers data to TFRecords of TF-Example protos. This module downloads the Flowers data, uncompresses it, reads the files that make up the Flowers data and creates two TFRecord datasets: one for train and one for test. Each TFRecord dataset is comprised of a set of TF-Example protocol buffers, each of which contain a single image and label. The script should take about a minute to run. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import os import random import sys import tensorflow as tf from datasets import dataset_utils # The URL where the Flowers data can be downloaded. _DATA_URL = 'http://download.tensorflow.org/example_images/flower_photos.tgz' # The number of images in the validation set. _NUM_VALIDATION = 350 # Seed for repeatability. _RANDOM_SEED = 0 # The number of shards per dataset split. _NUM_SHARDS = 5 class ImageReader(object): """Helper class that provides TensorFlow image coding utilities.""" def __init__(self): # Initializes function that decodes RGB JPEG data. self._decode_jpeg_data = tf.placeholder(dtype=tf.string) self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3) def read_image_dims(self, sess, image_data): image = self.decode_jpeg(sess, image_data) return image.shape[0], image.shape[1] def decode_jpeg(self, sess, image_data): image = sess.run(self._decode_jpeg, feed_dict={self._decode_jpeg_data: image_data}) assert len(image.shape) == 3 assert image.shape[2] == 3 return image def _get_filenames_and_classes(dataset_dir): """Returns a list of filenames and inferred class names. Args: dataset_dir: A directory containing a set of subdirectories representing class names. Each subdirectory should contain PNG or JPG encoded images. Returns: A list of image file paths, relative to `dataset_dir` and the list of subdirectories, representing class names. """ flower_root = os.path.join(dataset_dir, 'flower_photos') directories = [] class_names = [] for filename in os.listdir(flower_root): path = os.path.join(flower_root, filename) if os.path.isdir(path): directories.append(path) class_names.append(filename) photo_filenames = [] for directory in directories: for filename in os.listdir(directory): path = os.path.join(directory, filename) photo_filenames.append(path) return photo_filenames, sorted(class_names) def _get_dataset_filename(dataset_dir, split_name, shard_id): output_filename = 'flowers_%s_%05d-of-%05d.tfrecord' % ( split_name, shard_id, _NUM_SHARDS) return os.path.join(dataset_dir, output_filename) def _convert_dataset(split_name, filenames, class_names_to_ids, dataset_dir): """Converts the given filenames to a TFRecord dataset. Args: split_name: The name of the dataset, either 'train' or 'validation'. filenames: A list of absolute paths to png or jpg images. class_names_to_ids: A dictionary from class names (strings) to ids (integers). dataset_dir: The directory where the converted datasets are stored. """ assert split_name in ['train', 'validation'] num_per_shard = int(math.ceil(len(filenames) / float(_NUM_SHARDS))) with tf.Graph().as_default(): image_reader = ImageReader() with tf.Session('') as sess: for shard_id in range(_NUM_SHARDS): output_filename = _get_dataset_filename( dataset_dir, split_name, shard_id) with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer: start_ndx = shard_id * num_per_shard end_ndx = min((shard_id+1) * num_per_shard, len(filenames)) for i in range(start_ndx, end_ndx): sys.stdout.write('\r>> Converting image %d/%d shard %d' % ( i+1, len(filenames), shard_id)) sys.stdout.flush() # Read the filename: image_data = tf.gfile.FastGFile(filenames[i], 'rb').read() height, width = image_reader.read_image_dims(sess, image_data) class_name = os.path.basename(os.path.dirname(filenames[i])) class_id = class_names_to_ids[class_name] example = dataset_utils.image_to_tfexample( image_data, b'jpg', height, width, class_id) tfrecord_writer.write(example.SerializeToString()) sys.stdout.write('\n') sys.stdout.flush() def _clean_up_temporary_files(dataset_dir): """Removes temporary files used to create the dataset. Args: dataset_dir: The directory where the temporary files are stored. """ filename = _DATA_URL.split('/')[-1] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'flower_photos') tf.gfile.DeleteRecursively(tmp_dir) def _dataset_exists(dataset_dir): for split_name in ['train', 'validation']: for shard_id in range(_NUM_SHARDS): output_filename = _get_dataset_filename( dataset_dir, split_name, shard_id) if not tf.gfile.Exists(output_filename): return False return True def run(dataset_dir): """Runs the download and conversion operation. Args: dataset_dir: The dataset directory where the dataset is stored. """ if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) if _dataset_exists(dataset_dir): print('Dataset files already exist. Exiting without re-creating them.') return dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir) photo_filenames, class_names = _get_filenames_and_classes(dataset_dir) class_names_to_ids = dict(zip(class_names, range(len(class_names)))) # Divide into train and test: random.seed(_RANDOM_SEED) random.shuffle(photo_filenames) training_filenames = photo_filenames[_NUM_VALIDATION:] validation_filenames = photo_filenames[:_NUM_VALIDATION] # First, convert the training and validation sets. _convert_dataset('train', training_filenames, class_names_to_ids, dataset_dir) _convert_dataset('validation', validation_filenames, class_names_to_ids, dataset_dir) # Finally, write the labels file: labels_to_class_names = dict(zip(range(len(class_names)), class_names)) dataset_utils.write_label_file(labels_to_class_names, dataset_dir) _clean_up_temporary_files(dataset_dir) print('\nFinished converting the Flowers dataset!')
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/download_and_convert_flowers.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Downloads and converts MNIST data to TFRecords of TF-Example protos. This module downloads the MNIST data, uncompresses it, reads the files that make up the MNIST data and creates two TFRecord datasets: one for train and one for test. Each TFRecord dataset is comprised of a set of TF-Example protocol buffers, each of which contain a single image and label. The script should take about a minute to run. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import os import sys import numpy as np from six.moves import urllib import tensorflow as tf from datasets import dataset_utils # The URLs where the MNIST data can be downloaded. _DATA_URL = 'http://yann.lecun.com/exdb/mnist/' _TRAIN_DATA_FILENAME = 'train-images-idx3-ubyte.gz' _TRAIN_LABELS_FILENAME = 'train-labels-idx1-ubyte.gz' _TEST_DATA_FILENAME = 't10k-images-idx3-ubyte.gz' _TEST_LABELS_FILENAME = 't10k-labels-idx1-ubyte.gz' _IMAGE_SIZE = 28 _NUM_CHANNELS = 1 # The names of the classes. _CLASS_NAMES = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'size', 'seven', 'eight', 'nine', ] def _extract_images(filename, num_images): """Extract the images into a numpy array. Args: filename: The path to an MNIST images file. num_images: The number of images in the file. Returns: A numpy array of shape [number_of_images, height, width, channels]. """ print('Extracting images from: ', filename) with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read( _IMAGE_SIZE * _IMAGE_SIZE * num_images * _NUM_CHANNELS) data = np.frombuffer(buf, dtype=np.uint8) data = data.reshape(num_images, _IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS) return data def _extract_labels(filename, num_labels): """Extract the labels into a vector of int64 label IDs. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A numpy array of shape [number_of_labels] """ print('Extracting labels from: ', filename) with gzip.open(filename) as bytestream: bytestream.read(8) buf = bytestream.read(1 * num_labels) labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64) return labels def _add_to_tfrecord(data_filename, labels_filename, num_images, tfrecord_writer): """Loads data from the binary MNIST files and writes files to a TFRecord. Args: data_filename: The filename of the MNIST images. labels_filename: The filename of the MNIST labels. num_images: The number of images in the dataset. tfrecord_writer: The TFRecord writer to use for writing. """ images = _extract_images(data_filename, num_images) labels = _extract_labels(labels_filename, num_images) shape = (_IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS) with tf.Graph().as_default(): image = tf.placeholder(dtype=tf.uint8, shape=shape) encoded_png = tf.image.encode_png(image) with tf.Session('') as sess: for j in range(num_images): sys.stdout.write('\r>> Converting image %d/%d' % (j + 1, num_images)) sys.stdout.flush() png_string = sess.run(encoded_png, feed_dict={image: images[j]}) example = dataset_utils.image_to_tfexample( png_string, 'png'.encode(), _IMAGE_SIZE, _IMAGE_SIZE, labels[j]) tfrecord_writer.write(example.SerializeToString()) def _get_output_filename(dataset_dir, split_name): """Creates the output filename. Args: dataset_dir: The directory where the temporary files are stored. split_name: The name of the train/test split. Returns: An absolute file path. """ return '%s/mnist_%s.tfrecord' % (dataset_dir, split_name) def _download_dataset(dataset_dir): """Downloads MNIST locally. Args: dataset_dir: The directory where the temporary files are stored. """ for filename in [_TRAIN_DATA_FILENAME, _TRAIN_LABELS_FILENAME, _TEST_DATA_FILENAME, _TEST_LABELS_FILENAME]: filepath = os.path.join(dataset_dir, filename) if not os.path.exists(filepath): print('Downloading file %s...' % filename) def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %.1f%%' % ( float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = urllib.request.urlretrieve(_DATA_URL + filename, filepath, _progress) print() with tf.gfile.GFile(filepath) as f: size = f.size() print('Successfully downloaded', filename, size, 'bytes.') def _clean_up_temporary_files(dataset_dir): """Removes temporary files used to create the dataset. Args: dataset_dir: The directory where the temporary files are stored. """ for filename in [_TRAIN_DATA_FILENAME, _TRAIN_LABELS_FILENAME, _TEST_DATA_FILENAME, _TEST_LABELS_FILENAME]: filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) def run(dataset_dir): """Runs the download and conversion operation. Args: dataset_dir: The dataset directory where the dataset is stored. """ if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) training_filename = _get_output_filename(dataset_dir, 'train') testing_filename = _get_output_filename(dataset_dir, 'test') if tf.gfile.Exists(training_filename) and tf.gfile.Exists(testing_filename): print('Dataset files already exist. Exiting without re-creating them.') return _download_dataset(dataset_dir) # First, process the training data: with tf.python_io.TFRecordWriter(training_filename) as tfrecord_writer: data_filename = os.path.join(dataset_dir, _TRAIN_DATA_FILENAME) labels_filename = os.path.join(dataset_dir, _TRAIN_LABELS_FILENAME) _add_to_tfrecord(data_filename, labels_filename, 60000, tfrecord_writer) # Next, process the testing data: with tf.python_io.TFRecordWriter(testing_filename) as tfrecord_writer: data_filename = os.path.join(dataset_dir, _TEST_DATA_FILENAME) labels_filename = os.path.join(dataset_dir, _TEST_LABELS_FILENAME) _add_to_tfrecord(data_filename, labels_filename, 10000, tfrecord_writer) # Finally, write the labels file: labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES)) dataset_utils.write_label_file(labels_to_class_names, dataset_dir) _clean_up_temporary_files(dataset_dir) print('\nFinished converting the MNIST dataset!')
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/download_and_convert_mnist.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Provides data for the flowers dataset. The dataset scripts used to create the dataset can be found at: tensorflow/models/research/slim/datasets/download_and_convert_flowers.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from datasets import dataset_utils slim = tf.contrib.slim _FILE_PATTERN = 'flowers_%s_*.tfrecord' SPLITS_TO_SIZES = {'train': 3320, 'validation': 350} _NUM_CLASSES = 5 _ITEMS_TO_DESCRIPTIONS = { 'image': 'A color image of varying size.', 'label': 'A single integer between 0 and 4', } def get_split(split_name, dataset_dir, file_pattern=None, reader=None): """Gets a dataset tuple with instructions for reading flowers. Args: split_name: A train/validation split name. dataset_dir: The base directory of the dataset sources. file_pattern: The file pattern to use when matching the dataset sources. It is assumed that the pattern contains a '%s' string so that the split name can be inserted. reader: The TensorFlow reader type. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/validation split. """ if split_name not in SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if reader is None: reader = tf.TFRecordReader keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='png'), 'image/class/label': tf.FixedLenFeature( [], tf.int64, default_value=tf.zeros([], dtype=tf.int64)), } items_to_handlers = { 'image': slim.tfexample_decoder.Image(), 'label': slim.tfexample_decoder.Tensor('image/class/label'), } decoder = slim.tfexample_decoder.TFExampleDecoder( keys_to_features, items_to_handlers) labels_to_names = None if dataset_utils.has_labels(dataset_dir): labels_to_names = dataset_utils.read_label_file(dataset_dir) return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=SPLITS_TO_SIZES[split_name], items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, num_classes=_NUM_CLASSES, labels_to_names=labels_to_names)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/flowers.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Provides data for the MNIST dataset. The dataset scripts used to create the dataset can be found at: tensorflow/models/research/slim/datasets/download_and_convert_mnist.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from datasets import dataset_utils slim = tf.contrib.slim _FILE_PATTERN = 'mnist_%s.tfrecord' _SPLITS_TO_SIZES = {'train': 60000, 'test': 10000} _NUM_CLASSES = 10 _ITEMS_TO_DESCRIPTIONS = { 'image': 'A [28 x 28 x 1] grayscale image.', 'label': 'A single integer between 0 and 9', } def get_split(split_name, dataset_dir, file_pattern=None, reader=None): """Gets a dataset tuple with instructions for reading MNIST. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources. file_pattern: The file pattern to use when matching the dataset sources. It is assumed that the pattern contains a '%s' string so that the split name can be inserted. reader: The TensorFlow reader type. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split. """ if split_name not in _SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if reader is None: reader = tf.TFRecordReader keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='raw'), 'image/class/label': tf.FixedLenFeature( [1], tf.int64, default_value=tf.zeros([1], dtype=tf.int64)), } items_to_handlers = { 'image': slim.tfexample_decoder.Image(shape=[28, 28, 1], channels=1), 'label': slim.tfexample_decoder.Tensor('image/class/label', shape=[]), } decoder = slim.tfexample_decoder.TFExampleDecoder( keys_to_features, items_to_handlers) labels_to_names = None if dataset_utils.has_labels(dataset_dir): labels_to_names = dataset_utils.read_label_file(dataset_dir) return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=_SPLITS_TO_SIZES[split_name], num_classes=_NUM_CLASSES, items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, labels_to_names=labels_to_names)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/datasets/mnist.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nets.resnet_v2.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nets import resnet_utils from nets import resnet_v2 slim = tf.contrib.slim def create_test_input(batch_size, height, width, channels): """Create test input tensor. Args: batch_size: The number of images per batch or `None` if unknown. height: The height of each image or `None` if unknown. width: The width of each image or `None` if unknown. channels: The number of channels per image or `None` if unknown. Returns: Either a placeholder `Tensor` of dimension [batch_size, height, width, channels] if any of the inputs are `None` or a constant `Tensor` with the mesh grid values along the spatial dimensions. """ if None in [batch_size, height, width, channels]: return tf.placeholder(tf.float32, (batch_size, height, width, channels)) else: return tf.to_float( np.tile( np.reshape( np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width]), [1, height, width, 1]), [batch_size, 1, 1, channels])) class ResnetUtilsTest(tf.test.TestCase): def testSubsampleThreeByThree(self): x = tf.reshape(tf.to_float(tf.range(9)), [1, 3, 3, 1]) x = resnet_utils.subsample(x, 2) expected = tf.reshape(tf.constant([0, 2, 6, 8]), [1, 2, 2, 1]) with self.test_session(): self.assertAllClose(x.eval(), expected.eval()) def testSubsampleFourByFour(self): x = tf.reshape(tf.to_float(tf.range(16)), [1, 4, 4, 1]) x = resnet_utils.subsample(x, 2) expected = tf.reshape(tf.constant([0, 2, 8, 10]), [1, 2, 2, 1]) with self.test_session(): self.assertAllClose(x.eval(), expected.eval()) def testConv2DSameEven(self): n, n2 = 4, 2 # Input image. x = create_test_input(1, n, n, 1) # Convolution kernel. w = create_test_input(1, 3, 3, 1) w = tf.reshape(w, [3, 3, 1, 1]) tf.get_variable('Conv/weights', initializer=w) tf.get_variable('Conv/biases', initializer=tf.zeros([1])) tf.get_variable_scope().reuse_variables() y1 = slim.conv2d(x, 1, [3, 3], stride=1, scope='Conv') y1_expected = tf.to_float([[14, 28, 43, 26], [28, 48, 66, 37], [43, 66, 84, 46], [26, 37, 46, 22]]) y1_expected = tf.reshape(y1_expected, [1, n, n, 1]) y2 = resnet_utils.subsample(y1, 2) y2_expected = tf.to_float([[14, 43], [43, 84]]) y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1]) y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv') y3_expected = y2_expected y4 = slim.conv2d(x, 1, [3, 3], stride=2, scope='Conv') y4_expected = tf.to_float([[48, 37], [37, 22]]) y4_expected = tf.reshape(y4_expected, [1, n2, n2, 1]) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) self.assertAllClose(y1.eval(), y1_expected.eval()) self.assertAllClose(y2.eval(), y2_expected.eval()) self.assertAllClose(y3.eval(), y3_expected.eval()) self.assertAllClose(y4.eval(), y4_expected.eval()) def testConv2DSameOdd(self): n, n2 = 5, 3 # Input image. x = create_test_input(1, n, n, 1) # Convolution kernel. w = create_test_input(1, 3, 3, 1) w = tf.reshape(w, [3, 3, 1, 1]) tf.get_variable('Conv/weights', initializer=w) tf.get_variable('Conv/biases', initializer=tf.zeros([1])) tf.get_variable_scope().reuse_variables() y1 = slim.conv2d(x, 1, [3, 3], stride=1, scope='Conv') y1_expected = tf.to_float([[14, 28, 43, 58, 34], [28, 48, 66, 84, 46], [43, 66, 84, 102, 55], [58, 84, 102, 120, 64], [34, 46, 55, 64, 30]]) y1_expected = tf.reshape(y1_expected, [1, n, n, 1]) y2 = resnet_utils.subsample(y1, 2) y2_expected = tf.to_float([[14, 43, 34], [43, 84, 55], [34, 55, 30]]) y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1]) y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv') y3_expected = y2_expected y4 = slim.conv2d(x, 1, [3, 3], stride=2, scope='Conv') y4_expected = y2_expected with self.test_session() as sess: sess.run(tf.global_variables_initializer()) self.assertAllClose(y1.eval(), y1_expected.eval()) self.assertAllClose(y2.eval(), y2_expected.eval()) self.assertAllClose(y3.eval(), y3_expected.eval()) self.assertAllClose(y4.eval(), y4_expected.eval()) def _resnet_plain(self, inputs, blocks, output_stride=None, scope=None): """A plain ResNet without extra layers before or after the ResNet blocks.""" with tf.variable_scope(scope, values=[inputs]): with slim.arg_scope([slim.conv2d], outputs_collections='end_points'): net = resnet_utils.stack_blocks_dense(inputs, blocks, output_stride) end_points = slim.utils.convert_collection_to_dict('end_points') return net, end_points def testEndPointsV2(self): """Test the end points of a tiny v2 bottleneck network.""" blocks = [ resnet_v2.resnet_v2_block( 'block1', base_depth=1, num_units=2, stride=2), resnet_v2.resnet_v2_block( 'block2', base_depth=2, num_units=2, stride=1), ] inputs = create_test_input(2, 32, 16, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_plain(inputs, blocks, scope='tiny') expected = [ 'tiny/block1/unit_1/bottleneck_v2/shortcut', 'tiny/block1/unit_1/bottleneck_v2/conv1', 'tiny/block1/unit_1/bottleneck_v2/conv2', 'tiny/block1/unit_1/bottleneck_v2/conv3', 'tiny/block1/unit_2/bottleneck_v2/conv1', 'tiny/block1/unit_2/bottleneck_v2/conv2', 'tiny/block1/unit_2/bottleneck_v2/conv3', 'tiny/block2/unit_1/bottleneck_v2/shortcut', 'tiny/block2/unit_1/bottleneck_v2/conv1', 'tiny/block2/unit_1/bottleneck_v2/conv2', 'tiny/block2/unit_1/bottleneck_v2/conv3', 'tiny/block2/unit_2/bottleneck_v2/conv1', 'tiny/block2/unit_2/bottleneck_v2/conv2', 'tiny/block2/unit_2/bottleneck_v2/conv3'] self.assertItemsEqual(expected, end_points.keys()) def _stack_blocks_nondense(self, net, blocks): """A simplified ResNet Block stacker without output stride control.""" for block in blocks: with tf.variable_scope(block.scope, 'block', [net]): for i, unit in enumerate(block.args): with tf.variable_scope('unit_%d' % (i + 1), values=[net]): net = block.unit_fn(net, rate=1, **unit) return net def testAtrousValuesBottleneck(self): """Verify the values of dense feature extraction by atrous convolution. Make sure that dense feature extraction by stack_blocks_dense() followed by subsampling gives identical results to feature extraction at the nominal network output stride using the simple self._stack_blocks_nondense() above. """ block = resnet_v2.resnet_v2_block blocks = [ block('block1', base_depth=1, num_units=2, stride=2), block('block2', base_depth=2, num_units=2, stride=2), block('block3', base_depth=4, num_units=2, stride=2), block('block4', base_depth=8, num_units=2, stride=1), ] nominal_stride = 8 # Test both odd and even input dimensions. height = 30 width = 31 with slim.arg_scope(resnet_utils.resnet_arg_scope()): with slim.arg_scope([slim.batch_norm], is_training=False): for output_stride in [1, 2, 4, 8, None]: with tf.Graph().as_default(): with self.test_session() as sess: tf.set_random_seed(0) inputs = create_test_input(1, height, width, 3) # Dense feature extraction followed by subsampling. output = resnet_utils.stack_blocks_dense(inputs, blocks, output_stride) if output_stride is None: factor = 1 else: factor = nominal_stride // output_stride output = resnet_utils.subsample(output, factor) # Make the two networks use the same weights. tf.get_variable_scope().reuse_variables() # Feature extraction at the nominal network rate. expected = self._stack_blocks_nondense(inputs, blocks) sess.run(tf.global_variables_initializer()) output, expected = sess.run([output, expected]) self.assertAllClose(output, expected, atol=1e-4, rtol=1e-4) class ResnetCompleteNetworkTest(tf.test.TestCase): """Tests with complete small ResNet v2 networks.""" def _resnet_small(self, inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope='resnet_v2_small'): """A shallow and thin ResNet v2 for faster tests.""" block = resnet_v2.resnet_v2_block blocks = [ block('block1', base_depth=1, num_units=3, stride=2), block('block2', base_depth=2, num_units=3, stride=2), block('block3', base_depth=4, num_units=3, stride=2), block('block4', base_depth=8, num_units=2, stride=1), ] return resnet_v2.resnet_v2(inputs, blocks, num_classes, is_training=is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=include_root_block, spatial_squeeze=spatial_squeeze, reuse=reuse, scope=scope) def testClassificationEndPoints(self): global_pool = True num_classes = 10 inputs = create_test_input(2, 224, 224, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): logits, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, spatial_squeeze=False, scope='resnet') self.assertTrue(logits.op.name.startswith('resnet/logits')) self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes]) self.assertTrue('predictions' in end_points) self.assertListEqual(end_points['predictions'].get_shape().as_list(), [2, 1, 1, num_classes]) self.assertTrue('global_pool' in end_points) self.assertListEqual(end_points['global_pool'].get_shape().as_list(), [2, 1, 1, 32]) def testEndpointNames(self): # Like ResnetUtilsTest.testEndPointsV2(), but for the public API. global_pool = True num_classes = 10 inputs = create_test_input(2, 224, 224, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, scope='resnet') expected = ['resnet/conv1'] for block in range(1, 5): for unit in range(1, 4 if block < 4 else 3): for conv in range(1, 4): expected.append('resnet/block%d/unit_%d/bottleneck_v2/conv%d' % (block, unit, conv)) expected.append('resnet/block%d/unit_%d/bottleneck_v2' % (block, unit)) expected.append('resnet/block%d/unit_1/bottleneck_v2/shortcut' % block) expected.append('resnet/block%d' % block) expected.extend(['global_pool', 'resnet/logits', 'resnet/spatial_squeeze', 'predictions']) self.assertItemsEqual(end_points.keys(), expected) def testClassificationShapes(self): global_pool = True num_classes = 10 inputs = create_test_input(2, 224, 224, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 28, 28, 4], 'resnet/block2': [2, 14, 14, 8], 'resnet/block3': [2, 7, 7, 16], 'resnet/block4': [2, 7, 7, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testFullyConvolutionalEndpointShapes(self): global_pool = False num_classes = 10 inputs = create_test_input(2, 321, 321, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, spatial_squeeze=False, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 41, 41, 4], 'resnet/block2': [2, 21, 21, 8], 'resnet/block3': [2, 11, 11, 16], 'resnet/block4': [2, 11, 11, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testRootlessFullyConvolutionalEndpointShapes(self): global_pool = False num_classes = 10 inputs = create_test_input(2, 128, 128, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, include_root_block=False, spatial_squeeze=False, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 64, 64, 4], 'resnet/block2': [2, 32, 32, 8], 'resnet/block3': [2, 16, 16, 16], 'resnet/block4': [2, 16, 16, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testAtrousFullyConvolutionalEndpointShapes(self): global_pool = False num_classes = 10 output_stride = 8 inputs = create_test_input(2, 321, 321, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, output_stride=output_stride, spatial_squeeze=False, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 41, 41, 4], 'resnet/block2': [2, 41, 41, 8], 'resnet/block3': [2, 41, 41, 16], 'resnet/block4': [2, 41, 41, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testAtrousFullyConvolutionalValues(self): """Verify dense feature extraction with atrous convolution.""" nominal_stride = 32 for output_stride in [4, 8, 16, 32, None]: with slim.arg_scope(resnet_utils.resnet_arg_scope()): with tf.Graph().as_default(): with self.test_session() as sess: tf.set_random_seed(0) inputs = create_test_input(2, 81, 81, 3) # Dense feature extraction followed by subsampling. output, _ = self._resnet_small(inputs, None, is_training=False, global_pool=False, output_stride=output_stride) if output_stride is None: factor = 1 else: factor = nominal_stride // output_stride output = resnet_utils.subsample(output, factor) # Make the two networks use the same weights. tf.get_variable_scope().reuse_variables() # Feature extraction at the nominal network rate. expected, _ = self._resnet_small(inputs, None, is_training=False, global_pool=False) sess.run(tf.global_variables_initializer()) self.assertAllClose(output.eval(), expected.eval(), atol=1e-4, rtol=1e-4) def testUnknownBatchSize(self): batch = 2 height, width = 65, 65 global_pool = True num_classes = 10 inputs = create_test_input(None, height, width, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): logits, _ = self._resnet_small(inputs, num_classes, global_pool=global_pool, spatial_squeeze=False, scope='resnet') self.assertTrue(logits.op.name.startswith('resnet/logits')) self.assertListEqual(logits.get_shape().as_list(), [None, 1, 1, num_classes]) images = create_test_input(batch, height, width, 3) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEqual(output.shape, (batch, 1, 1, num_classes)) def testFullyConvolutionalUnknownHeightWidth(self): batch = 2 height, width = 65, 65 global_pool = False inputs = create_test_input(batch, None, None, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): output, _ = self._resnet_small(inputs, None, global_pool=global_pool) self.assertListEqual(output.get_shape().as_list(), [batch, None, None, 32]) images = create_test_input(batch, height, width, 3) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(output, {inputs: images.eval()}) self.assertEqual(output.shape, (batch, 3, 3, 32)) def testAtrousFullyConvolutionalUnknownHeightWidth(self): batch = 2 height, width = 65, 65 global_pool = False output_stride = 8 inputs = create_test_input(batch, None, None, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): output, _ = self._resnet_small(inputs, None, global_pool=global_pool, output_stride=output_stride) self.assertListEqual(output.get_shape().as_list(), [batch, None, None, 32]) images = create_test_input(batch, height, width, 3) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(output, {inputs: images.eval()}) self.assertEqual(output.shape, (batch, 9, 9, 32)) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/resnet_v2_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nets.overfeat.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import overfeat slim = tf.contrib.slim class OverFeatTest(tf.test.TestCase): def testBuild(self): batch_size = 5 height, width = 231, 231 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = overfeat.overfeat(inputs, num_classes) self.assertEquals(logits.op.name, 'overfeat/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 281, 281 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = overfeat.overfeat(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'overfeat/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 2, 2, num_classes]) def testGlobalPool(self): batch_size = 1 height, width = 281, 281 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = overfeat.overfeat(inputs, num_classes, spatial_squeeze=False, global_pool=True) self.assertEquals(logits.op.name, 'overfeat/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 1, 1, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 231, 231 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = overfeat.overfeat(inputs, num_classes) expected_names = ['overfeat/conv1', 'overfeat/pool1', 'overfeat/conv2', 'overfeat/pool2', 'overfeat/conv3', 'overfeat/conv4', 'overfeat/conv5', 'overfeat/pool5', 'overfeat/fc6', 'overfeat/fc7', 'overfeat/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testNoClasses(self): batch_size = 5 height, width = 231, 231 num_classes = None with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = overfeat.overfeat(inputs, num_classes) expected_names = ['overfeat/conv1', 'overfeat/pool1', 'overfeat/conv2', 'overfeat/pool2', 'overfeat/conv3', 'overfeat/conv4', 'overfeat/conv5', 'overfeat/pool5', 'overfeat/fc6', 'overfeat/fc7' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) self.assertTrue(net.op.name.startswith('overfeat/fc7')) def testModelVariables(self): batch_size = 5 height, width = 231, 231 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) overfeat.overfeat(inputs, num_classes) expected_names = ['overfeat/conv1/weights', 'overfeat/conv1/biases', 'overfeat/conv2/weights', 'overfeat/conv2/biases', 'overfeat/conv3/weights', 'overfeat/conv3/biases', 'overfeat/conv4/weights', 'overfeat/conv4/biases', 'overfeat/conv5/weights', 'overfeat/conv5/biases', 'overfeat/fc6/weights', 'overfeat/fc6/biases', 'overfeat/fc7/weights', 'overfeat/fc7/biases', 'overfeat/fc8/weights', 'overfeat/fc8/biases', ] model_variables = [v.op.name for v in slim.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 231, 231 num_classes = 1000 with self.test_session(): eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = overfeat.overfeat(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = tf.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 231, 231 eval_height, eval_width = 281, 281 num_classes = 1000 with self.test_session(): train_inputs = tf.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = overfeat.overfeat(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) tf.get_variable_scope().reuse_variables() eval_inputs = tf.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = overfeat.overfeat(eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 2, 2, num_classes]) logits = tf.reduce_mean(logits, [1, 2]) predictions = tf.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 231, 231 with self.test_session() as sess: inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = overfeat.overfeat(inputs) sess.run(tf.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/overfeat_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains definitions for the original form of Residual Networks. The 'v1' residual networks (ResNets) implemented in this module were proposed by: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 Other variants were introduced in: [2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks. arXiv: 1603.05027 The networks defined in this module utilize the bottleneck building block of [1] with projection shortcuts only for increasing depths. They employ batch normalization *after* every weight layer. This is the architecture used by MSRA in the Imagenet and MSCOCO 2016 competition models ResNet-101 and ResNet-152. See [2; Fig. 1a] for a comparison between the current 'v1' architecture and the alternative 'v2' architecture of [2] which uses batch normalization *before* every weight layer in the so-called full pre-activation units. Typical use: from tensorflow.contrib.slim.nets import resnet_v1 ResNet-101 for image classification into 1000 classes: # inputs has shape [batch, 224, 224, 3] with slim.arg_scope(resnet_v1.resnet_arg_scope()): net, end_points = resnet_v1.resnet_v1_101(inputs, 1000, is_training=False) ResNet-101 for semantic segmentation into 21 classes: # inputs has shape [batch, 513, 513, 3] with slim.arg_scope(resnet_v1.resnet_arg_scope()): net, end_points = resnet_v1.resnet_v1_101(inputs, 21, is_training=False, global_pool=False, output_stride=16) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import resnet_utils resnet_arg_scope = resnet_utils.resnet_arg_scope slim = tf.contrib.slim class NoOpScope(object): """No-op context manager.""" def __enter__(self): return None def __exit__(self, exc_type, exc_value, traceback): return False @slim.add_arg_scope def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None, use_bounded_activations=False): """Bottleneck residual unit variant with BN after convolutions. This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] for its definition. Note that we use here the bottleneck variant which has an extra bottleneck layer. When putting together two consecutive ResNet blocks that use this unit, one should use stride = 2 in the last unit of the first block. Args: inputs: A tensor of size [batch, height, width, channels]. depth: The depth of the ResNet unit output. depth_bottleneck: The depth of the bottleneck layers. stride: The ResNet unit's stride. Determines the amount of downsampling of the units output compared to its input. rate: An integer, rate for atrous convolution. outputs_collections: Collection to add the ResNet unit output. scope: Optional variable_scope. use_bounded_activations: Whether or not to use bounded activations. Bounded activations better lend themselves to quantized inference. Returns: The ResNet unit's output. """ with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc: depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4) if depth == depth_in: shortcut = resnet_utils.subsample(inputs, stride, 'shortcut') else: shortcut = slim.conv2d( inputs, depth, [1, 1], stride=stride, activation_fn=tf.nn.relu6 if use_bounded_activations else None, scope='shortcut') residual = slim.conv2d(inputs, depth_bottleneck, [1, 1], stride=1, scope='conv1') residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2') residual = slim.conv2d(residual, depth, [1, 1], stride=1, activation_fn=None, scope='conv3') if use_bounded_activations: # Use clip_by_value to simulate bandpass activation. residual = tf.clip_by_value(residual, -6.0, 6.0) output = tf.nn.relu6(shortcut + residual) else: output = tf.nn.relu(shortcut + residual) return slim.utils.collect_named_outputs(outputs_collections, sc.name, output) def resnet_v1(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, store_non_strided_activations=False, reuse=None, scope=None): """Generator for v1 ResNet models. This function generates a family of ResNet v1 models. See the resnet_v1_*() methods for specific model instantiations, obtained by selecting different block instantiations that produce ResNets of various depths. Training for image classification on Imagenet is usually done with [224, 224] inputs, resulting in [7, 7] feature maps at the output of the last ResNet block for the ResNets defined in [1] that have nominal stride equal to 32. However, for dense prediction tasks we advise that one uses inputs with spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In this case the feature maps at the ResNet output will have spatial shape [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1] and corners exactly aligned with the input image corners, which greatly facilitates alignment of the features to the image. Using as input [225, 225] images results in [8, 8] feature maps at the output of the last ResNet block. For dense prediction tasks, the ResNet needs to run in fully-convolutional (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all have nominal stride equal to 32 and a good choice in FCN mode is to use output_stride=16 in order to increase the density of the computed features at small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. blocks: A list of length equal to the number of ResNet blocks. Each element is a resnet_utils.Block object describing the units in the block. num_classes: Number of predicted classes for classification tasks. If 0 or None, we return the features before the logit layer. is_training: whether batch_norm layers are in training mode. If this is set to None, the callers can specify slim.batch_norm's is_training parameter from an outer slim.arg_scope. global_pool: If True, we perform global average pooling before computing the logits. Set to True for image classification, False for dense prediction. output_stride: If None, then the output will be computed at the nominal network stride. If output_stride is not None, it specifies the requested ratio of input to output spatial resolution. include_root_block: If True, include the initial convolution followed by max-pooling, if False excludes it. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. To use this parameter, the input images must be smaller than 300x300 pixels, in which case the output logit layer does not contain spatial information and can be removed. store_non_strided_activations: If True, we compute non-strided (undecimated) activations at the last unit of each block and store them in the `outputs_collections` before subsampling them. This gives us access to higher resolution intermediate activations which are useful in some dense prediction problems but increases 4x the computation and memory cost at the last unit of each block. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: net: A rank-4 tensor of size [batch, height_out, width_out, channels_out]. If global_pool is False, then height_out and width_out are reduced by a factor of output_stride compared to the respective height_in and width_in, else both height_out and width_out equal one. If num_classes is 0 or None, then net is the output of the last ResNet block, potentially after global average pooling. If num_classes a non-zero integer, net contains the pre-softmax activations. end_points: A dictionary from components of the network to the corresponding activation. Raises: ValueError: If the target output_stride is not valid. """ with tf.variable_scope(scope, 'resnet_v1', [inputs], reuse=reuse) as sc: end_points_collection = sc.original_name_scope + '_end_points' with slim.arg_scope([slim.conv2d, bottleneck, resnet_utils.stack_blocks_dense], outputs_collections=end_points_collection): with (slim.arg_scope([slim.batch_norm], is_training=is_training) if is_training is not None else NoOpScope()): net = inputs if include_root_block: if output_stride is not None: if output_stride % 4 != 0: raise ValueError('The output_stride needs to be a multiple of 4.') output_stride /= 4 net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1') net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1') net = resnet_utils.stack_blocks_dense(net, blocks, output_stride, store_non_strided_activations) # Convert end_points_collection into a dictionary of end_points. end_points = slim.utils.convert_collection_to_dict( end_points_collection) if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], name='pool5', keep_dims=True) end_points['global_pool'] = net if num_classes: net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='logits') end_points[sc.name + '/logits'] = net if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='SpatialSqueeze') end_points[sc.name + '/spatial_squeeze'] = net end_points['predictions'] = slim.softmax(net, scope='predictions') return net, end_points resnet_v1.default_image_size = 224 def resnet_v1_block(scope, base_depth, num_units, stride): """Helper function for creating a resnet_v1 bottleneck block. Args: scope: The scope of the block. base_depth: The depth of the bottleneck layer for each unit. num_units: The number of units in the block. stride: The stride of the block, implemented as a stride in the last unit. All other units have stride=1. Returns: A resnet_v1 bottleneck block. """ return resnet_utils.Block(scope, bottleneck, [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1 }] * (num_units - 1) + [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride }]) def resnet_v1_50(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, store_non_strided_activations=False, reuse=None, scope='resnet_v1_50'): """ResNet-50 model of [1]. See resnet_v1() for arg and return description.""" blocks = [ resnet_v1_block('block1', base_depth=64, num_units=3, stride=2), resnet_v1_block('block2', base_depth=128, num_units=4, stride=2), resnet_v1_block('block3', base_depth=256, num_units=6, stride=2), resnet_v1_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v1(inputs, blocks, num_classes, is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, store_non_strided_activations=store_non_strided_activations, reuse=reuse, scope=scope) resnet_v1_50.default_image_size = resnet_v1.default_image_size def resnet_v1_101(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, store_non_strided_activations=False, reuse=None, scope='resnet_v1_101'): """ResNet-101 model of [1]. See resnet_v1() for arg and return description.""" blocks = [ resnet_v1_block('block1', base_depth=64, num_units=3, stride=2), resnet_v1_block('block2', base_depth=128, num_units=4, stride=2), resnet_v1_block('block3', base_depth=256, num_units=23, stride=2), resnet_v1_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v1(inputs, blocks, num_classes, is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, store_non_strided_activations=store_non_strided_activations, reuse=reuse, scope=scope) resnet_v1_101.default_image_size = resnet_v1.default_image_size def resnet_v1_152(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, store_non_strided_activations=False, spatial_squeeze=True, reuse=None, scope='resnet_v1_152'): """ResNet-152 model of [1]. See resnet_v1() for arg and return description.""" blocks = [ resnet_v1_block('block1', base_depth=64, num_units=3, stride=2), resnet_v1_block('block2', base_depth=128, num_units=8, stride=2), resnet_v1_block('block3', base_depth=256, num_units=36, stride=2), resnet_v1_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v1(inputs, blocks, num_classes, is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, store_non_strided_activations=store_non_strided_activations, reuse=reuse, scope=scope) resnet_v1_152.default_image_size = resnet_v1.default_image_size def resnet_v1_200(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, store_non_strided_activations=False, spatial_squeeze=True, reuse=None, scope='resnet_v1_200'): """ResNet-200 model of [2]. See resnet_v1() for arg and return description.""" blocks = [ resnet_v1_block('block1', base_depth=64, num_units=3, stride=2), resnet_v1_block('block2', base_depth=128, num_units=24, stride=2), resnet_v1_block('block3', base_depth=256, num_units=36, stride=2), resnet_v1_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v1(inputs, blocks, num_classes, is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, store_non_strided_activations=store_non_strided_activations, reuse=reuse, scope=scope) resnet_v1_200.default_image_size = resnet_v1.default_image_size
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/resnet_v1.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition of the Inception Resnet V2 architecture. As described in http://arxiv.org/abs/1602.07261. Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 48, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 64, 3, scope='Conv2d_0c_3x3') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_1, tower_conv2_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') scaled_up = up * scale if activation_fn == tf.nn.relu6: # Use clip_by_value to simulate bandpass activation. scaled_up = tf.clip_by_value(scaled_up, -6.0, 6.0) net += scaled_up if activation_fn: net = activation_fn(net) return net def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7], scope='Conv2d_0b_1x7') tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1], scope='Conv2d_0c_7x1') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') scaled_up = up * scale if activation_fn == tf.nn.relu6: # Use clip_by_value to simulate bandpass activation. scaled_up = tf.clip_by_value(scaled_up, -6.0, 6.0) net += scaled_up if activation_fn: net = activation_fn(net) return net def block8(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 8x8 resnet block.""" with tf.variable_scope(scope, 'Block8', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 192, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 224, [1, 3], scope='Conv2d_0b_1x3') tower_conv1_2 = slim.conv2d(tower_conv1_1, 256, [3, 1], scope='Conv2d_0c_3x1') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') scaled_up = up * scale if activation_fn == tf.nn.relu6: # Use clip_by_value to simulate bandpass activation. scaled_up = tf.clip_by_value(scaled_up, -6.0, 6.0) net += scaled_up if activation_fn: net = activation_fn(net) return net def inception_resnet_v2_base(inputs, final_endpoint='Conv2d_7b_1x1', output_stride=16, align_feature_maps=False, scope=None, activation_fn=tf.nn.relu): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1'] output_stride: A scalar that specifies the requested ratio of input to output spatial resolution. Only supports 8 and 16. align_feature_maps: When true, changes all the VALID paddings in the network to SAME padding so that the feature maps are aligned. scope: Optional variable_scope. activation_fn: Activation function for block scopes. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or if the output_stride is not 8 or 16, or if the output_stride is 8 and we request an end point after 'PreAuxLogits'. """ if output_stride != 8 and output_stride != 16: raise ValueError('output_stride must be 8 or 16.') padding = 'SAME' if align_feature_maps else 'VALID' end_points = {} def add_and_check_final(name, net): end_points[name] = net return name == final_endpoint with tf.variable_scope(scope, 'InceptionResnetV2', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # 149 x 149 x 32 net = slim.conv2d(inputs, 32, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') if add_and_check_final('Conv2d_1a_3x3', net): return net, end_points # 147 x 147 x 32 net = slim.conv2d(net, 32, 3, padding=padding, scope='Conv2d_2a_3x3') if add_and_check_final('Conv2d_2a_3x3', net): return net, end_points # 147 x 147 x 64 net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3') if add_and_check_final('Conv2d_2b_3x3', net): return net, end_points # 73 x 73 x 64 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_3a_3x3') if add_and_check_final('MaxPool_3a_3x3', net): return net, end_points # 73 x 73 x 80 net = slim.conv2d(net, 80, 1, padding=padding, scope='Conv2d_3b_1x1') if add_and_check_final('Conv2d_3b_1x1', net): return net, end_points # 71 x 71 x 192 net = slim.conv2d(net, 192, 3, padding=padding, scope='Conv2d_4a_3x3') if add_and_check_final('Conv2d_4a_3x3', net): return net, end_points # 35 x 35 x 192 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_5a_3x3') if add_and_check_final('MaxPool_5a_3x3', net): return net, end_points # 35 x 35 x 320 with tf.variable_scope('Mixed_5b'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 96, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 48, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 64, 5, scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 64, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 96, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 96, 3, scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.avg_pool2d(net, 3, stride=1, padding='SAME', scope='AvgPool_0a_3x3') tower_pool_1 = slim.conv2d(tower_pool, 64, 1, scope='Conv2d_0b_1x1') net = tf.concat( [tower_conv, tower_conv1_1, tower_conv2_2, tower_pool_1], 3) if add_and_check_final('Mixed_5b', net): return net, end_points # TODO(alemi): Register intermediate endpoints net = slim.repeat(net, 10, block35, scale=0.17, activation_fn=activation_fn) # 17 x 17 x 1088 if output_stride == 8, # 33 x 33 x 1088 if output_stride == 16 use_atrous = output_stride == 8 with tf.variable_scope('Mixed_6a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 256, 3, scope='Conv2d_0b_3x3') tower_conv1_2 = slim.conv2d(tower_conv1_1, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_pool = slim.max_pool2d(net, 3, stride=1 if use_atrous else 2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3) if add_and_check_final('Mixed_6a', net): return net, end_points # TODO(alemi): register intermediate endpoints with slim.arg_scope([slim.conv2d], rate=2 if use_atrous else 1): net = slim.repeat(net, 20, block17, scale=0.10, activation_fn=activation_fn) if add_and_check_final('PreAuxLogits', net): return net, end_points if output_stride == 8: # TODO(gpapan): Properly support output_stride for the rest of the net. raise ValueError('output_stride==8 is only supported up to the ' 'PreAuxlogits end_point for now.') # 8 x 8 x 2080 with tf.variable_scope('Mixed_7a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1, 288, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2, 288, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 320, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat( [tower_conv_1, tower_conv1_1, tower_conv2_2, tower_pool], 3) if add_and_check_final('Mixed_7a', net): return net, end_points # TODO(alemi): register intermediate endpoints net = slim.repeat(net, 9, block8, scale=0.20, activation_fn=activation_fn) net = block8(net, activation_fn=None) # 8 x 8 x 1536 net = slim.conv2d(net, 1536, 1, scope='Conv2d_7b_1x1') if add_and_check_final('Conv2d_7b_1x1', net): return net, end_points raise ValueError('final_endpoint (%s) not recognized', final_endpoint) def inception_resnet_v2(inputs, num_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, activation_fn=tf.nn.relu): """Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. Dimension batch_size may be undefined. If create_aux_logits is false, also height and width may be undefined. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. create_aux_logits: Whether to include the auxilliary logits. activation_fn: Activation function for conv2d. Returns: net: the output of the logits layer (if num_classes is a non-zero integer), or the non-dropped-out input to the logits layer (if num_classes is 0 or None). end_points: the set of end_points from the inception model. """ end_points = {} with tf.variable_scope(scope, 'InceptionResnetV2', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_resnet_v2_base(inputs, scope=scope, activation_fn=activation_fn) if create_aux_logits and num_classes: with tf.variable_scope('AuxLogits'): aux = end_points['PreAuxLogits'] aux = slim.avg_pool2d(aux, 5, stride=3, padding='VALID', scope='Conv2d_1a_3x3') aux = slim.conv2d(aux, 128, 1, scope='Conv2d_1b_1x1') aux = slim.conv2d(aux, 768, aux.get_shape()[1:3], padding='VALID', scope='Conv2d_2a_5x5') aux = slim.flatten(aux) aux = slim.fully_connected(aux, num_classes, activation_fn=None, scope='Logits') end_points['AuxLogits'] = aux with tf.variable_scope('Logits'): # TODO(sguada,arnoegw): Consider adding a parameter global_pool which # can be set to False to disable pooling here (as in resnet_*()). kernel_size = net.get_shape()[1:3] if kernel_size.is_fully_defined(): net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a_8x8') else: net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if not num_classes: return net, end_points net = slim.flatten(net) net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='Dropout') end_points['PreLogitsFlatten'] = net logits = slim.fully_connected(net, num_classes, activation_fn=None, scope='Logits') end_points['Logits'] = logits end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions') return logits, end_points inception_resnet_v2.default_image_size = 299 def inception_resnet_v2_arg_scope( weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, activation_fn=tf.nn.relu, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS, batch_norm_scale=False): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. activation_fn: Activation function for conv2d. batch_norm_updates_collections: Collection for the update ops for batch norm. batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the activations in the batch normalization layer. Returns: a arg_scope with the parameters needed for inception_resnet_v2. """ # Set weight_decay for weights in conv2d and fully_connected layers. with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), biases_regularizer=slim.l2_regularizer(weight_decay)): batch_norm_params = { 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'updates_collections': batch_norm_updates_collections, 'fused': None, # Use fused batch norm if possible. 'scale': batch_norm_scale, } # Set activation_fn and parameters for batch_norm. with slim.arg_scope([slim.conv2d], activation_fn=activation_fn, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params) as scope: return scope
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_resnet_v2.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.inception_v4.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception class InceptionTest(tf.test.TestCase): def testBuildLogits(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v4(inputs, num_classes) auxlogits = end_points['AuxLogits'] predictions = end_points['Predictions'] self.assertTrue(auxlogits.op.name.startswith('InceptionV4/AuxLogits')) self.assertListEqual(auxlogits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue(logits.op.name.startswith('InceptionV4/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue(predictions.op.name.startswith( 'InceptionV4/Logits/Predictions')) self.assertListEqual(predictions.get_shape().as_list(), [batch_size, num_classes]) def testBuildPreLogitsNetwork(self): batch_size = 5 height, width = 299, 299 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = inception.inception_v4(inputs, num_classes) self.assertTrue(net.op.name.startswith('InceptionV4/Logits/AvgPool')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 1536]) self.assertFalse('Logits' in end_points) self.assertFalse('Predictions' in end_points) def testBuildWithoutAuxLogits(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, endpoints = inception.inception_v4(inputs, num_classes, create_aux_logits=False) self.assertFalse('AuxLogits' in endpoints) self.assertTrue(logits.op.name.startswith('InceptionV4/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testAllEndPointsShapes(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v4(inputs, num_classes) endpoints_shapes = {'Conv2d_1a_3x3': [batch_size, 149, 149, 32], 'Conv2d_2a_3x3': [batch_size, 147, 147, 32], 'Conv2d_2b_3x3': [batch_size, 147, 147, 64], 'Mixed_3a': [batch_size, 73, 73, 160], 'Mixed_4a': [batch_size, 71, 71, 192], 'Mixed_5a': [batch_size, 35, 35, 384], # 4 x Inception-A blocks 'Mixed_5b': [batch_size, 35, 35, 384], 'Mixed_5c': [batch_size, 35, 35, 384], 'Mixed_5d': [batch_size, 35, 35, 384], 'Mixed_5e': [batch_size, 35, 35, 384], # Reduction-A block 'Mixed_6a': [batch_size, 17, 17, 1024], # 7 x Inception-B blocks 'Mixed_6b': [batch_size, 17, 17, 1024], 'Mixed_6c': [batch_size, 17, 17, 1024], 'Mixed_6d': [batch_size, 17, 17, 1024], 'Mixed_6e': [batch_size, 17, 17, 1024], 'Mixed_6f': [batch_size, 17, 17, 1024], 'Mixed_6g': [batch_size, 17, 17, 1024], 'Mixed_6h': [batch_size, 17, 17, 1024], # Reduction-A block 'Mixed_7a': [batch_size, 8, 8, 1536], # 3 x Inception-C blocks 'Mixed_7b': [batch_size, 8, 8, 1536], 'Mixed_7c': [batch_size, 8, 8, 1536], 'Mixed_7d': [batch_size, 8, 8, 1536], # Logits and predictions 'AuxLogits': [batch_size, num_classes], 'global_pool': [batch_size, 1, 1, 1536], 'PreLogitsFlatten': [batch_size, 1536], 'Logits': [batch_size, num_classes], 'Predictions': [batch_size, num_classes]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testBuildBaseNetwork(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = inception.inception_v4_base(inputs) self.assertTrue(net.op.name.startswith( 'InceptionV4/Mixed_7d')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 8, 8, 1536]) expected_endpoints = [ 'Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'Mixed_3a', 'Mixed_4a', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_5e', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_6f', 'Mixed_6g', 'Mixed_6h', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c', 'Mixed_7d'] self.assertItemsEqual(end_points.keys(), expected_endpoints) for name, op in end_points.items(): self.assertTrue(op.name.startswith('InceptionV4/' + name)) def testBuildOnlyUpToFinalEndpoint(self): batch_size = 5 height, width = 299, 299 all_endpoints = [ 'Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'Mixed_3a', 'Mixed_4a', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_5e', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_6f', 'Mixed_6g', 'Mixed_6h', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c', 'Mixed_7d'] for index, endpoint in enumerate(all_endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = inception.inception_v4_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'InceptionV4/' + endpoint)) self.assertItemsEqual(all_endpoints[:index+1], end_points.keys()) def testVariablesSetDevice(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) # Force all Variables to reside on the device. with tf.variable_scope('on_cpu'), tf.device('/cpu:0'): inception.inception_v4(inputs, num_classes) with tf.variable_scope('on_gpu'), tf.device('/gpu:0'): inception.inception_v4(inputs, num_classes) for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='on_cpu'): self.assertDeviceEqual(v.device, '/cpu:0') for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='on_gpu'): self.assertDeviceEqual(v.device, '/gpu:0') def testHalfSizeImages(self): batch_size = 5 height, width = 150, 150 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v4(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV4/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_7d'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 3, 3, 1536]) def testGlobalPool(self): batch_size = 1 height, width = 350, 400 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v4(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV4/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_7d'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 9, 11, 1536]) def testGlobalPoolUnknownImageShape(self): batch_size = 1 height, width = 350, 400 num_classes = 1000 with self.test_session() as sess: inputs = tf.placeholder(tf.float32, (batch_size, None, None, 3)) logits, end_points = inception.inception_v4( inputs, num_classes, create_aux_logits=False) self.assertTrue(logits.op.name.startswith('InceptionV4/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_7d'] images = tf.random_uniform((batch_size, height, width, 3)) sess.run(tf.global_variables_initializer()) logits_out, pre_pool_out = sess.run([logits, pre_pool], {inputs: images.eval()}) self.assertTupleEqual(logits_out.shape, (batch_size, num_classes)) self.assertTupleEqual(pre_pool_out.shape, (batch_size, 9, 11, 1536)) def testUnknownBatchSize(self): batch_size = 1 height, width = 299, 299 num_classes = 1000 with self.test_session() as sess: inputs = tf.placeholder(tf.float32, (None, height, width, 3)) logits, _ = inception.inception_v4(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV4/Logits')) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEquals(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 299, 299 num_classes = 1000 with self.test_session() as sess: eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = inception.inception_v4(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 150, 150 num_classes = 1000 with self.test_session() as sess: train_inputs = tf.random_uniform((train_batch_size, height, width, 3)) inception.inception_v4(train_inputs, num_classes) eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3)) logits, _ = inception.inception_v4(eval_inputs, num_classes, is_training=False, reuse=True) predictions = tf.argmax(logits, 1) sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (eval_batch_size,)) def testNoBatchNormScaleByDefault(self): height, width = 299, 299 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with tf.contrib.slim.arg_scope(inception.inception_v4_arg_scope()): inception.inception_v4(inputs, num_classes, is_training=False) self.assertEqual(tf.global_variables('.*/BatchNorm/gamma:0$'), []) def testBatchNormScale(self): height, width = 299, 299 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with tf.contrib.slim.arg_scope( inception.inception_v4_arg_scope(batch_norm_scale=True)): inception.inception_v4(inputs, num_classes, is_training=False) gamma_names = set( v.op.name for v in tf.global_variables('.*/BatchNorm/gamma:0$')) self.assertGreater(len(gamma_names), 0) for v in tf.global_variables('.*/BatchNorm/moving_mean:0$'): self.assertIn(v.op.name[:-len('moving_mean')] + 'gamma', gamma_names) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v4_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains model definitions for versions of the Oxford VGG network. These model definitions were introduced in the following technical report: Very Deep Convolutional Networks For Large-Scale Image Recognition Karen Simonyan and Andrew Zisserman arXiv technical report, 2015 PDF: http://arxiv.org/pdf/1409.1556.pdf ILSVRC 2014 Slides: http://www.robots.ox.ac.uk/~karen/pdf/ILSVRC_2014.pdf CC-BY-4.0 More information can be obtained from the VGG website: www.robots.ox.ac.uk/~vgg/research/very_deep/ Usage: with slim.arg_scope(vgg.vgg_arg_scope()): outputs, end_points = vgg.vgg_a(inputs) with slim.arg_scope(vgg.vgg_arg_scope()): outputs, end_points = vgg.vgg_16(inputs) @@vgg_a @@vgg_16 @@vgg_19 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim def vgg_arg_scope(weight_decay=0.0005): """Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope. """ with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(weight_decay), biases_initializer=tf.zeros_initializer()): with slim.arg_scope([slim.conv2d], padding='SAME') as arg_sc: return arg_sc def vgg_a(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_a', fc_conv_padding='VALID', global_pool=False): """Oxford Net VGG 11-Layers version A Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. fc_conv_padding: the type of padding to use for the fully connected layer that is implemented as a convolutional layer. Use 'SAME' padding if you are applying the network in a fully convolutional manner and want to get a prediction map downsampled by a factor of 32 as an output. Otherwise, the output prediction map will be (input / 32) - 6 in case of 'VALID' padding. global_pool: Optional boolean flag. If True, the input to the classification layer is avgpooled to size 1x1, for any input size. (This is not part of the original VGG architecture.) Returns: net: the output of the logits layer (if num_classes is a non-zero integer), or the input to the logits layer (if num_classes is 0 or None). end_points: a dict of tensors with intermediate activations. """ with tf.variable_scope(scope, 'vgg_a', [inputs]) as sc: end_points_collection = sc.original_name_scope + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d. with slim.arg_scope([slim.conv2d, slim.max_pool2d], outputs_collections=end_points_collection): net = slim.repeat(inputs, 1, slim.conv2d, 64, [3, 3], scope='conv1') net = slim.max_pool2d(net, [2, 2], scope='pool1') net = slim.repeat(net, 1, slim.conv2d, 128, [3, 3], scope='conv2') net = slim.max_pool2d(net, [2, 2], scope='pool2') net = slim.repeat(net, 2, slim.conv2d, 256, [3, 3], scope='conv3') net = slim.max_pool2d(net, [2, 2], scope='pool3') net = slim.repeat(net, 2, slim.conv2d, 512, [3, 3], scope='conv4') net = slim.max_pool2d(net, [2, 2], scope='pool4') net = slim.repeat(net, 2, slim.conv2d, 512, [3, 3], scope='conv5') net = slim.max_pool2d(net, [2, 2], scope='pool5') # Use conv2d instead of fully_connected layers. net = slim.conv2d(net, 4096, [7, 7], padding=fc_conv_padding, scope='fc6') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = slim.conv2d(net, 4096, [1, 1], scope='fc7') # Convert end_points_collection into a end_point dict. end_points = slim.utils.convert_collection_to_dict(end_points_collection) if global_pool: net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if num_classes: net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='fc8') if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='fc8/squeezed') end_points[sc.name + '/fc8'] = net return net, end_points vgg_a.default_image_size = 224 def vgg_16(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_16', fc_conv_padding='VALID', global_pool=False): """Oxford Net VGG 16-Layers version D Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. fc_conv_padding: the type of padding to use for the fully connected layer that is implemented as a convolutional layer. Use 'SAME' padding if you are applying the network in a fully convolutional manner and want to get a prediction map downsampled by a factor of 32 as an output. Otherwise, the output prediction map will be (input / 32) - 6 in case of 'VALID' padding. global_pool: Optional boolean flag. If True, the input to the classification layer is avgpooled to size 1x1, for any input size. (This is not part of the original VGG architecture.) Returns: net: the output of the logits layer (if num_classes is a non-zero integer), or the input to the logits layer (if num_classes is 0 or None). end_points: a dict of tensors with intermediate activations. """ with tf.variable_scope(scope, 'vgg_16', [inputs]) as sc: end_points_collection = sc.original_name_scope + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d. with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d], outputs_collections=end_points_collection): net = slim.repeat(inputs, 2, slim.conv2d, 64, [3, 3], scope='conv1') net = slim.max_pool2d(net, [2, 2], scope='pool1') net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2') net = slim.max_pool2d(net, [2, 2], scope='pool2') net = slim.repeat(net, 3, slim.conv2d, 256, [3, 3], scope='conv3') net = slim.max_pool2d(net, [2, 2], scope='pool3') net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv4') net = slim.max_pool2d(net, [2, 2], scope='pool4') net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv5') net = slim.max_pool2d(net, [2, 2], scope='pool5') # Use conv2d instead of fully_connected layers. net = slim.conv2d(net, 4096, [7, 7], padding=fc_conv_padding, scope='fc6') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = slim.conv2d(net, 4096, [1, 1], scope='fc7') # Convert end_points_collection into a end_point dict. end_points = slim.utils.convert_collection_to_dict(end_points_collection) if global_pool: net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if num_classes: net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='fc8') if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='fc8/squeezed') end_points[sc.name + '/fc8'] = net return net, end_points vgg_16.default_image_size = 224 def vgg_19(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19', fc_conv_padding='VALID', global_pool=False): """Oxford Net VGG 19-Layers version E Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. fc_conv_padding: the type of padding to use for the fully connected layer that is implemented as a convolutional layer. Use 'SAME' padding if you are applying the network in a fully convolutional manner and want to get a prediction map downsampled by a factor of 32 as an output. Otherwise, the output prediction map will be (input / 32) - 6 in case of 'VALID' padding. global_pool: Optional boolean flag. If True, the input to the classification layer is avgpooled to size 1x1, for any input size. (This is not part of the original VGG architecture.) Returns: net: the output of the logits layer (if num_classes is a non-zero integer), or the non-dropped-out input to the logits layer (if num_classes is 0 or None). end_points: a dict of tensors with intermediate activations. """ with tf.variable_scope(scope, 'vgg_19', [inputs]) as sc: end_points_collection = sc.original_name_scope + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d. with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d], outputs_collections=end_points_collection): net = slim.repeat(inputs, 2, slim.conv2d, 64, [3, 3], scope='conv1') net = slim.max_pool2d(net, [2, 2], scope='pool1') net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2') net = slim.max_pool2d(net, [2, 2], scope='pool2') net = slim.repeat(net, 4, slim.conv2d, 256, [3, 3], scope='conv3') net = slim.max_pool2d(net, [2, 2], scope='pool3') net = slim.repeat(net, 4, slim.conv2d, 512, [3, 3], scope='conv4') net = slim.max_pool2d(net, [2, 2], scope='pool4') net = slim.repeat(net, 4, slim.conv2d, 512, [3, 3], scope='conv5') net = slim.max_pool2d(net, [2, 2], scope='pool5') # Use conv2d instead of fully_connected layers. net = slim.conv2d(net, 4096, [7, 7], padding=fc_conv_padding, scope='fc6') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = slim.conv2d(net, 4096, [1, 1], scope='fc7') # Convert end_points_collection into a end_point dict. end_points = slim.utils.convert_collection_to_dict(end_points_collection) if global_pool: net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if num_classes: net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='fc8') if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='fc8/squeezed') end_points[sc.name + '/fc8'] = net return net, end_points vgg_19.default_image_size = 224 # Alias vgg_d = vgg_16 vgg_e = vgg_19
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/vgg.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Validate mobilenet_v1 with options for quantization.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from datasets import dataset_factory from nets import mobilenet_v1 from preprocessing import preprocessing_factory slim = tf.contrib.slim flags = tf.app.flags flags.DEFINE_string('master', '', 'Session master') flags.DEFINE_integer('batch_size', 250, 'Batch size') flags.DEFINE_integer('num_classes', 1001, 'Number of classes to distinguish') flags.DEFINE_integer('num_examples', 50000, 'Number of examples to evaluate') flags.DEFINE_integer('image_size', 224, 'Input image resolution') flags.DEFINE_float('depth_multiplier', 1.0, 'Depth multiplier for mobilenet') flags.DEFINE_bool('quantize', False, 'Quantize training') flags.DEFINE_string('checkpoint_dir', '', 'The directory for checkpoints') flags.DEFINE_string('eval_dir', '', 'Directory for writing eval event logs') flags.DEFINE_string('dataset_dir', '', 'Location of dataset') FLAGS = flags.FLAGS def imagenet_input(is_training): """Data reader for imagenet. Reads in imagenet data and performs pre-processing on the images. Args: is_training: bool specifying if train or validation dataset is needed. Returns: A batch of images and labels. """ if is_training: dataset = dataset_factory.get_dataset('imagenet', 'train', FLAGS.dataset_dir) else: dataset = dataset_factory.get_dataset('imagenet', 'validation', FLAGS.dataset_dir) provider = slim.dataset_data_provider.DatasetDataProvider( dataset, shuffle=is_training, common_queue_capacity=2 * FLAGS.batch_size, common_queue_min=FLAGS.batch_size) [image, label] = provider.get(['image', 'label']) image_preprocessing_fn = preprocessing_factory.get_preprocessing( 'mobilenet_v1', is_training=is_training) image = image_preprocessing_fn(image, FLAGS.image_size, FLAGS.image_size) images, labels = tf.train.batch( tensors=[image, label], batch_size=FLAGS.batch_size, num_threads=4, capacity=5 * FLAGS.batch_size) return images, labels def metrics(logits, labels): """Specify the metrics for eval. Args: logits: Logits output from the graph. labels: Ground truth labels for inputs. Returns: Eval Op for the graph. """ labels = tf.squeeze(labels) names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ 'Accuracy': tf.metrics.accuracy(tf.argmax(logits, 1), labels), 'Recall_5': tf.metrics.recall_at_k(labels, logits, 5), }) for name, value in names_to_values.iteritems(): slim.summaries.add_scalar_summary( value, name, prefix='eval', print_summary=True) return names_to_updates.values() def build_model(): """Build the mobilenet_v1 model for evaluation. Returns: g: graph with rewrites after insertion of quantization ops and batch norm folding. eval_ops: eval ops for inference. variables_to_restore: List of variables to restore from checkpoint. """ g = tf.Graph() with g.as_default(): inputs, labels = imagenet_input(is_training=False) scope = mobilenet_v1.mobilenet_v1_arg_scope( is_training=False, weight_decay=0.0) with slim.arg_scope(scope): logits, _ = mobilenet_v1.mobilenet_v1( inputs, is_training=False, depth_multiplier=FLAGS.depth_multiplier, num_classes=FLAGS.num_classes) if FLAGS.quantize: tf.contrib.quantize.create_eval_graph() eval_ops = metrics(logits, labels) return g, eval_ops def eval_model(): """Evaluates mobilenet_v1.""" g, eval_ops = build_model() with g.as_default(): num_batches = math.ceil(FLAGS.num_examples / float(FLAGS.batch_size)) slim.evaluation.evaluate_once( FLAGS.master, FLAGS.checkpoint_dir, logdir=FLAGS.eval_dir, num_evals=num_batches, eval_op=eval_ops) def main(unused_arg): eval_model() if __name__ == '__main__': tf.app.run(main)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet_v1_eval.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition for inception v1 classification network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception_utils slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) def inception_v1_base(inputs, final_endpoint='Mixed_5c', scope='InceptionV1'): """Defines the Inception V1 base architecture. This architecture is defined in: Going deeper with convolutions Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich. http://arxiv.org/pdf/1409.4842v1.pdf. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] scope: Optional variable_scope. Returns: A dictionary from components of the network to the corresponding activation. Raises: ValueError: if final_endpoint is not set to one of the predefined values. """ end_points = {} with tf.variable_scope(scope, 'InceptionV1', [inputs]): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_initializer=trunc_normal(0.01)): with slim.arg_scope([slim.conv2d, slim.max_pool2d], stride=1, padding='SAME'): end_point = 'Conv2d_1a_7x7' net = slim.conv2d(inputs, 64, [7, 7], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_2a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Conv2d_2b_1x1' net = slim.conv2d(net, 64, [1, 1], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Conv2d_2c_3x3' net = slim.conv2d(net, 192, [3, 3], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_3a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_3b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 96, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 128, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 16, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 32, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 32, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_3c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 192, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_4a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 96, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 208, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 16, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 48, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 112, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 224, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 24, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 64, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 256, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 24, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 64, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4e' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 112, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 144, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 288, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 64, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_4f' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 256, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 320, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 128, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_5a_2x2' net = slim.max_pool2d(net, [2, 2], stride=2, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_5b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 256, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 320, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 32, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 128, [3, 3], scope='Conv2d_0a_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_5c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 384, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 384, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, 48, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 128, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1') net = tf.concat( axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if final_endpoint == end_point: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def inception_v1(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, scope='InceptionV1', global_pool=False): """Defines the Inception V1 architecture. This architecture is defined in: Going deeper with convolutions Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich. http://arxiv.org/pdf/1409.4842v1.pdf. The default image size used to train this network is 224x224. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. is_training: whether is training or not. dropout_keep_prob: the percentage of activation values that are retained. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. global_pool: Optional boolean flag to control the avgpooling before the logits layer. If false or unset, pooling is done with a fixed window that reduces default-sized inputs to 1x1, while larger inputs lead to larger outputs. If true, any input size is pooled down to 1x1. Returns: net: a Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped-out input to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. """ # Final pooling and prediction with tf.variable_scope(scope, 'InceptionV1', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_v1_base(inputs, scope=scope) with tf.variable_scope('Logits'): if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net else: # Pooling with a fixed kernel size. net = slim.avg_pool2d(net, [7, 7], stride=1, scope='AvgPool_0a_7x7') end_points['AvgPool_0a_7x7'] = net if not num_classes: return net, end_points net = slim.dropout(net, dropout_keep_prob, scope='Dropout_0b') logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_0c_1x1') if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points inception_v1.default_image_size = 224 inception_v1_arg_scope = inception_utils.inception_arg_scope
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v1.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.inception_resnet_v2.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception class InceptionTest(tf.test.TestCase): def testBuildLogits(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, endpoints = inception.inception_resnet_v2(inputs, num_classes) self.assertTrue('AuxLogits' in endpoints) auxlogits = endpoints['AuxLogits'] self.assertTrue( auxlogits.op.name.startswith('InceptionResnetV2/AuxLogits')) self.assertListEqual(auxlogits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue(logits.op.name.startswith('InceptionResnetV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testBuildWithoutAuxLogits(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, endpoints = inception.inception_resnet_v2(inputs, num_classes, create_aux_logits=False) self.assertTrue('AuxLogits' not in endpoints) self.assertTrue(logits.op.name.startswith('InceptionResnetV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testBuildNoClasses(self): batch_size = 5 height, width = 299, 299 num_classes = None with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) net, endpoints = inception.inception_resnet_v2(inputs, num_classes) self.assertTrue('AuxLogits' not in endpoints) self.assertTrue('Logits' not in endpoints) self.assertTrue( net.op.name.startswith('InceptionResnetV2/Logits/AvgPool')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 1536]) def testBuildEndPoints(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_resnet_v2(inputs, num_classes) self.assertTrue('Logits' in end_points) logits = end_points['Logits'] self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('AuxLogits' in end_points) aux_logits = end_points['AuxLogits'] self.assertListEqual(aux_logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_7b_1x1'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 8, 8, 1536]) def testBuildBaseNetwork(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = inception.inception_resnet_v2_base(inputs) self.assertTrue(net.op.name.startswith('InceptionResnetV2/Conv2d_7b_1x1')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 8, 8, 1536]) expected_endpoints = ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpoint(self): batch_size = 5 height, width = 299, 299 endpoints = ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = inception.inception_resnet_v2_base( inputs, final_endpoint=endpoint) if endpoint != 'PreAuxLogits': self.assertTrue(out_tensor.op.name.startswith( 'InceptionResnetV2/' + endpoint)) self.assertItemsEqual(endpoints[:index+1], end_points.keys()) def testBuildAndCheckAllEndPointsUptoPreAuxLogits(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_resnet_v2_base( inputs, final_endpoint='PreAuxLogits') endpoints_shapes = {'Conv2d_1a_3x3': [5, 149, 149, 32], 'Conv2d_2a_3x3': [5, 147, 147, 32], 'Conv2d_2b_3x3': [5, 147, 147, 64], 'MaxPool_3a_3x3': [5, 73, 73, 64], 'Conv2d_3b_1x1': [5, 73, 73, 80], 'Conv2d_4a_3x3': [5, 71, 71, 192], 'MaxPool_5a_3x3': [5, 35, 35, 192], 'Mixed_5b': [5, 35, 35, 320], 'Mixed_6a': [5, 17, 17, 1088], 'PreAuxLogits': [5, 17, 17, 1088] } self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testBuildAndCheckAllEndPointsUptoPreAuxLogitsWithAlignedFeatureMaps(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_resnet_v2_base( inputs, final_endpoint='PreAuxLogits', align_feature_maps=True) endpoints_shapes = {'Conv2d_1a_3x3': [5, 150, 150, 32], 'Conv2d_2a_3x3': [5, 150, 150, 32], 'Conv2d_2b_3x3': [5, 150, 150, 64], 'MaxPool_3a_3x3': [5, 75, 75, 64], 'Conv2d_3b_1x1': [5, 75, 75, 80], 'Conv2d_4a_3x3': [5, 75, 75, 192], 'MaxPool_5a_3x3': [5, 38, 38, 192], 'Mixed_5b': [5, 38, 38, 320], 'Mixed_6a': [5, 19, 19, 1088], 'PreAuxLogits': [5, 19, 19, 1088] } self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testBuildAndCheckAllEndPointsUptoPreAuxLogitsWithOutputStrideEight(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_resnet_v2_base( inputs, final_endpoint='PreAuxLogits', output_stride=8) endpoints_shapes = {'Conv2d_1a_3x3': [5, 149, 149, 32], 'Conv2d_2a_3x3': [5, 147, 147, 32], 'Conv2d_2b_3x3': [5, 147, 147, 64], 'MaxPool_3a_3x3': [5, 73, 73, 64], 'Conv2d_3b_1x1': [5, 73, 73, 80], 'Conv2d_4a_3x3': [5, 71, 71, 192], 'MaxPool_5a_3x3': [5, 35, 35, 192], 'Mixed_5b': [5, 35, 35, 320], 'Mixed_6a': [5, 33, 33, 1088], 'PreAuxLogits': [5, 33, 33, 1088] } self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testVariablesSetDevice(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) # Force all Variables to reside on the device. with tf.variable_scope('on_cpu'), tf.device('/cpu:0'): inception.inception_resnet_v2(inputs, num_classes) with tf.variable_scope('on_gpu'), tf.device('/gpu:0'): inception.inception_resnet_v2(inputs, num_classes) for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='on_cpu'): self.assertDeviceEqual(v.device, '/cpu:0') for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='on_gpu'): self.assertDeviceEqual(v.device, '/gpu:0') def testHalfSizeImages(self): batch_size = 5 height, width = 150, 150 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_resnet_v2(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionResnetV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_7b_1x1'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 3, 3, 1536]) def testGlobalPool(self): batch_size = 1 height, width = 330, 400 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_resnet_v2(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionResnetV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_7b_1x1'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 8, 11, 1536]) def testGlobalPoolUnknownImageShape(self): batch_size = 1 height, width = 330, 400 num_classes = 1000 with self.test_session() as sess: inputs = tf.placeholder(tf.float32, (batch_size, None, None, 3)) logits, end_points = inception.inception_resnet_v2( inputs, num_classes, create_aux_logits=False) self.assertTrue(logits.op.name.startswith('InceptionResnetV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_7b_1x1'] images = tf.random_uniform((batch_size, height, width, 3)) sess.run(tf.global_variables_initializer()) logits_out, pre_pool_out = sess.run([logits, pre_pool], {inputs: images.eval()}) self.assertTupleEqual(logits_out.shape, (batch_size, num_classes)) self.assertTupleEqual(pre_pool_out.shape, (batch_size, 8, 11, 1536)) def testUnknownBatchSize(self): batch_size = 1 height, width = 299, 299 num_classes = 1000 with self.test_session() as sess: inputs = tf.placeholder(tf.float32, (None, height, width, 3)) logits, _ = inception.inception_resnet_v2(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionResnetV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEquals(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 299, 299 num_classes = 1000 with self.test_session() as sess: eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = inception.inception_resnet_v2(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 150, 150 num_classes = 1000 with self.test_session() as sess: train_inputs = tf.random_uniform((train_batch_size, height, width, 3)) inception.inception_resnet_v2(train_inputs, num_classes) eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3)) logits, _ = inception.inception_resnet_v2(eval_inputs, num_classes, is_training=False, reuse=True) predictions = tf.argmax(logits, 1) sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (eval_batch_size,)) def testNoBatchNormScaleByDefault(self): height, width = 299, 299 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with tf.contrib.slim.arg_scope(inception.inception_resnet_v2_arg_scope()): inception.inception_resnet_v2(inputs, num_classes, is_training=False) self.assertEqual(tf.global_variables('.*/BatchNorm/gamma:0$'), []) def testBatchNormScale(self): height, width = 299, 299 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with tf.contrib.slim.arg_scope( inception.inception_resnet_v2_arg_scope(batch_norm_scale=True)): inception.inception_resnet_v2(inputs, num_classes, is_training=False) gamma_names = set( v.op.name for v in tf.global_variables('.*/BatchNorm/gamma:0$')) self.assertGreater(len(gamma_names), 0) for v in tf.global_variables('.*/BatchNorm/moving_mean:0$'): self.assertIn(v.op.name[:-len('moving_mean')] + 'gamma', gamma_names) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_resnet_v2_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nets.vgg.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import vgg slim = tf.contrib.slim class VGGATest(tf.test.TestCase): def testBuild(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(inputs, num_classes) self.assertEquals(logits.op.name, 'vgg_a/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'vgg_a/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 2, 2, num_classes]) def testGlobalPool(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(inputs, num_classes, spatial_squeeze=False, global_pool=True) self.assertEquals(logits.op.name, 'vgg_a/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 1, 1, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = vgg.vgg_a(inputs, num_classes) expected_names = ['vgg_a/conv1/conv1_1', 'vgg_a/pool1', 'vgg_a/conv2/conv2_1', 'vgg_a/pool2', 'vgg_a/conv3/conv3_1', 'vgg_a/conv3/conv3_2', 'vgg_a/pool3', 'vgg_a/conv4/conv4_1', 'vgg_a/conv4/conv4_2', 'vgg_a/pool4', 'vgg_a/conv5/conv5_1', 'vgg_a/conv5/conv5_2', 'vgg_a/pool5', 'vgg_a/fc6', 'vgg_a/fc7', 'vgg_a/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testNoClasses(self): batch_size = 5 height, width = 224, 224 num_classes = None with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = vgg.vgg_a(inputs, num_classes) expected_names = ['vgg_a/conv1/conv1_1', 'vgg_a/pool1', 'vgg_a/conv2/conv2_1', 'vgg_a/pool2', 'vgg_a/conv3/conv3_1', 'vgg_a/conv3/conv3_2', 'vgg_a/pool3', 'vgg_a/conv4/conv4_1', 'vgg_a/conv4/conv4_2', 'vgg_a/pool4', 'vgg_a/conv5/conv5_1', 'vgg_a/conv5/conv5_2', 'vgg_a/pool5', 'vgg_a/fc6', 'vgg_a/fc7', ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) self.assertTrue(net.op.name.startswith('vgg_a/fc7')) def testModelVariables(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) vgg.vgg_a(inputs, num_classes) expected_names = ['vgg_a/conv1/conv1_1/weights', 'vgg_a/conv1/conv1_1/biases', 'vgg_a/conv2/conv2_1/weights', 'vgg_a/conv2/conv2_1/biases', 'vgg_a/conv3/conv3_1/weights', 'vgg_a/conv3/conv3_1/biases', 'vgg_a/conv3/conv3_2/weights', 'vgg_a/conv3/conv3_2/biases', 'vgg_a/conv4/conv4_1/weights', 'vgg_a/conv4/conv4_1/biases', 'vgg_a/conv4/conv4_2/weights', 'vgg_a/conv4/conv4_2/biases', 'vgg_a/conv5/conv5_1/weights', 'vgg_a/conv5/conv5_1/biases', 'vgg_a/conv5/conv5_2/weights', 'vgg_a/conv5/conv5_2/biases', 'vgg_a/fc6/weights', 'vgg_a/fc6/biases', 'vgg_a/fc7/weights', 'vgg_a/fc7/biases', 'vgg_a/fc8/weights', 'vgg_a/fc8/biases', ] model_variables = [v.op.name for v in slim.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.test_session(): eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = tf.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 224, 224 eval_height, eval_width = 256, 256 num_classes = 1000 with self.test_session(): train_inputs = tf.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = vgg.vgg_a(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) tf.get_variable_scope().reuse_variables() eval_inputs = tf.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = vgg.vgg_a(eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 2, 2, num_classes]) logits = tf.reduce_mean(logits, [1, 2]) predictions = tf.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 224, 224 with self.test_session() as sess: inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_a(inputs) sess.run(tf.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) class VGG16Test(tf.test.TestCase): def testBuild(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(inputs, num_classes) self.assertEquals(logits.op.name, 'vgg_16/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'vgg_16/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 2, 2, num_classes]) def testGlobalPool(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(inputs, num_classes, spatial_squeeze=False, global_pool=True) self.assertEquals(logits.op.name, 'vgg_16/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 1, 1, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = vgg.vgg_16(inputs, num_classes) expected_names = ['vgg_16/conv1/conv1_1', 'vgg_16/conv1/conv1_2', 'vgg_16/pool1', 'vgg_16/conv2/conv2_1', 'vgg_16/conv2/conv2_2', 'vgg_16/pool2', 'vgg_16/conv3/conv3_1', 'vgg_16/conv3/conv3_2', 'vgg_16/conv3/conv3_3', 'vgg_16/pool3', 'vgg_16/conv4/conv4_1', 'vgg_16/conv4/conv4_2', 'vgg_16/conv4/conv4_3', 'vgg_16/pool4', 'vgg_16/conv5/conv5_1', 'vgg_16/conv5/conv5_2', 'vgg_16/conv5/conv5_3', 'vgg_16/pool5', 'vgg_16/fc6', 'vgg_16/fc7', 'vgg_16/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testNoClasses(self): batch_size = 5 height, width = 224, 224 num_classes = None with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = vgg.vgg_16(inputs, num_classes) expected_names = ['vgg_16/conv1/conv1_1', 'vgg_16/conv1/conv1_2', 'vgg_16/pool1', 'vgg_16/conv2/conv2_1', 'vgg_16/conv2/conv2_2', 'vgg_16/pool2', 'vgg_16/conv3/conv3_1', 'vgg_16/conv3/conv3_2', 'vgg_16/conv3/conv3_3', 'vgg_16/pool3', 'vgg_16/conv4/conv4_1', 'vgg_16/conv4/conv4_2', 'vgg_16/conv4/conv4_3', 'vgg_16/pool4', 'vgg_16/conv5/conv5_1', 'vgg_16/conv5/conv5_2', 'vgg_16/conv5/conv5_3', 'vgg_16/pool5', 'vgg_16/fc6', 'vgg_16/fc7', ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) self.assertTrue(net.op.name.startswith('vgg_16/fc7')) def testModelVariables(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) vgg.vgg_16(inputs, num_classes) expected_names = ['vgg_16/conv1/conv1_1/weights', 'vgg_16/conv1/conv1_1/biases', 'vgg_16/conv1/conv1_2/weights', 'vgg_16/conv1/conv1_2/biases', 'vgg_16/conv2/conv2_1/weights', 'vgg_16/conv2/conv2_1/biases', 'vgg_16/conv2/conv2_2/weights', 'vgg_16/conv2/conv2_2/biases', 'vgg_16/conv3/conv3_1/weights', 'vgg_16/conv3/conv3_1/biases', 'vgg_16/conv3/conv3_2/weights', 'vgg_16/conv3/conv3_2/biases', 'vgg_16/conv3/conv3_3/weights', 'vgg_16/conv3/conv3_3/biases', 'vgg_16/conv4/conv4_1/weights', 'vgg_16/conv4/conv4_1/biases', 'vgg_16/conv4/conv4_2/weights', 'vgg_16/conv4/conv4_2/biases', 'vgg_16/conv4/conv4_3/weights', 'vgg_16/conv4/conv4_3/biases', 'vgg_16/conv5/conv5_1/weights', 'vgg_16/conv5/conv5_1/biases', 'vgg_16/conv5/conv5_2/weights', 'vgg_16/conv5/conv5_2/biases', 'vgg_16/conv5/conv5_3/weights', 'vgg_16/conv5/conv5_3/biases', 'vgg_16/fc6/weights', 'vgg_16/fc6/biases', 'vgg_16/fc7/weights', 'vgg_16/fc7/biases', 'vgg_16/fc8/weights', 'vgg_16/fc8/biases', ] model_variables = [v.op.name for v in slim.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.test_session(): eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = tf.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 224, 224 eval_height, eval_width = 256, 256 num_classes = 1000 with self.test_session(): train_inputs = tf.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = vgg.vgg_16(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) tf.get_variable_scope().reuse_variables() eval_inputs = tf.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = vgg.vgg_16(eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 2, 2, num_classes]) logits = tf.reduce_mean(logits, [1, 2]) predictions = tf.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 224, 224 with self.test_session() as sess: inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_16(inputs) sess.run(tf.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) class VGG19Test(tf.test.TestCase): def testBuild(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(inputs, num_classes) self.assertEquals(logits.op.name, 'vgg_19/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'vgg_19/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 2, 2, num_classes]) def testGlobalPool(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(inputs, num_classes, spatial_squeeze=False, global_pool=True) self.assertEquals(logits.op.name, 'vgg_19/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 1, 1, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = vgg.vgg_19(inputs, num_classes) expected_names = [ 'vgg_19/conv1/conv1_1', 'vgg_19/conv1/conv1_2', 'vgg_19/pool1', 'vgg_19/conv2/conv2_1', 'vgg_19/conv2/conv2_2', 'vgg_19/pool2', 'vgg_19/conv3/conv3_1', 'vgg_19/conv3/conv3_2', 'vgg_19/conv3/conv3_3', 'vgg_19/conv3/conv3_4', 'vgg_19/pool3', 'vgg_19/conv4/conv4_1', 'vgg_19/conv4/conv4_2', 'vgg_19/conv4/conv4_3', 'vgg_19/conv4/conv4_4', 'vgg_19/pool4', 'vgg_19/conv5/conv5_1', 'vgg_19/conv5/conv5_2', 'vgg_19/conv5/conv5_3', 'vgg_19/conv5/conv5_4', 'vgg_19/pool5', 'vgg_19/fc6', 'vgg_19/fc7', 'vgg_19/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testNoClasses(self): batch_size = 5 height, width = 224, 224 num_classes = None with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = vgg.vgg_19(inputs, num_classes) expected_names = [ 'vgg_19/conv1/conv1_1', 'vgg_19/conv1/conv1_2', 'vgg_19/pool1', 'vgg_19/conv2/conv2_1', 'vgg_19/conv2/conv2_2', 'vgg_19/pool2', 'vgg_19/conv3/conv3_1', 'vgg_19/conv3/conv3_2', 'vgg_19/conv3/conv3_3', 'vgg_19/conv3/conv3_4', 'vgg_19/pool3', 'vgg_19/conv4/conv4_1', 'vgg_19/conv4/conv4_2', 'vgg_19/conv4/conv4_3', 'vgg_19/conv4/conv4_4', 'vgg_19/pool4', 'vgg_19/conv5/conv5_1', 'vgg_19/conv5/conv5_2', 'vgg_19/conv5/conv5_3', 'vgg_19/conv5/conv5_4', 'vgg_19/pool5', 'vgg_19/fc6', 'vgg_19/fc7', ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) self.assertTrue(net.op.name.startswith('vgg_19/fc7')) def testModelVariables(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) vgg.vgg_19(inputs, num_classes) expected_names = [ 'vgg_19/conv1/conv1_1/weights', 'vgg_19/conv1/conv1_1/biases', 'vgg_19/conv1/conv1_2/weights', 'vgg_19/conv1/conv1_2/biases', 'vgg_19/conv2/conv2_1/weights', 'vgg_19/conv2/conv2_1/biases', 'vgg_19/conv2/conv2_2/weights', 'vgg_19/conv2/conv2_2/biases', 'vgg_19/conv3/conv3_1/weights', 'vgg_19/conv3/conv3_1/biases', 'vgg_19/conv3/conv3_2/weights', 'vgg_19/conv3/conv3_2/biases', 'vgg_19/conv3/conv3_3/weights', 'vgg_19/conv3/conv3_3/biases', 'vgg_19/conv3/conv3_4/weights', 'vgg_19/conv3/conv3_4/biases', 'vgg_19/conv4/conv4_1/weights', 'vgg_19/conv4/conv4_1/biases', 'vgg_19/conv4/conv4_2/weights', 'vgg_19/conv4/conv4_2/biases', 'vgg_19/conv4/conv4_3/weights', 'vgg_19/conv4/conv4_3/biases', 'vgg_19/conv4/conv4_4/weights', 'vgg_19/conv4/conv4_4/biases', 'vgg_19/conv5/conv5_1/weights', 'vgg_19/conv5/conv5_1/biases', 'vgg_19/conv5/conv5_2/weights', 'vgg_19/conv5/conv5_2/biases', 'vgg_19/conv5/conv5_3/weights', 'vgg_19/conv5/conv5_3/biases', 'vgg_19/conv5/conv5_4/weights', 'vgg_19/conv5/conv5_4/biases', 'vgg_19/fc6/weights', 'vgg_19/fc6/biases', 'vgg_19/fc7/weights', 'vgg_19/fc7/biases', 'vgg_19/fc8/weights', 'vgg_19/fc8/biases', ] model_variables = [v.op.name for v in slim.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.test_session(): eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = tf.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 224, 224 eval_height, eval_width = 256, 256 num_classes = 1000 with self.test_session(): train_inputs = tf.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = vgg.vgg_19(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) tf.get_variable_scope().reuse_variables() eval_inputs = tf.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = vgg.vgg_19(eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 2, 2, num_classes]) logits = tf.reduce_mean(logits, [1, 2]) predictions = tf.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 224, 224 with self.test_session() as sess: inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = vgg.vgg_19(inputs) sess.run(tf.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/vgg_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nets.resnet_v1.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nets import resnet_utils from nets import resnet_v1 slim = tf.contrib.slim def create_test_input(batch_size, height, width, channels): """Create test input tensor. Args: batch_size: The number of images per batch or `None` if unknown. height: The height of each image or `None` if unknown. width: The width of each image or `None` if unknown. channels: The number of channels per image or `None` if unknown. Returns: Either a placeholder `Tensor` of dimension [batch_size, height, width, channels] if any of the inputs are `None` or a constant `Tensor` with the mesh grid values along the spatial dimensions. """ if None in [batch_size, height, width, channels]: return tf.placeholder(tf.float32, (batch_size, height, width, channels)) else: return tf.to_float( np.tile( np.reshape( np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width]), [1, height, width, 1]), [batch_size, 1, 1, channels])) class ResnetUtilsTest(tf.test.TestCase): def testSubsampleThreeByThree(self): x = tf.reshape(tf.to_float(tf.range(9)), [1, 3, 3, 1]) x = resnet_utils.subsample(x, 2) expected = tf.reshape(tf.constant([0, 2, 6, 8]), [1, 2, 2, 1]) with self.test_session(): self.assertAllClose(x.eval(), expected.eval()) def testSubsampleFourByFour(self): x = tf.reshape(tf.to_float(tf.range(16)), [1, 4, 4, 1]) x = resnet_utils.subsample(x, 2) expected = tf.reshape(tf.constant([0, 2, 8, 10]), [1, 2, 2, 1]) with self.test_session(): self.assertAllClose(x.eval(), expected.eval()) def testConv2DSameEven(self): n, n2 = 4, 2 # Input image. x = create_test_input(1, n, n, 1) # Convolution kernel. w = create_test_input(1, 3, 3, 1) w = tf.reshape(w, [3, 3, 1, 1]) tf.get_variable('Conv/weights', initializer=w) tf.get_variable('Conv/biases', initializer=tf.zeros([1])) tf.get_variable_scope().reuse_variables() y1 = slim.conv2d(x, 1, [3, 3], stride=1, scope='Conv') y1_expected = tf.to_float([[14, 28, 43, 26], [28, 48, 66, 37], [43, 66, 84, 46], [26, 37, 46, 22]]) y1_expected = tf.reshape(y1_expected, [1, n, n, 1]) y2 = resnet_utils.subsample(y1, 2) y2_expected = tf.to_float([[14, 43], [43, 84]]) y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1]) y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv') y3_expected = y2_expected y4 = slim.conv2d(x, 1, [3, 3], stride=2, scope='Conv') y4_expected = tf.to_float([[48, 37], [37, 22]]) y4_expected = tf.reshape(y4_expected, [1, n2, n2, 1]) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) self.assertAllClose(y1.eval(), y1_expected.eval()) self.assertAllClose(y2.eval(), y2_expected.eval()) self.assertAllClose(y3.eval(), y3_expected.eval()) self.assertAllClose(y4.eval(), y4_expected.eval()) def testConv2DSameOdd(self): n, n2 = 5, 3 # Input image. x = create_test_input(1, n, n, 1) # Convolution kernel. w = create_test_input(1, 3, 3, 1) w = tf.reshape(w, [3, 3, 1, 1]) tf.get_variable('Conv/weights', initializer=w) tf.get_variable('Conv/biases', initializer=tf.zeros([1])) tf.get_variable_scope().reuse_variables() y1 = slim.conv2d(x, 1, [3, 3], stride=1, scope='Conv') y1_expected = tf.to_float([[14, 28, 43, 58, 34], [28, 48, 66, 84, 46], [43, 66, 84, 102, 55], [58, 84, 102, 120, 64], [34, 46, 55, 64, 30]]) y1_expected = tf.reshape(y1_expected, [1, n, n, 1]) y2 = resnet_utils.subsample(y1, 2) y2_expected = tf.to_float([[14, 43, 34], [43, 84, 55], [34, 55, 30]]) y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1]) y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv') y3_expected = y2_expected y4 = slim.conv2d(x, 1, [3, 3], stride=2, scope='Conv') y4_expected = y2_expected with self.test_session() as sess: sess.run(tf.global_variables_initializer()) self.assertAllClose(y1.eval(), y1_expected.eval()) self.assertAllClose(y2.eval(), y2_expected.eval()) self.assertAllClose(y3.eval(), y3_expected.eval()) self.assertAllClose(y4.eval(), y4_expected.eval()) def _resnet_plain(self, inputs, blocks, output_stride=None, scope=None): """A plain ResNet without extra layers before or after the ResNet blocks.""" with tf.variable_scope(scope, values=[inputs]): with slim.arg_scope([slim.conv2d], outputs_collections='end_points'): net = resnet_utils.stack_blocks_dense(inputs, blocks, output_stride) end_points = slim.utils.convert_collection_to_dict('end_points') return net, end_points def testEndPointsV1(self): """Test the end points of a tiny v1 bottleneck network.""" blocks = [ resnet_v1.resnet_v1_block( 'block1', base_depth=1, num_units=2, stride=2), resnet_v1.resnet_v1_block( 'block2', base_depth=2, num_units=2, stride=1), ] inputs = create_test_input(2, 32, 16, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_plain(inputs, blocks, scope='tiny') expected = [ 'tiny/block1/unit_1/bottleneck_v1/shortcut', 'tiny/block1/unit_1/bottleneck_v1/conv1', 'tiny/block1/unit_1/bottleneck_v1/conv2', 'tiny/block1/unit_1/bottleneck_v1/conv3', 'tiny/block1/unit_2/bottleneck_v1/conv1', 'tiny/block1/unit_2/bottleneck_v1/conv2', 'tiny/block1/unit_2/bottleneck_v1/conv3', 'tiny/block2/unit_1/bottleneck_v1/shortcut', 'tiny/block2/unit_1/bottleneck_v1/conv1', 'tiny/block2/unit_1/bottleneck_v1/conv2', 'tiny/block2/unit_1/bottleneck_v1/conv3', 'tiny/block2/unit_2/bottleneck_v1/conv1', 'tiny/block2/unit_2/bottleneck_v1/conv2', 'tiny/block2/unit_2/bottleneck_v1/conv3'] self.assertItemsEqual(expected, end_points.keys()) def _stack_blocks_nondense(self, net, blocks): """A simplified ResNet Block stacker without output stride control.""" for block in blocks: with tf.variable_scope(block.scope, 'block', [net]): for i, unit in enumerate(block.args): with tf.variable_scope('unit_%d' % (i + 1), values=[net]): net = block.unit_fn(net, rate=1, **unit) return net def testAtrousValuesBottleneck(self): """Verify the values of dense feature extraction by atrous convolution. Make sure that dense feature extraction by stack_blocks_dense() followed by subsampling gives identical results to feature extraction at the nominal network output stride using the simple self._stack_blocks_nondense() above. """ block = resnet_v1.resnet_v1_block blocks = [ block('block1', base_depth=1, num_units=2, stride=2), block('block2', base_depth=2, num_units=2, stride=2), block('block3', base_depth=4, num_units=2, stride=2), block('block4', base_depth=8, num_units=2, stride=1), ] nominal_stride = 8 # Test both odd and even input dimensions. height = 30 width = 31 with slim.arg_scope(resnet_utils.resnet_arg_scope()): with slim.arg_scope([slim.batch_norm], is_training=False): for output_stride in [1, 2, 4, 8, None]: with tf.Graph().as_default(): with self.test_session() as sess: tf.set_random_seed(0) inputs = create_test_input(1, height, width, 3) # Dense feature extraction followed by subsampling. output = resnet_utils.stack_blocks_dense(inputs, blocks, output_stride) if output_stride is None: factor = 1 else: factor = nominal_stride // output_stride output = resnet_utils.subsample(output, factor) # Make the two networks use the same weights. tf.get_variable_scope().reuse_variables() # Feature extraction at the nominal network rate. expected = self._stack_blocks_nondense(inputs, blocks) sess.run(tf.global_variables_initializer()) output, expected = sess.run([output, expected]) self.assertAllClose(output, expected, atol=1e-4, rtol=1e-4) def testStridingLastUnitVsSubsampleBlockEnd(self): """Compares subsampling at the block's last unit or block's end. Makes sure that the final output is the same when we use a stride at the last unit of a block vs. we subsample activations at the end of a block. """ block = resnet_v1.resnet_v1_block blocks = [ block('block1', base_depth=1, num_units=2, stride=2), block('block2', base_depth=2, num_units=2, stride=2), block('block3', base_depth=4, num_units=2, stride=2), block('block4', base_depth=8, num_units=2, stride=1), ] # Test both odd and even input dimensions. height = 30 width = 31 with slim.arg_scope(resnet_utils.resnet_arg_scope()): with slim.arg_scope([slim.batch_norm], is_training=False): for output_stride in [1, 2, 4, 8, None]: with tf.Graph().as_default(): with self.test_session() as sess: tf.set_random_seed(0) inputs = create_test_input(1, height, width, 3) # Subsampling at the last unit of the block. output = resnet_utils.stack_blocks_dense( inputs, blocks, output_stride, store_non_strided_activations=False, outputs_collections='output') output_end_points = slim.utils.convert_collection_to_dict( 'output') # Make the two networks use the same weights. tf.get_variable_scope().reuse_variables() # Subsample activations at the end of the blocks. expected = resnet_utils.stack_blocks_dense( inputs, blocks, output_stride, store_non_strided_activations=True, outputs_collections='expected') expected_end_points = slim.utils.convert_collection_to_dict( 'expected') sess.run(tf.global_variables_initializer()) # Make sure that the final output is the same. output, expected = sess.run([output, expected]) self.assertAllClose(output, expected, atol=1e-4, rtol=1e-4) # Make sure that intermediate block activations in # output_end_points are subsampled versions of the corresponding # ones in expected_end_points. for i, block in enumerate(blocks[:-1:]): output = output_end_points[block.scope] expected = expected_end_points[block.scope] atrous_activated = (output_stride is not None and 2 ** i >= output_stride) if not atrous_activated: expected = resnet_utils.subsample(expected, 2) output, expected = sess.run([output, expected]) self.assertAllClose(output, expected, atol=1e-4, rtol=1e-4) class ResnetCompleteNetworkTest(tf.test.TestCase): """Tests with complete small ResNet v1 networks.""" def _resnet_small(self, inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope='resnet_v1_small'): """A shallow and thin ResNet v1 for faster tests.""" block = resnet_v1.resnet_v1_block blocks = [ block('block1', base_depth=1, num_units=3, stride=2), block('block2', base_depth=2, num_units=3, stride=2), block('block3', base_depth=4, num_units=3, stride=2), block('block4', base_depth=8, num_units=2, stride=1), ] return resnet_v1.resnet_v1(inputs, blocks, num_classes, is_training=is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=include_root_block, spatial_squeeze=spatial_squeeze, reuse=reuse, scope=scope) def testClassificationEndPoints(self): global_pool = True num_classes = 10 inputs = create_test_input(2, 224, 224, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): logits, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, spatial_squeeze=False, scope='resnet') self.assertTrue(logits.op.name.startswith('resnet/logits')) self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes]) self.assertTrue('predictions' in end_points) self.assertListEqual(end_points['predictions'].get_shape().as_list(), [2, 1, 1, num_classes]) self.assertTrue('global_pool' in end_points) self.assertListEqual(end_points['global_pool'].get_shape().as_list(), [2, 1, 1, 32]) def testClassificationEndPointsWithNoBatchNormArgscope(self): global_pool = True num_classes = 10 inputs = create_test_input(2, 224, 224, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): logits, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, spatial_squeeze=False, is_training=None, scope='resnet') self.assertTrue(logits.op.name.startswith('resnet/logits')) self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes]) self.assertTrue('predictions' in end_points) self.assertListEqual(end_points['predictions'].get_shape().as_list(), [2, 1, 1, num_classes]) self.assertTrue('global_pool' in end_points) self.assertListEqual(end_points['global_pool'].get_shape().as_list(), [2, 1, 1, 32]) def testEndpointNames(self): # Like ResnetUtilsTest.testEndPointsV1(), but for the public API. global_pool = True num_classes = 10 inputs = create_test_input(2, 224, 224, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, scope='resnet') expected = ['resnet/conv1'] for block in range(1, 5): for unit in range(1, 4 if block < 4 else 3): for conv in range(1, 4): expected.append('resnet/block%d/unit_%d/bottleneck_v1/conv%d' % (block, unit, conv)) expected.append('resnet/block%d/unit_%d/bottleneck_v1' % (block, unit)) expected.append('resnet/block%d/unit_1/bottleneck_v1/shortcut' % block) expected.append('resnet/block%d' % block) expected.extend(['global_pool', 'resnet/logits', 'resnet/spatial_squeeze', 'predictions']) self.assertItemsEqual(end_points.keys(), expected) def testClassificationShapes(self): global_pool = True num_classes = 10 inputs = create_test_input(2, 224, 224, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 28, 28, 4], 'resnet/block2': [2, 14, 14, 8], 'resnet/block3': [2, 7, 7, 16], 'resnet/block4': [2, 7, 7, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testFullyConvolutionalEndpointShapes(self): global_pool = False num_classes = 10 inputs = create_test_input(2, 321, 321, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, spatial_squeeze=False, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 41, 41, 4], 'resnet/block2': [2, 21, 21, 8], 'resnet/block3': [2, 11, 11, 16], 'resnet/block4': [2, 11, 11, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testRootlessFullyConvolutionalEndpointShapes(self): global_pool = False num_classes = 10 inputs = create_test_input(2, 128, 128, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, include_root_block=False, spatial_squeeze=False, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 64, 64, 4], 'resnet/block2': [2, 32, 32, 8], 'resnet/block3': [2, 16, 16, 16], 'resnet/block4': [2, 16, 16, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testAtrousFullyConvolutionalEndpointShapes(self): global_pool = False num_classes = 10 output_stride = 8 inputs = create_test_input(2, 321, 321, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): _, end_points = self._resnet_small(inputs, num_classes, global_pool=global_pool, output_stride=output_stride, spatial_squeeze=False, scope='resnet') endpoint_to_shape = { 'resnet/block1': [2, 41, 41, 4], 'resnet/block2': [2, 41, 41, 8], 'resnet/block3': [2, 41, 41, 16], 'resnet/block4': [2, 41, 41, 32]} for endpoint in endpoint_to_shape: shape = endpoint_to_shape[endpoint] self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape) def testAtrousFullyConvolutionalValues(self): """Verify dense feature extraction with atrous convolution.""" nominal_stride = 32 for output_stride in [4, 8, 16, 32, None]: with slim.arg_scope(resnet_utils.resnet_arg_scope()): with tf.Graph().as_default(): with self.test_session() as sess: tf.set_random_seed(0) inputs = create_test_input(2, 81, 81, 3) # Dense feature extraction followed by subsampling. output, _ = self._resnet_small(inputs, None, is_training=False, global_pool=False, output_stride=output_stride) if output_stride is None: factor = 1 else: factor = nominal_stride // output_stride output = resnet_utils.subsample(output, factor) # Make the two networks use the same weights. tf.get_variable_scope().reuse_variables() # Feature extraction at the nominal network rate. expected, _ = self._resnet_small(inputs, None, is_training=False, global_pool=False) sess.run(tf.global_variables_initializer()) self.assertAllClose(output.eval(), expected.eval(), atol=1e-4, rtol=1e-4) def testUnknownBatchSize(self): batch = 2 height, width = 65, 65 global_pool = True num_classes = 10 inputs = create_test_input(None, height, width, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): logits, _ = self._resnet_small(inputs, num_classes, global_pool=global_pool, spatial_squeeze=False, scope='resnet') self.assertTrue(logits.op.name.startswith('resnet/logits')) self.assertListEqual(logits.get_shape().as_list(), [None, 1, 1, num_classes]) images = create_test_input(batch, height, width, 3) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEqual(output.shape, (batch, 1, 1, num_classes)) def testFullyConvolutionalUnknownHeightWidth(self): batch = 2 height, width = 65, 65 global_pool = False inputs = create_test_input(batch, None, None, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): output, _ = self._resnet_small(inputs, None, global_pool=global_pool) self.assertListEqual(output.get_shape().as_list(), [batch, None, None, 32]) images = create_test_input(batch, height, width, 3) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(output, {inputs: images.eval()}) self.assertEqual(output.shape, (batch, 3, 3, 32)) def testAtrousFullyConvolutionalUnknownHeightWidth(self): batch = 2 height, width = 65, 65 global_pool = False output_stride = 8 inputs = create_test_input(batch, None, None, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): output, _ = self._resnet_small(inputs, None, global_pool=global_pool, output_stride=output_stride) self.assertListEqual(output.get_shape().as_list(), [batch, None, None, 32]) images = create_test_input(batch, height, width, 3) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(output, {inputs: images.eval()}) self.assertEqual(output.shape, (batch, 9, 9, 32)) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/resnet_v1_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition for Gated Separable 3D network (S3D-G). The network architecture is proposed by: Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Murphy, Rethinking Spatiotemporal Feature Learning For Video Understanding. https://arxiv.org/abs/1712.04851. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import i3d_utils trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) conv3d_spatiotemporal = i3d_utils.conv3d_spatiotemporal inception_block_v1_3d = i3d_utils.inception_block_v1_3d # Orignaly, arg_scope = slim.arg_scope and layers = slim, now switch to more # update-to-date tf.contrib.* API. arg_scope = tf.contrib.framework.arg_scope layers = tf.contrib.layers def s3dg_arg_scope(weight_decay=1e-7, batch_norm_decay=0.999, batch_norm_epsilon=0.001): """Defines default arg_scope for S3D-G. Args: weight_decay: The weight decay to use for regularizing the model. batch_norm_decay: Decay for batch norm moving average. batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. Returns: sc: An arg_scope to use for the models. """ batch_norm_params = { # Decay for the moving averages. 'decay': batch_norm_decay, # epsilon to prevent 0s in variance. 'epsilon': batch_norm_epsilon, # Turns off fused batch norm. 'fused': False, # collection containing the moving mean and moving variance. 'variables_collections': { 'beta': None, 'gamma': None, 'moving_mean': ['moving_vars'], 'moving_variance': ['moving_vars'], } } with arg_scope( [layers.conv3d, conv3d_spatiotemporal], weights_regularizer=layers.l2_regularizer(weight_decay), activation_fn=tf.nn.relu, normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params): with arg_scope([conv3d_spatiotemporal], separable=True) as sc: return sc def self_gating(input_tensor, scope, data_format='NDHWC'): """Feature gating as used in S3D-G. Transforms the input features by aggregating features from all spatial and temporal locations, and applying gating conditioned on the aggregated features. More details can be found at: https://arxiv.org/abs/1712.04851 Args: input_tensor: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. scope: scope for `variable_scope`. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. Returns: A tensor with the same shape as input_tensor. """ index_c = data_format.index('C') index_d = data_format.index('D') index_h = data_format.index('H') index_w = data_format.index('W') input_shape = input_tensor.get_shape().as_list() t = input_shape[index_d] w = input_shape[index_w] h = input_shape[index_h] num_channels = input_shape[index_c] spatiotemporal_average = layers.avg_pool3d( input_tensor, [t, w, h], stride=1, data_format=data_format, scope=scope + '/self_gating/avg_pool3d') weights = layers.conv3d( spatiotemporal_average, num_channels, [1, 1, 1], activation_fn=None, normalizer_fn=None, biases_initializer=None, data_format=data_format, weights_initializer=trunc_normal(0.01), scope=scope + '/self_gating/transformer_W') tile_multiples = [1, t, w, h] tile_multiples.insert(index_c, 1) weights = tf.tile(weights, tile_multiples) weights = tf.nn.sigmoid(weights) return tf.multiply(weights, input_tensor) def s3dg_base(inputs, first_temporal_kernel_size=3, temporal_conv_startat='Conv2d_2c_3x3', gating_startat='Conv2d_2c_3x3', final_endpoint='Mixed_5c', min_depth=16, depth_multiplier=1.0, data_format='NDHWC', scope='InceptionV1'): """Defines the I3D/S3DG base architecture. Note that we use the names as defined in Inception V1 to facilitate checkpoint conversion from an image-trained Inception V1 checkpoint to I3D checkpoint. Args: inputs: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. first_temporal_kernel_size: Specifies the temporal kernel size for the first conv3d filter. A larger value slows down the model but provides little accuracy improvement. The default is 7 in the original I3D and S3D-G but 3 gives better performance. Must be set to one of 1, 3, 5 or 7. temporal_conv_startat: Specifies the first conv block to use 3D or separable 3D convs rather than 2D convs (implemented as [1, k, k] 3D conv). This is used to construct the inverted pyramid models. 'Conv2d_2c_3x3' is the first valid block to use separable 3D convs. If provided block name is not present, all valid blocks will use separable 3D convs. Note that 'Conv2d_1a_7x7' cannot be made into a separable 3D conv, but can be made into a 2D or 3D conv using the `first_temporal_kernel_size` option. gating_startat: Specifies the first conv block to use self gating. 'Conv2d_2c_3x3' is the first valid block to use self gating. If provided block name is not present, all valid blocks will use separable 3D convs. final_endpoint: Specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. scope: Optional variable_scope. Returns: A dictionary from components of the network to the corresponding activation. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or if depth_multiplier <= 0. """ assert data_format in ['NDHWC', 'NCDHW'] end_points = {} t = 1 # For inverted pyramid models, we start with gating switched off. use_gating = False self_gating_fn = None def gating_fn(inputs, scope): return self_gating(inputs, scope, data_format=data_format) if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV1', [inputs]): with arg_scope([layers.conv3d], weights_initializer=trunc_normal(0.01)): with arg_scope( [layers.conv3d, layers.max_pool3d, conv3d_spatiotemporal], stride=1, data_format=data_format, padding='SAME'): # batch_size x 32 x 112 x 112 x 64 end_point = 'Conv2d_1a_7x7' if first_temporal_kernel_size not in [1, 3, 5, 7]: raise ValueError( 'first_temporal_kernel_size can only be 1, 3, 5 or 7.') # Separable conv is slow when used at first conv layer. net = conv3d_spatiotemporal( inputs, depth(64), [first_temporal_kernel_size, 7, 7], stride=2, separable=False, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 56 x 56 x 64 end_point = 'MaxPool_2a_3x3' net = layers.max_pool3d( net, [1, 3, 3], stride=[1, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 56 x 56 x 64 end_point = 'Conv2d_2b_1x1' net = layers.conv3d(net, depth(64), [1, 1, 1], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 56 x 56 x 192 end_point = 'Conv2d_2c_3x3' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = conv3d_spatiotemporal(net, depth(192), [t, 3, 3], scope=end_point) if use_gating: net = self_gating(net, scope=end_point, data_format=data_format) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 28 x 28 x 192 end_point = 'MaxPool_3a_3x3' net = layers.max_pool3d( net, [1, 3, 3], stride=[1, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 28 x 28 x 256 end_point = 'Mixed_3b' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(64), num_outputs_1_0a=depth(96), num_outputs_1_0b=depth(128), num_outputs_2_0a=depth(16), num_outputs_2_0b=depth(32), num_outputs_3_0b=depth(32), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_3c' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(128), num_outputs_1_0a=depth(128), num_outputs_1_0b=depth(192), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(96), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_4a_3x3' net = layers.max_pool3d( net, [3, 3, 3], stride=[2, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 512 end_point = 'Mixed_4b' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(192), num_outputs_1_0a=depth(96), num_outputs_1_0b=depth(208), num_outputs_2_0a=depth(16), num_outputs_2_0b=depth(48), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 512 end_point = 'Mixed_4c' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(160), num_outputs_1_0a=depth(112), num_outputs_1_0b=depth(224), num_outputs_2_0a=depth(24), num_outputs_2_0b=depth(64), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 512 end_point = 'Mixed_4d' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(128), num_outputs_1_0a=depth(128), num_outputs_1_0b=depth(256), num_outputs_2_0a=depth(24), num_outputs_2_0b=depth(64), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 528 end_point = 'Mixed_4e' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(112), num_outputs_1_0a=depth(144), num_outputs_1_0b=depth(288), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(64), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 832 end_point = 'Mixed_4f' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(256), num_outputs_1_0a=depth(160), num_outputs_1_0b=depth(320), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(128), num_outputs_3_0b=depth(128), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_5a_2x2' net = layers.max_pool3d( net, [2, 2, 2], stride=[2, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 8 x 7 x 7 x 832 end_point = 'Mixed_5b' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(256), num_outputs_1_0a=depth(160), num_outputs_1_0b=depth(320), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(128), num_outputs_3_0b=depth(128), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 8 x 7 x 7 x 1024 end_point = 'Mixed_5c' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(384), num_outputs_1_0a=depth(192), num_outputs_1_0b=depth(384), num_outputs_2_0a=depth(48), num_outputs_2_0b=depth(128), num_outputs_3_0b=depth(128), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def s3dg(inputs, num_classes=1000, first_temporal_kernel_size=3, temporal_conv_startat='Conv2d_2c_3x3', gating_startat='Conv2d_2c_3x3', final_endpoint='Mixed_5c', min_depth=16, depth_multiplier=1.0, dropout_keep_prob=0.8, is_training=True, prediction_fn=layers.softmax, spatial_squeeze=True, reuse=None, data_format='NDHWC', scope='InceptionV1'): """Defines the S3D-G architecture. The default image size used to train this network is 224x224. Args: inputs: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. num_classes: number of predicted classes. first_temporal_kernel_size: Specifies the temporal kernel size for the first conv3d filter. A larger value slows down the model but provides little accuracy improvement. Must be set to one of 1, 3, 5 or 7. temporal_conv_startat: Specifies the first conv block to use separable 3D convs rather than 2D convs (implemented as [1, k, k] 3D conv). This is used to construct the inverted pyramid models. 'Conv2d_2c_3x3' is the first valid block to use separable 3D convs. If provided block name is not present, all valid blocks will use separable 3D convs. gating_startat: Specifies the first conv block to use self gating. 'Conv2d_2c_3x3' is the first valid block to use self gating. If provided block name is not present, all valid blocks will use separable 3D convs. final_endpoint: Specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. scope: Optional variable_scope. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, num_classes] end_points: a dictionary from components of the network to the corresponding activation. """ assert data_format in ['NDHWC', 'NCDHW'] # Final pooling and prediction with tf.variable_scope( scope, 'InceptionV1', [inputs, num_classes], reuse=reuse) as scope: with arg_scope( [layers.batch_norm, layers.dropout], is_training=is_training): net, end_points = s3dg_base( inputs, first_temporal_kernel_size=first_temporal_kernel_size, temporal_conv_startat=temporal_conv_startat, gating_startat=gating_startat, final_endpoint=final_endpoint, min_depth=min_depth, depth_multiplier=depth_multiplier, data_format=data_format, scope=scope) with tf.variable_scope('Logits'): if data_format.startswith('NC'): net = tf.transpose(net, [0, 2, 3, 4, 1]) kernel_size = i3d_utils.reduced_kernel_size_3d(net, [2, 7, 7]) net = layers.avg_pool3d( net, kernel_size, stride=1, data_format='NDHWC', scope='AvgPool_0a_7x7') net = layers.dropout(net, dropout_keep_prob, scope='Dropout_0b') logits = layers.conv3d( net, num_classes, [1, 1, 1], activation_fn=None, normalizer_fn=None, data_format='NDHWC', scope='Conv2d_0c_1x1') # Temporal average pooling. logits = tf.reduce_mean(logits, axis=1) if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points s3dg.default_image_size = 224
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/s3dg.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains a factory for building various models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import tensorflow as tf from nets import alexnet from nets import cifarnet from nets import i3d from nets import inception from nets import lenet from nets import mobilenet_v1 from nets import overfeat from nets import resnet_v1 from nets import resnet_v2 from nets import s3dg from nets import vgg from nets.mobilenet import mobilenet_v2 from nets.nasnet import nasnet from nets.nasnet import pnasnet slim = tf.contrib.slim networks_map = {'alexnet_v2': alexnet.alexnet_v2, 'cifarnet': cifarnet.cifarnet, 'overfeat': overfeat.overfeat, 'vgg_a': vgg.vgg_a, 'vgg_16': vgg.vgg_16, 'vgg_19': vgg.vgg_19, 'inception_v1': inception.inception_v1, 'inception_v2': inception.inception_v2, 'inception_v3': inception.inception_v3, 'inception_v4': inception.inception_v4, 'inception_resnet_v2': inception.inception_resnet_v2, 'i3d': i3d.i3d, 's3dg': s3dg.s3dg, 'lenet': lenet.lenet, 'resnet_v1_50': resnet_v1.resnet_v1_50, 'resnet_v1_101': resnet_v1.resnet_v1_101, 'resnet_v1_152': resnet_v1.resnet_v1_152, 'resnet_v1_200': resnet_v1.resnet_v1_200, 'resnet_v2_50': resnet_v2.resnet_v2_50, 'resnet_v2_101': resnet_v2.resnet_v2_101, 'resnet_v2_152': resnet_v2.resnet_v2_152, 'resnet_v2_200': resnet_v2.resnet_v2_200, 'mobilenet_v1': mobilenet_v1.mobilenet_v1, 'mobilenet_v1_075': mobilenet_v1.mobilenet_v1_075, 'mobilenet_v1_050': mobilenet_v1.mobilenet_v1_050, 'mobilenet_v1_025': mobilenet_v1.mobilenet_v1_025, 'mobilenet_v2': mobilenet_v2.mobilenet, 'mobilenet_v2_140': mobilenet_v2.mobilenet_v2_140, 'mobilenet_v2_035': mobilenet_v2.mobilenet_v2_035, 'nasnet_cifar': nasnet.build_nasnet_cifar, 'nasnet_mobile': nasnet.build_nasnet_mobile, 'nasnet_large': nasnet.build_nasnet_large, 'pnasnet_large': pnasnet.build_pnasnet_large, 'pnasnet_mobile': pnasnet.build_pnasnet_mobile, } arg_scopes_map = {'alexnet_v2': alexnet.alexnet_v2_arg_scope, 'cifarnet': cifarnet.cifarnet_arg_scope, 'overfeat': overfeat.overfeat_arg_scope, 'vgg_a': vgg.vgg_arg_scope, 'vgg_16': vgg.vgg_arg_scope, 'vgg_19': vgg.vgg_arg_scope, 'inception_v1': inception.inception_v3_arg_scope, 'inception_v2': inception.inception_v3_arg_scope, 'inception_v3': inception.inception_v3_arg_scope, 'inception_v4': inception.inception_v4_arg_scope, 'inception_resnet_v2': inception.inception_resnet_v2_arg_scope, 'i3d': i3d.i3d_arg_scope, 's3dg': s3dg.s3dg_arg_scope, 'lenet': lenet.lenet_arg_scope, 'resnet_v1_50': resnet_v1.resnet_arg_scope, 'resnet_v1_101': resnet_v1.resnet_arg_scope, 'resnet_v1_152': resnet_v1.resnet_arg_scope, 'resnet_v1_200': resnet_v1.resnet_arg_scope, 'resnet_v2_50': resnet_v2.resnet_arg_scope, 'resnet_v2_101': resnet_v2.resnet_arg_scope, 'resnet_v2_152': resnet_v2.resnet_arg_scope, 'resnet_v2_200': resnet_v2.resnet_arg_scope, 'mobilenet_v1': mobilenet_v1.mobilenet_v1_arg_scope, 'mobilenet_v1_075': mobilenet_v1.mobilenet_v1_arg_scope, 'mobilenet_v1_050': mobilenet_v1.mobilenet_v1_arg_scope, 'mobilenet_v1_025': mobilenet_v1.mobilenet_v1_arg_scope, 'mobilenet_v2': mobilenet_v2.training_scope, 'mobilenet_v2_035': mobilenet_v2.training_scope, 'mobilenet_v2_140': mobilenet_v2.training_scope, 'nasnet_cifar': nasnet.nasnet_cifar_arg_scope, 'nasnet_mobile': nasnet.nasnet_mobile_arg_scope, 'nasnet_large': nasnet.nasnet_large_arg_scope, 'pnasnet_large': pnasnet.pnasnet_large_arg_scope, 'pnasnet_mobile': pnasnet.pnasnet_mobile_arg_scope, } def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False): """Returns a network_fn such as `logits, end_points = network_fn(images)`. Args: name: The name of the network. num_classes: The number of classes to use for classification. If 0 or None, the logits layer is omitted and its input features are returned instead. weight_decay: The l2 coefficient for the model weights. is_training: `True` if the model is being used for training and `False` otherwise. Returns: network_fn: A function that applies the model to a batch of images. It has the following signature: net, end_points = network_fn(images) The `images` input is a tensor of shape [batch_size, height, width, 3] with height = width = network_fn.default_image_size. (The permissibility and treatment of other sizes depends on the network_fn.) The returned `end_points` are a dictionary of intermediate activations. The returned `net` is the topmost layer, depending on `num_classes`: If `num_classes` was a non-zero integer, `net` is a logits tensor of shape [batch_size, num_classes]. If `num_classes` was 0 or `None`, `net` is a tensor with the input to the logits layer of shape [batch_size, 1, 1, num_features] or [batch_size, num_features]. Dropout has not been applied to this (even if the network's original classification does); it remains for the caller to do this or not. Raises: ValueError: If network `name` is not recognized. """ if name not in networks_map: raise ValueError('Name of network unknown %s' % name) func = networks_map[name] @functools.wraps(func) def network_fn(images, **kwargs): arg_scope = arg_scopes_map[name](weight_decay=weight_decay) with slim.arg_scope(arg_scope): return func(images, num_classes=num_classes, is_training=is_training, **kwargs) if hasattr(func, 'default_image_size'): network_fn.default_image_size = func.default_image_size return network_fn
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/nets_factory.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for networks.i3d.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import i3d class I3DTest(tf.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 num_frames = 64 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) logits, end_points = i3d.i3d(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Predictions' in end_points) self.assertListEqual(end_points['Predictions'].get_shape().as_list(), [batch_size, num_classes]) def testBuildBaseNetwork(self): batch_size = 5 num_frames = 64 height, width = 224, 224 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) mixed_6c, end_points = i3d.i3d_base(inputs) self.assertTrue(mixed_6c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_6c.get_shape().as_list(), [batch_size, 8, 7, 7, 1024]) expected_endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpoint(self): batch_size = 5 num_frames = 64 height, width = 224, 224 endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) out_tensor, end_points = i3d.i3d_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'InceptionV1/' + endpoint)) self.assertItemsEqual(endpoints[:index+1], end_points) def testBuildAndCheckAllEndPointsUptoMixed5c(self): batch_size = 5 num_frames = 64 height, width = 224, 224 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) _, end_points = i3d.i3d_base(inputs, final_endpoint='Mixed_5c') endpoints_shapes = {'Conv2d_1a_7x7': [5, 32, 112, 112, 64], 'MaxPool_2a_3x3': [5, 32, 56, 56, 64], 'Conv2d_2b_1x1': [5, 32, 56, 56, 64], 'Conv2d_2c_3x3': [5, 32, 56, 56, 192], 'MaxPool_3a_3x3': [5, 32, 28, 28, 192], 'Mixed_3b': [5, 32, 28, 28, 256], 'Mixed_3c': [5, 32, 28, 28, 480], 'MaxPool_4a_3x3': [5, 16, 14, 14, 480], 'Mixed_4b': [5, 16, 14, 14, 512], 'Mixed_4c': [5, 16, 14, 14, 512], 'Mixed_4d': [5, 16, 14, 14, 512], 'Mixed_4e': [5, 16, 14, 14, 528], 'Mixed_4f': [5, 16, 14, 14, 832], 'MaxPool_5a_2x2': [5, 8, 7, 7, 832], 'Mixed_5b': [5, 8, 7, 7, 832], 'Mixed_5c': [5, 8, 7, 7, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.iteritems(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testHalfSizeImages(self): batch_size = 5 num_frames = 64 height, width = 112, 112 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) mixed_5c, _ = i3d.i3d_base(inputs) self.assertTrue(mixed_5c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_5c.get_shape().as_list(), [batch_size, 8, 4, 4, 1024]) def testTenFrames(self): batch_size = 5 num_frames = 10 height, width = 224, 224 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) mixed_5c, _ = i3d.i3d_base(inputs) self.assertTrue(mixed_5c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_5c.get_shape().as_list(), [batch_size, 2, 7, 7, 1024]) def testEvaluation(self): batch_size = 2 num_frames = 64 height, width = 224, 224 num_classes = 1000 eval_inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) logits, _ = i3d.i3d(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/i3d_test.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/__init__.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition of the Inception V4 architecture. As described in http://arxiv.org/abs/1602.07261. Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception_utils slim = tf.contrib.slim def block_inception_a(inputs, scope=None, reuse=None): """Builds Inception-A block for Inception v4 network.""" # By default use stride=1 and SAME padding with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'): with tf.variable_scope(scope, 'BlockInceptionA', [inputs], reuse=reuse): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(inputs, 96, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(inputs, 64, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 96, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(inputs, 64, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 96, [1, 1], scope='Conv2d_0b_1x1') return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) def block_reduction_a(inputs, scope=None, reuse=None): """Builds Reduction-A block for Inception v4 network.""" # By default use stride=1 and SAME padding with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'): with tf.variable_scope(scope, 'BlockReductionA', [inputs], reuse=reuse): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(inputs, 384, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 224, [3, 3], scope='Conv2d_0b_3x3') branch_1 = slim.conv2d(branch_1, 256, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(inputs, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') return tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) def block_inception_b(inputs, scope=None, reuse=None): """Builds Inception-B block for Inception v4 network.""" # By default use stride=1 and SAME padding with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'): with tf.variable_scope(scope, 'BlockInceptionB', [inputs], reuse=reuse): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 224, [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, 256, [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 192, [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, 224, [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, 224, [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, 256, [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1') return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) def block_reduction_b(inputs, scope=None, reuse=None): """Builds Reduction-B block for Inception v4 network.""" # By default use stride=1 and SAME padding with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'): with tf.variable_scope(scope, 'BlockReductionB', [inputs], reuse=reuse): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, 192, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(inputs, 256, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 256, [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, 320, [7, 1], scope='Conv2d_0c_7x1') branch_1 = slim.conv2d(branch_1, 320, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(inputs, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') return tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) def block_inception_c(inputs, scope=None, reuse=None): """Builds Inception-C block for Inception v4 network.""" # By default use stride=1 and SAME padding with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'): with tf.variable_scope(scope, 'BlockInceptionC', [inputs], reuse=reuse): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(inputs, 256, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, 256, [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, 256, [3, 1], scope='Conv2d_0c_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 448, [3, 1], scope='Conv2d_0b_3x1') branch_2 = slim.conv2d(branch_2, 512, [1, 3], scope='Conv2d_0c_1x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, 256, [1, 3], scope='Conv2d_0d_1x3'), slim.conv2d(branch_2, 256, [3, 1], scope='Conv2d_0e_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 256, [1, 1], scope='Conv2d_0b_1x1') return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) def inception_v4_base(inputs, final_endpoint='Mixed_7d', scope=None): """Creates the Inception V4 network up to the given final endpoint. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of [ 'Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'Mixed_3a', 'Mixed_4a', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_5e', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_6f', 'Mixed_6g', 'Mixed_6h', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c', 'Mixed_7d'] scope: Optional variable_scope. Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model. Raises: ValueError: if final_endpoint is not set to one of the predefined values, """ end_points = {} def add_and_check_final(name, net): end_points[name] = net return name == final_endpoint with tf.variable_scope(scope, 'InceptionV4', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # 299 x 299 x 3 net = slim.conv2d(inputs, 32, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') if add_and_check_final('Conv2d_1a_3x3', net): return net, end_points # 149 x 149 x 32 net = slim.conv2d(net, 32, [3, 3], padding='VALID', scope='Conv2d_2a_3x3') if add_and_check_final('Conv2d_2a_3x3', net): return net, end_points # 147 x 147 x 32 net = slim.conv2d(net, 64, [3, 3], scope='Conv2d_2b_3x3') if add_and_check_final('Conv2d_2b_3x3', net): return net, end_points # 147 x 147 x 64 with tf.variable_scope('Mixed_3a'): with tf.variable_scope('Branch_0'): branch_0 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_0a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 96, [3, 3], stride=2, padding='VALID', scope='Conv2d_0a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1]) if add_and_check_final('Mixed_3a', net): return net, end_points # 73 x 73 x 160 with tf.variable_scope('Mixed_4a'): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, 96, [3, 3], padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 64, [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, 64, [7, 1], scope='Conv2d_0c_7x1') branch_1 = slim.conv2d(branch_1, 96, [3, 3], padding='VALID', scope='Conv2d_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1]) if add_and_check_final('Mixed_4a', net): return net, end_points # 71 x 71 x 192 with tf.variable_scope('Mixed_5a'): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, 192, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1]) if add_and_check_final('Mixed_5a', net): return net, end_points # 35 x 35 x 384 # 4 x Inception-A blocks for idx in range(4): block_scope = 'Mixed_5' + chr(ord('b') + idx) net = block_inception_a(net, block_scope) if add_and_check_final(block_scope, net): return net, end_points # 35 x 35 x 384 # Reduction-A block net = block_reduction_a(net, 'Mixed_6a') if add_and_check_final('Mixed_6a', net): return net, end_points # 17 x 17 x 1024 # 7 x Inception-B blocks for idx in range(7): block_scope = 'Mixed_6' + chr(ord('b') + idx) net = block_inception_b(net, block_scope) if add_and_check_final(block_scope, net): return net, end_points # 17 x 17 x 1024 # Reduction-B block net = block_reduction_b(net, 'Mixed_7a') if add_and_check_final('Mixed_7a', net): return net, end_points # 8 x 8 x 1536 # 3 x Inception-C blocks for idx in range(3): block_scope = 'Mixed_7' + chr(ord('b') + idx) net = block_inception_c(net, block_scope) if add_and_check_final(block_scope, net): return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def inception_v4(inputs, num_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionV4', create_aux_logits=True): """Creates the Inception V4 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. create_aux_logits: Whether to include the auxiliary logits. Returns: net: a Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped input to the logits layer if num_classes is 0 or None. end_points: the set of end_points from the inception model. """ end_points = {} with tf.variable_scope(scope, 'InceptionV4', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_v4_base(inputs, scope=scope) with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # Auxiliary Head logits if create_aux_logits and num_classes: with tf.variable_scope('AuxLogits'): # 17 x 17 x 1024 aux_logits = end_points['Mixed_6h'] aux_logits = slim.avg_pool2d(aux_logits, [5, 5], stride=3, padding='VALID', scope='AvgPool_1a_5x5') aux_logits = slim.conv2d(aux_logits, 128, [1, 1], scope='Conv2d_1b_1x1') aux_logits = slim.conv2d(aux_logits, 768, aux_logits.get_shape()[1:3], padding='VALID', scope='Conv2d_2a') aux_logits = slim.flatten(aux_logits) aux_logits = slim.fully_connected(aux_logits, num_classes, activation_fn=None, scope='Aux_logits') end_points['AuxLogits'] = aux_logits # Final pooling and prediction # TODO(sguada,arnoegw): Consider adding a parameter global_pool which # can be set to False to disable pooling here (as in resnet_*()). with tf.variable_scope('Logits'): # 8 x 8 x 1536 kernel_size = net.get_shape()[1:3] if kernel_size.is_fully_defined(): net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a') else: net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if not num_classes: return net, end_points # 1 x 1 x 1536 net = slim.dropout(net, dropout_keep_prob, scope='Dropout_1b') net = slim.flatten(net, scope='PreLogitsFlatten') end_points['PreLogitsFlatten'] = net # 1536 logits = slim.fully_connected(net, num_classes, activation_fn=None, scope='Logits') end_points['Logits'] = logits end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions') return logits, end_points inception_v4.default_image_size = 299 inception_v4_arg_scope = inception_utils.inception_arg_scope
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v4.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Brings all inception models under one namespace.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import from nets.inception_resnet_v2 import inception_resnet_v2 from nets.inception_resnet_v2 import inception_resnet_v2_arg_scope from nets.inception_resnet_v2 import inception_resnet_v2_base from nets.inception_v1 import inception_v1 from nets.inception_v1 import inception_v1_arg_scope from nets.inception_v1 import inception_v1_base from nets.inception_v2 import inception_v2 from nets.inception_v2 import inception_v2_arg_scope from nets.inception_v2 import inception_v2_base from nets.inception_v3 import inception_v3 from nets.inception_v3 import inception_v3_arg_scope from nets.inception_v3 import inception_v3_base from nets.inception_v4 import inception_v4 from nets.inception_v4 import inception_v4_arg_scope from nets.inception_v4 import inception_v4_base # pylint: enable=unused-import
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains building blocks for various versions of Residual Networks. Residual networks (ResNets) were proposed in: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385, 2015 More variants were introduced in: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks. arXiv: 1603.05027, 2016 We can obtain different ResNet variants by changing the network depth, width, and form of residual unit. This module implements the infrastructure for building them. Concrete ResNet units and full ResNet networks are implemented in the accompanying resnet_v1.py and resnet_v2.py modules. Compared to https://github.com/KaimingHe/deep-residual-networks, in the current implementation we subsample the output activations in the last residual unit of each block, instead of subsampling the input activations in the first residual unit of each block. The two implementations give identical results but our implementation is more memory efficient. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import tensorflow as tf slim = tf.contrib.slim class Block(collections.namedtuple('Block', ['scope', 'unit_fn', 'args'])): """A named tuple describing a ResNet block. Its parts are: scope: The scope of the `Block`. unit_fn: The ResNet unit function which takes as input a `Tensor` and returns another `Tensor` with the output of the ResNet unit. args: A list of length equal to the number of units in the `Block`. The list contains one (depth, depth_bottleneck, stride) tuple for each unit in the block to serve as argument to unit_fn. """ def subsample(inputs, factor, scope=None): """Subsamples the input along the spatial dimensions. Args: inputs: A `Tensor` of size [batch, height_in, width_in, channels]. factor: The subsampling factor. scope: Optional variable_scope. Returns: output: A `Tensor` of size [batch, height_out, width_out, channels] with the input, either intact (if factor == 1) or subsampled (if factor > 1). """ if factor == 1: return inputs else: return slim.max_pool2d(inputs, [1, 1], stride=factor, scope=scope) def conv2d_same(inputs, num_outputs, kernel_size, stride, rate=1, scope=None): """Strided 2-D convolution with 'SAME' padding. When stride > 1, then we do explicit zero-padding, followed by conv2d with 'VALID' padding. Note that net = conv2d_same(inputs, num_outputs, 3, stride=stride) is equivalent to net = slim.conv2d(inputs, num_outputs, 3, stride=1, padding='SAME') net = subsample(net, factor=stride) whereas net = slim.conv2d(inputs, num_outputs, 3, stride=stride, padding='SAME') is different when the input's height or width is even, which is why we add the current function. For more details, see ResnetUtilsTest.testConv2DSameEven(). Args: inputs: A 4-D tensor of size [batch, height_in, width_in, channels]. num_outputs: An integer, the number of output filters. kernel_size: An int with the kernel_size of the filters. stride: An integer, the output stride. rate: An integer, rate for atrous convolution. scope: Scope. Returns: output: A 4-D tensor of size [batch, height_out, width_out, channels] with the convolution output. """ if stride == 1: return slim.conv2d(inputs, num_outputs, kernel_size, stride=1, rate=rate, padding='SAME', scope=scope) else: kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1) pad_total = kernel_size_effective - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]]) return slim.conv2d(inputs, num_outputs, kernel_size, stride=stride, rate=rate, padding='VALID', scope=scope) @slim.add_arg_scope def stack_blocks_dense(net, blocks, output_stride=None, store_non_strided_activations=False, outputs_collections=None): """Stacks ResNet `Blocks` and controls output feature density. First, this function creates scopes for the ResNet in the form of 'block_name/unit_1', 'block_name/unit_2', etc. Second, this function allows the user to explicitly control the ResNet output_stride, which is the ratio of the input to output spatial resolution. This is useful for dense prediction tasks such as semantic segmentation or object detection. Most ResNets consist of 4 ResNet blocks and subsample the activations by a factor of 2 when transitioning between consecutive ResNet blocks. This results to a nominal ResNet output_stride equal to 8. If we set the output_stride to half the nominal network stride (e.g., output_stride=4), then we compute responses twice. Control of the output feature density is implemented by atrous convolution. Args: net: A `Tensor` of size [batch, height, width, channels]. blocks: A list of length equal to the number of ResNet `Blocks`. Each element is a ResNet `Block` object describing the units in the `Block`. output_stride: If `None`, then the output will be computed at the nominal network stride. If output_stride is not `None`, it specifies the requested ratio of input to output spatial resolution, which needs to be equal to the product of unit strides from the start up to some level of the ResNet. For example, if the ResNet employs units with strides 1, 2, 1, 3, 4, 1, then valid values for the output_stride are 1, 2, 6, 24 or None (which is equivalent to output_stride=24). store_non_strided_activations: If True, we compute non-strided (undecimated) activations at the last unit of each block and store them in the `outputs_collections` before subsampling them. This gives us access to higher resolution intermediate activations which are useful in some dense prediction problems but increases 4x the computation and memory cost at the last unit of each block. outputs_collections: Collection to add the ResNet block outputs. Returns: net: Output tensor with stride equal to the specified output_stride. Raises: ValueError: If the target output_stride is not valid. """ # The current_stride variable keeps track of the effective stride of the # activations. This allows us to invoke atrous convolution whenever applying # the next residual unit would result in the activations having stride larger # than the target output_stride. current_stride = 1 # The atrous convolution rate parameter. rate = 1 for block in blocks: with tf.variable_scope(block.scope, 'block', [net]) as sc: block_stride = 1 for i, unit in enumerate(block.args): if store_non_strided_activations and i == len(block.args) - 1: # Move stride from the block's last unit to the end of the block. block_stride = unit.get('stride', 1) unit = dict(unit, stride=1) with tf.variable_scope('unit_%d' % (i + 1), values=[net]): # If we have reached the target output_stride, then we need to employ # atrous convolution with stride=1 and multiply the atrous rate by the # current unit's stride for use in subsequent layers. if output_stride is not None and current_stride == output_stride: net = block.unit_fn(net, rate=rate, **dict(unit, stride=1)) rate *= unit.get('stride', 1) else: net = block.unit_fn(net, rate=1, **unit) current_stride *= unit.get('stride', 1) if output_stride is not None and current_stride > output_stride: raise ValueError('The target output_stride cannot be reached.') # Collect activations at the block's end before performing subsampling. net = slim.utils.collect_named_outputs(outputs_collections, sc.name, net) # Subsampling of the block's output activations. if output_stride is not None and current_stride == output_stride: rate *= block_stride else: net = subsample(net, block_stride) current_stride *= block_stride if output_stride is not None and current_stride > output_stride: raise ValueError('The target output_stride cannot be reached.') if output_stride is not None and current_stride != output_stride: raise ValueError('The target output_stride cannot be reached.') return net def resnet_arg_scope(weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True, activation_fn=tf.nn.relu, use_batch_norm=True, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS): """Defines the default ResNet arg scope. TODO(gpapan): The batch-normalization related default values above are appropriate for use in conjunction with the reference ResNet models released at https://github.com/KaimingHe/deep-residual-networks. When training ResNets from scratch, they might need to be tuned. Args: weight_decay: The weight decay to use for regularizing the model. batch_norm_decay: The moving average decay when estimating layer activation statistics in batch normalization. batch_norm_epsilon: Small constant to prevent division by zero when normalizing activations by their variance in batch normalization. batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the activations in the batch normalization layer. activation_fn: The activation function which is used in ResNet. use_batch_norm: Whether or not to use batch normalization. batch_norm_updates_collections: Collection for the update ops for batch norm. Returns: An `arg_scope` to use for the resnet models. """ batch_norm_params = { 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': batch_norm_scale, 'updates_collections': batch_norm_updates_collections, 'fused': None, # Use fused batch norm if possible. } with slim.arg_scope( [slim.conv2d], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=slim.variance_scaling_initializer(), activation_fn=activation_fn, normalizer_fn=slim.batch_norm if use_batch_norm else None, normalizer_params=batch_norm_params): with slim.arg_scope([slim.batch_norm], **batch_norm_params): # The following implies padding='SAME' for pool1, which makes feature # alignment easier for dense prediction tasks. This is also used in # https://github.com/facebook/fb.resnet.torch. However the accompanying # code of 'Deep Residual Learning for Image Recognition' uses # padding='VALID' for pool1. You can switch to that choice by setting # slim.arg_scope([slim.max_pool2d], padding='VALID'). with slim.arg_scope([slim.max_pool2d], padding='SAME') as arg_sc: return arg_sc
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/resnet_utils.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for networks.s3dg.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import s3dg class S3DGTest(tf.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 num_frames = 64 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) logits, end_points = s3dg.s3dg(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Predictions' in end_points) self.assertListEqual(end_points['Predictions'].get_shape().as_list(), [batch_size, num_classes]) def testBuildBaseNetwork(self): batch_size = 5 num_frames = 64 height, width = 224, 224 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) mixed_6c, end_points = s3dg.s3dg_base(inputs) self.assertTrue(mixed_6c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_6c.get_shape().as_list(), [batch_size, 8, 7, 7, 1024]) expected_endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpointNoGating(self): batch_size = 5 num_frames = 64 height, width = 224, 224 endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) out_tensor, end_points = s3dg.s3dg_base( inputs, final_endpoint=endpoint, gating_startat=None) print(endpoint, out_tensor.op.name) self.assertTrue(out_tensor.op.name.startswith( 'InceptionV1/' + endpoint)) self.assertItemsEqual(endpoints[:index+1], end_points) def testBuildAndCheckAllEndPointsUptoMixed5c(self): batch_size = 5 num_frames = 64 height, width = 224, 224 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) _, end_points = s3dg.s3dg_base(inputs, final_endpoint='Mixed_5c') endpoints_shapes = {'Conv2d_1a_7x7': [5, 32, 112, 112, 64], 'MaxPool_2a_3x3': [5, 32, 56, 56, 64], 'Conv2d_2b_1x1': [5, 32, 56, 56, 64], 'Conv2d_2c_3x3': [5, 32, 56, 56, 192], 'MaxPool_3a_3x3': [5, 32, 28, 28, 192], 'Mixed_3b': [5, 32, 28, 28, 256], 'Mixed_3c': [5, 32, 28, 28, 480], 'MaxPool_4a_3x3': [5, 16, 14, 14, 480], 'Mixed_4b': [5, 16, 14, 14, 512], 'Mixed_4c': [5, 16, 14, 14, 512], 'Mixed_4d': [5, 16, 14, 14, 512], 'Mixed_4e': [5, 16, 14, 14, 528], 'Mixed_4f': [5, 16, 14, 14, 832], 'MaxPool_5a_2x2': [5, 8, 7, 7, 832], 'Mixed_5b': [5, 8, 7, 7, 832], 'Mixed_5c': [5, 8, 7, 7, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.iteritems(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testHalfSizeImages(self): batch_size = 5 num_frames = 64 height, width = 112, 112 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) mixed_5c, _ = s3dg.s3dg_base(inputs) self.assertTrue(mixed_5c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_5c.get_shape().as_list(), [batch_size, 8, 4, 4, 1024]) def testTenFrames(self): batch_size = 5 num_frames = 10 height, width = 224, 224 inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) mixed_5c, _ = s3dg.s3dg_base(inputs) self.assertTrue(mixed_5c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_5c.get_shape().as_list(), [batch_size, 2, 7, 7, 1024]) def testEvaluation(self): batch_size = 2 num_frames = 64 height, width = 224, 224 num_classes = 1000 eval_inputs = tf.random_uniform((batch_size, num_frames, height, width, 3)) logits, _ = s3dg.s3dg(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/s3dg_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nets.alexnet.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import alexnet slim = tf.contrib.slim class AlexnetV2Test(tf.test.TestCase): def testBuild(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = alexnet.alexnet_v2(inputs, num_classes) self.assertEquals(logits.op.name, 'alexnet_v2/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def testFullyConvolutional(self): batch_size = 1 height, width = 300, 400 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = alexnet.alexnet_v2(inputs, num_classes, spatial_squeeze=False) self.assertEquals(logits.op.name, 'alexnet_v2/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 4, 7, num_classes]) def testGlobalPool(self): batch_size = 1 height, width = 256, 256 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = alexnet.alexnet_v2(inputs, num_classes, spatial_squeeze=False, global_pool=True) self.assertEquals(logits.op.name, 'alexnet_v2/fc8/BiasAdd') self.assertListEqual(logits.get_shape().as_list(), [batch_size, 1, 1, num_classes]) def testEndPoints(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = alexnet.alexnet_v2(inputs, num_classes) expected_names = ['alexnet_v2/conv1', 'alexnet_v2/pool1', 'alexnet_v2/conv2', 'alexnet_v2/pool2', 'alexnet_v2/conv3', 'alexnet_v2/conv4', 'alexnet_v2/conv5', 'alexnet_v2/pool5', 'alexnet_v2/fc6', 'alexnet_v2/fc7', 'alexnet_v2/fc8' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) def testNoClasses(self): batch_size = 5 height, width = 224, 224 num_classes = None with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = alexnet.alexnet_v2(inputs, num_classes) expected_names = ['alexnet_v2/conv1', 'alexnet_v2/pool1', 'alexnet_v2/conv2', 'alexnet_v2/pool2', 'alexnet_v2/conv3', 'alexnet_v2/conv4', 'alexnet_v2/conv5', 'alexnet_v2/pool5', 'alexnet_v2/fc6', 'alexnet_v2/fc7' ] self.assertSetEqual(set(end_points.keys()), set(expected_names)) self.assertTrue(net.op.name.startswith('alexnet_v2/fc7')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 4096]) def testModelVariables(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 with self.test_session(): inputs = tf.random_uniform((batch_size, height, width, 3)) alexnet.alexnet_v2(inputs, num_classes) expected_names = ['alexnet_v2/conv1/weights', 'alexnet_v2/conv1/biases', 'alexnet_v2/conv2/weights', 'alexnet_v2/conv2/biases', 'alexnet_v2/conv3/weights', 'alexnet_v2/conv3/biases', 'alexnet_v2/conv4/weights', 'alexnet_v2/conv4/biases', 'alexnet_v2/conv5/weights', 'alexnet_v2/conv5/biases', 'alexnet_v2/fc6/weights', 'alexnet_v2/fc6/biases', 'alexnet_v2/fc7/weights', 'alexnet_v2/fc7/biases', 'alexnet_v2/fc8/weights', 'alexnet_v2/fc8/biases', ] model_variables = [v.op.name for v in slim.get_model_variables()] self.assertSetEqual(set(model_variables), set(expected_names)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.test_session(): eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = alexnet.alexnet_v2(eval_inputs, is_training=False) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) predictions = tf.argmax(logits, 1) self.assertListEqual(predictions.get_shape().as_list(), [batch_size]) def testTrainEvalWithReuse(self): train_batch_size = 2 eval_batch_size = 1 train_height, train_width = 224, 224 eval_height, eval_width = 300, 400 num_classes = 1000 with self.test_session(): train_inputs = tf.random_uniform( (train_batch_size, train_height, train_width, 3)) logits, _ = alexnet.alexnet_v2(train_inputs) self.assertListEqual(logits.get_shape().as_list(), [train_batch_size, num_classes]) tf.get_variable_scope().reuse_variables() eval_inputs = tf.random_uniform( (eval_batch_size, eval_height, eval_width, 3)) logits, _ = alexnet.alexnet_v2(eval_inputs, is_training=False, spatial_squeeze=False) self.assertListEqual(logits.get_shape().as_list(), [eval_batch_size, 4, 7, num_classes]) logits = tf.reduce_mean(logits, [1, 2]) predictions = tf.argmax(logits, 1) self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size]) def testForward(self): batch_size = 1 height, width = 224, 224 with self.test_session() as sess: inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = alexnet.alexnet_v2(inputs) sess.run(tf.global_variables_initializer()) output = sess.run(logits) self.assertTrue(output.any()) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/alexnet_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Tests for MobileNet v1.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nets import mobilenet_v1 slim = tf.contrib.slim class MobilenetV1Test(tf.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith( 'MobilenetV1/Logits/SpatialSqueeze')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Predictions' in end_points) self.assertListEqual(end_points['Predictions'].get_shape().as_list(), [batch_size, num_classes]) def testBuildPreLogitsNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(net.op.name.startswith('MobilenetV1/Logits/AvgPool')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 1024]) self.assertFalse('Logits' in end_points) self.assertFalse('Predictions' in end_points) def testBuildBaseNetwork(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = mobilenet_v1.mobilenet_v1_base(inputs) self.assertTrue(net.op.name.startswith('MobilenetV1/Conv2d_13')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 7, 7, 1024]) expected_endpoints = ['Conv2d_0', 'Conv2d_1_depthwise', 'Conv2d_1_pointwise', 'Conv2d_2_depthwise', 'Conv2d_2_pointwise', 'Conv2d_3_depthwise', 'Conv2d_3_pointwise', 'Conv2d_4_depthwise', 'Conv2d_4_pointwise', 'Conv2d_5_depthwise', 'Conv2d_5_pointwise', 'Conv2d_6_depthwise', 'Conv2d_6_pointwise', 'Conv2d_7_depthwise', 'Conv2d_7_pointwise', 'Conv2d_8_depthwise', 'Conv2d_8_pointwise', 'Conv2d_9_depthwise', 'Conv2d_9_pointwise', 'Conv2d_10_depthwise', 'Conv2d_10_pointwise', 'Conv2d_11_depthwise', 'Conv2d_11_pointwise', 'Conv2d_12_depthwise', 'Conv2d_12_pointwise', 'Conv2d_13_depthwise', 'Conv2d_13_pointwise'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpoint(self): batch_size = 5 height, width = 224, 224 endpoints = ['Conv2d_0', 'Conv2d_1_depthwise', 'Conv2d_1_pointwise', 'Conv2d_2_depthwise', 'Conv2d_2_pointwise', 'Conv2d_3_depthwise', 'Conv2d_3_pointwise', 'Conv2d_4_depthwise', 'Conv2d_4_pointwise', 'Conv2d_5_depthwise', 'Conv2d_5_pointwise', 'Conv2d_6_depthwise', 'Conv2d_6_pointwise', 'Conv2d_7_depthwise', 'Conv2d_7_pointwise', 'Conv2d_8_depthwise', 'Conv2d_8_pointwise', 'Conv2d_9_depthwise', 'Conv2d_9_pointwise', 'Conv2d_10_depthwise', 'Conv2d_10_pointwise', 'Conv2d_11_depthwise', 'Conv2d_11_pointwise', 'Conv2d_12_depthwise', 'Conv2d_12_pointwise', 'Conv2d_13_depthwise', 'Conv2d_13_pointwise'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'MobilenetV1/' + endpoint)) self.assertItemsEqual(endpoints[:index+1], end_points.keys()) def testBuildCustomNetworkUsingConvDefs(self): batch_size = 5 height, width = 224, 224 conv_defs = [ mobilenet_v1.Conv(kernel=[3, 3], stride=2, depth=32), mobilenet_v1.DepthSepConv(kernel=[3, 3], stride=1, depth=64), mobilenet_v1.DepthSepConv(kernel=[3, 3], stride=2, depth=128), mobilenet_v1.DepthSepConv(kernel=[3, 3], stride=1, depth=512) ] inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_3_pointwise', conv_defs=conv_defs) self.assertTrue(net.op.name.startswith('MobilenetV1/Conv2d_3')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 56, 56, 512]) expected_endpoints = ['Conv2d_0', 'Conv2d_1_depthwise', 'Conv2d_1_pointwise', 'Conv2d_2_depthwise', 'Conv2d_2_pointwise', 'Conv2d_3_depthwise', 'Conv2d_3_pointwise'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildAndCheckAllEndPointsUptoConv2d_13(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise') _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise', use_explicit_padding=True) endpoints_shapes = {'Conv2d_0': [batch_size, 112, 112, 32], 'Conv2d_1_depthwise': [batch_size, 112, 112, 32], 'Conv2d_1_pointwise': [batch_size, 112, 112, 64], 'Conv2d_2_depthwise': [batch_size, 56, 56, 64], 'Conv2d_2_pointwise': [batch_size, 56, 56, 128], 'Conv2d_3_depthwise': [batch_size, 56, 56, 128], 'Conv2d_3_pointwise': [batch_size, 56, 56, 128], 'Conv2d_4_depthwise': [batch_size, 28, 28, 128], 'Conv2d_4_pointwise': [batch_size, 28, 28, 256], 'Conv2d_5_depthwise': [batch_size, 28, 28, 256], 'Conv2d_5_pointwise': [batch_size, 28, 28, 256], 'Conv2d_6_depthwise': [batch_size, 14, 14, 256], 'Conv2d_6_pointwise': [batch_size, 14, 14, 512], 'Conv2d_7_depthwise': [batch_size, 14, 14, 512], 'Conv2d_7_pointwise': [batch_size, 14, 14, 512], 'Conv2d_8_depthwise': [batch_size, 14, 14, 512], 'Conv2d_8_pointwise': [batch_size, 14, 14, 512], 'Conv2d_9_depthwise': [batch_size, 14, 14, 512], 'Conv2d_9_pointwise': [batch_size, 14, 14, 512], 'Conv2d_10_depthwise': [batch_size, 14, 14, 512], 'Conv2d_10_pointwise': [batch_size, 14, 14, 512], 'Conv2d_11_depthwise': [batch_size, 14, 14, 512], 'Conv2d_11_pointwise': [batch_size, 14, 14, 512], 'Conv2d_12_depthwise': [batch_size, 7, 7, 512], 'Conv2d_12_pointwise': [batch_size, 7, 7, 1024], 'Conv2d_13_depthwise': [batch_size, 7, 7, 1024], 'Conv2d_13_pointwise': [batch_size, 7, 7, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testOutputStride16BuildAndCheckAllEndPointsUptoConv2d_13(self): batch_size = 5 height, width = 224, 224 output_stride = 16 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise') _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise', use_explicit_padding=True) endpoints_shapes = {'Conv2d_0': [batch_size, 112, 112, 32], 'Conv2d_1_depthwise': [batch_size, 112, 112, 32], 'Conv2d_1_pointwise': [batch_size, 112, 112, 64], 'Conv2d_2_depthwise': [batch_size, 56, 56, 64], 'Conv2d_2_pointwise': [batch_size, 56, 56, 128], 'Conv2d_3_depthwise': [batch_size, 56, 56, 128], 'Conv2d_3_pointwise': [batch_size, 56, 56, 128], 'Conv2d_4_depthwise': [batch_size, 28, 28, 128], 'Conv2d_4_pointwise': [batch_size, 28, 28, 256], 'Conv2d_5_depthwise': [batch_size, 28, 28, 256], 'Conv2d_5_pointwise': [batch_size, 28, 28, 256], 'Conv2d_6_depthwise': [batch_size, 14, 14, 256], 'Conv2d_6_pointwise': [batch_size, 14, 14, 512], 'Conv2d_7_depthwise': [batch_size, 14, 14, 512], 'Conv2d_7_pointwise': [batch_size, 14, 14, 512], 'Conv2d_8_depthwise': [batch_size, 14, 14, 512], 'Conv2d_8_pointwise': [batch_size, 14, 14, 512], 'Conv2d_9_depthwise': [batch_size, 14, 14, 512], 'Conv2d_9_pointwise': [batch_size, 14, 14, 512], 'Conv2d_10_depthwise': [batch_size, 14, 14, 512], 'Conv2d_10_pointwise': [batch_size, 14, 14, 512], 'Conv2d_11_depthwise': [batch_size, 14, 14, 512], 'Conv2d_11_pointwise': [batch_size, 14, 14, 512], 'Conv2d_12_depthwise': [batch_size, 14, 14, 512], 'Conv2d_12_pointwise': [batch_size, 14, 14, 1024], 'Conv2d_13_depthwise': [batch_size, 14, 14, 1024], 'Conv2d_13_pointwise': [batch_size, 14, 14, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testOutputStride8BuildAndCheckAllEndPointsUptoConv2d_13(self): batch_size = 5 height, width = 224, 224 output_stride = 8 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise') _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise', use_explicit_padding=True) endpoints_shapes = {'Conv2d_0': [batch_size, 112, 112, 32], 'Conv2d_1_depthwise': [batch_size, 112, 112, 32], 'Conv2d_1_pointwise': [batch_size, 112, 112, 64], 'Conv2d_2_depthwise': [batch_size, 56, 56, 64], 'Conv2d_2_pointwise': [batch_size, 56, 56, 128], 'Conv2d_3_depthwise': [batch_size, 56, 56, 128], 'Conv2d_3_pointwise': [batch_size, 56, 56, 128], 'Conv2d_4_depthwise': [batch_size, 28, 28, 128], 'Conv2d_4_pointwise': [batch_size, 28, 28, 256], 'Conv2d_5_depthwise': [batch_size, 28, 28, 256], 'Conv2d_5_pointwise': [batch_size, 28, 28, 256], 'Conv2d_6_depthwise': [batch_size, 28, 28, 256], 'Conv2d_6_pointwise': [batch_size, 28, 28, 512], 'Conv2d_7_depthwise': [batch_size, 28, 28, 512], 'Conv2d_7_pointwise': [batch_size, 28, 28, 512], 'Conv2d_8_depthwise': [batch_size, 28, 28, 512], 'Conv2d_8_pointwise': [batch_size, 28, 28, 512], 'Conv2d_9_depthwise': [batch_size, 28, 28, 512], 'Conv2d_9_pointwise': [batch_size, 28, 28, 512], 'Conv2d_10_depthwise': [batch_size, 28, 28, 512], 'Conv2d_10_pointwise': [batch_size, 28, 28, 512], 'Conv2d_11_depthwise': [batch_size, 28, 28, 512], 'Conv2d_11_pointwise': [batch_size, 28, 28, 512], 'Conv2d_12_depthwise': [batch_size, 28, 28, 512], 'Conv2d_12_pointwise': [batch_size, 28, 28, 1024], 'Conv2d_13_depthwise': [batch_size, 28, 28, 1024], 'Conv2d_13_pointwise': [batch_size, 28, 28, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testBuildAndCheckAllEndPointsApproximateFaceNet(self): batch_size = 5 height, width = 128, 128 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise', depth_multiplier=0.75) _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise', depth_multiplier=0.75, use_explicit_padding=True) # For the Conv2d_0 layer FaceNet has depth=16 endpoints_shapes = {'Conv2d_0': [batch_size, 64, 64, 24], 'Conv2d_1_depthwise': [batch_size, 64, 64, 24], 'Conv2d_1_pointwise': [batch_size, 64, 64, 48], 'Conv2d_2_depthwise': [batch_size, 32, 32, 48], 'Conv2d_2_pointwise': [batch_size, 32, 32, 96], 'Conv2d_3_depthwise': [batch_size, 32, 32, 96], 'Conv2d_3_pointwise': [batch_size, 32, 32, 96], 'Conv2d_4_depthwise': [batch_size, 16, 16, 96], 'Conv2d_4_pointwise': [batch_size, 16, 16, 192], 'Conv2d_5_depthwise': [batch_size, 16, 16, 192], 'Conv2d_5_pointwise': [batch_size, 16, 16, 192], 'Conv2d_6_depthwise': [batch_size, 8, 8, 192], 'Conv2d_6_pointwise': [batch_size, 8, 8, 384], 'Conv2d_7_depthwise': [batch_size, 8, 8, 384], 'Conv2d_7_pointwise': [batch_size, 8, 8, 384], 'Conv2d_8_depthwise': [batch_size, 8, 8, 384], 'Conv2d_8_pointwise': [batch_size, 8, 8, 384], 'Conv2d_9_depthwise': [batch_size, 8, 8, 384], 'Conv2d_9_pointwise': [batch_size, 8, 8, 384], 'Conv2d_10_depthwise': [batch_size, 8, 8, 384], 'Conv2d_10_pointwise': [batch_size, 8, 8, 384], 'Conv2d_11_depthwise': [batch_size, 8, 8, 384], 'Conv2d_11_pointwise': [batch_size, 8, 8, 384], 'Conv2d_12_depthwise': [batch_size, 4, 4, 384], 'Conv2d_12_pointwise': [batch_size, 4, 4, 768], 'Conv2d_13_depthwise': [batch_size, 4, 4, 768], 'Conv2d_13_pointwise': [batch_size, 4, 4, 768]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testModelHasExpectedNumberOfParameters(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): mobilenet_v1.mobilenet_v1_base(inputs) total_params, _ = slim.model_analyzer.analyze_vars( slim.get_model_variables()) self.assertAlmostEqual(3217920, total_params) def testBuildEndPointsWithDepthMultiplierLessThanOne(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Conv')] _, end_points_with_multiplier = mobilenet_v1.mobilenet_v1( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=0.5) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(0.5 * original_depth, new_depth) def testBuildEndPointsWithDepthMultiplierGreaterThanOne(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv')] _, end_points_with_multiplier = mobilenet_v1.mobilenet_v1( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=2.0) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(2.0 * original_depth, new_depth) def testRaiseValueErrorWithInvalidDepthMultiplier(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) with self.assertRaises(ValueError): _ = mobilenet_v1.mobilenet_v1( inputs, num_classes, depth_multiplier=-0.1) with self.assertRaises(ValueError): _ = mobilenet_v1.mobilenet_v1( inputs, num_classes, depth_multiplier=0.0) def testHalfSizeImages(self): batch_size = 5 height, width = 112, 112 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_13_pointwise'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 4, 4, 1024]) def testUnknownImageShape(self): tf.reset_default_graph() batch_size = 2 height, width = 224, 224 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_13_pointwise'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) def testGlobalPoolUnknownImageShape(self): tf.reset_default_graph() batch_size = 1 height, width = 250, 300 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes, global_pool=True) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_13_pointwise'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 10, 1024]) def testUnknowBatchSize(self): batch_size = 1 height, width = 224, 224 num_classes = 1000 inputs = tf.placeholder(tf.float32, (None, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEquals(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 150, 150 num_classes = 1000 train_inputs = tf.random_uniform((train_batch_size, height, width, 3)) mobilenet_v1.mobilenet_v1(train_inputs, num_classes) eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes, reuse=True) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (eval_batch_size,)) def testLogitsNotSqueezed(self): num_classes = 25 images = tf.random_uniform([1, 224, 224, 3]) logits, _ = mobilenet_v1.mobilenet_v1(images, num_classes=num_classes, spatial_squeeze=False) with self.test_session() as sess: tf.global_variables_initializer().run() logits_out = sess.run(logits) self.assertListEqual(list(logits_out.shape), [1, 1, 1, num_classes]) def testBatchNormScopeDoesNotHaveIsTrainingWhenItsSetToNone(self): sc = mobilenet_v1.mobilenet_v1_arg_scope(is_training=None) self.assertNotIn('is_training', sc[slim.arg_scope_func_key( slim.batch_norm)]) def testBatchNormScopeDoesHasIsTrainingWhenItsNotNone(self): sc = mobilenet_v1.mobilenet_v1_arg_scope(is_training=True) self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) sc = mobilenet_v1.mobilenet_v1_arg_scope(is_training=False) self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) sc = mobilenet_v1.mobilenet_v1_arg_scope() self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet_v1_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for nets.inception_v1.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nets import inception slim = tf.contrib.slim class InceptionV3Test(tf.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v3(inputs, num_classes) self.assertTrue(logits.op.name.startswith( 'InceptionV3/Logits/SpatialSqueeze')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Predictions' in end_points) self.assertListEqual(end_points['Predictions'].get_shape().as_list(), [batch_size, num_classes]) def testBuildPreLogitsNetwork(self): batch_size = 5 height, width = 299, 299 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = inception.inception_v3(inputs, num_classes) self.assertTrue(net.op.name.startswith('InceptionV3/Logits/AvgPool')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 2048]) self.assertFalse('Logits' in end_points) self.assertFalse('Predictions' in end_points) def testBuildBaseNetwork(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) final_endpoint, end_points = inception.inception_v3_base(inputs) self.assertTrue(final_endpoint.op.name.startswith( 'InceptionV3/Mixed_7c')) self.assertListEqual(final_endpoint.get_shape().as_list(), [batch_size, 8, 8, 2048]) expected_endpoints = ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpoint(self): batch_size = 5 height, width = 299, 299 endpoints = ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = inception.inception_v3_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'InceptionV3/' + endpoint)) self.assertItemsEqual(endpoints[:index+1], end_points.keys()) def testBuildAndCheckAllEndPointsUptoMixed7c(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v3_base( inputs, final_endpoint='Mixed_7c') endpoints_shapes = {'Conv2d_1a_3x3': [batch_size, 149, 149, 32], 'Conv2d_2a_3x3': [batch_size, 147, 147, 32], 'Conv2d_2b_3x3': [batch_size, 147, 147, 64], 'MaxPool_3a_3x3': [batch_size, 73, 73, 64], 'Conv2d_3b_1x1': [batch_size, 73, 73, 80], 'Conv2d_4a_3x3': [batch_size, 71, 71, 192], 'MaxPool_5a_3x3': [batch_size, 35, 35, 192], 'Mixed_5b': [batch_size, 35, 35, 256], 'Mixed_5c': [batch_size, 35, 35, 288], 'Mixed_5d': [batch_size, 35, 35, 288], 'Mixed_6a': [batch_size, 17, 17, 768], 'Mixed_6b': [batch_size, 17, 17, 768], 'Mixed_6c': [batch_size, 17, 17, 768], 'Mixed_6d': [batch_size, 17, 17, 768], 'Mixed_6e': [batch_size, 17, 17, 768], 'Mixed_7a': [batch_size, 8, 8, 1280], 'Mixed_7b': [batch_size, 8, 8, 2048], 'Mixed_7c': [batch_size, 8, 8, 2048]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testModelHasExpectedNumberOfParameters(self): batch_size = 5 height, width = 299, 299 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope(inception.inception_v3_arg_scope()): inception.inception_v3_base(inputs) total_params, _ = slim.model_analyzer.analyze_vars( slim.get_model_variables()) self.assertAlmostEqual(21802784, total_params) def testBuildEndPoints(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v3(inputs, num_classes) self.assertTrue('Logits' in end_points) logits = end_points['Logits'] self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('AuxLogits' in end_points) aux_logits = end_points['AuxLogits'] self.assertListEqual(aux_logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Mixed_7c' in end_points) pre_pool = end_points['Mixed_7c'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 8, 8, 2048]) self.assertTrue('PreLogits' in end_points) pre_logits = end_points['PreLogits'] self.assertListEqual(pre_logits.get_shape().as_list(), [batch_size, 1, 1, 2048]) def testBuildEndPointsWithDepthMultiplierLessThanOne(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v3(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv')] _, end_points_with_multiplier = inception.inception_v3( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=0.5) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(0.5 * original_depth, new_depth) def testBuildEndPointsWithDepthMultiplierGreaterThanOne(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v3(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv')] _, end_points_with_multiplier = inception.inception_v3( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=2.0) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(2.0 * original_depth, new_depth) def testRaiseValueErrorWithInvalidDepthMultiplier(self): batch_size = 5 height, width = 299, 299 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) with self.assertRaises(ValueError): _ = inception.inception_v3(inputs, num_classes, depth_multiplier=-0.1) with self.assertRaises(ValueError): _ = inception.inception_v3(inputs, num_classes, depth_multiplier=0.0) def testHalfSizeImages(self): batch_size = 5 height, width = 150, 150 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v3(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV3/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_7c'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 3, 3, 2048]) def testUnknownImageShape(self): tf.reset_default_graph() batch_size = 2 height, width = 299, 299 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = inception.inception_v3(inputs, num_classes) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_7c'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 8, 2048]) def testGlobalPoolUnknownImageShape(self): tf.reset_default_graph() batch_size = 1 height, width = 330, 400 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = inception.inception_v3(inputs, num_classes, global_pool=True) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_7c'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 11, 2048]) def testUnknowBatchSize(self): batch_size = 1 height, width = 299, 299 num_classes = 1000 inputs = tf.placeholder(tf.float32, (None, height, width, 3)) logits, _ = inception.inception_v3(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV3/Logits')) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEquals(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 299, 299 num_classes = 1000 eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = inception.inception_v3(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 150, 150 num_classes = 1000 train_inputs = tf.random_uniform((train_batch_size, height, width, 3)) inception.inception_v3(train_inputs, num_classes) eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3)) logits, _ = inception.inception_v3(eval_inputs, num_classes, is_training=False, reuse=True) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (eval_batch_size,)) def testLogitsNotSqueezed(self): num_classes = 25 images = tf.random_uniform([1, 299, 299, 3]) logits, _ = inception.inception_v3(images, num_classes=num_classes, spatial_squeeze=False) with self.test_session() as sess: tf.global_variables_initializer().run() logits_out = sess.run(logits) self.assertListEqual(list(logits_out.shape), [1, 1, 1, num_classes]) def testNoBatchNormScaleByDefault(self): height, width = 299, 299 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with slim.arg_scope(inception.inception_v3_arg_scope()): inception.inception_v3(inputs, num_classes, is_training=False) self.assertEqual(tf.global_variables('.*/BatchNorm/gamma:0$'), []) def testBatchNormScale(self): height, width = 299, 299 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with slim.arg_scope( inception.inception_v3_arg_scope(batch_norm_scale=True)): inception.inception_v3(inputs, num_classes, is_training=False) gamma_names = set( v.op.name for v in tf.global_variables('.*/BatchNorm/gamma:0$')) self.assertGreater(len(gamma_names), 0) for v in tf.global_variables('.*/BatchNorm/moving_mean:0$'): self.assertIn(v.op.name[:-len('moving_mean')] + 'gamma', gamma_names) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v3_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.slim.nets.cyclegan.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import cyclegan # TODO(joelshor): Add a test to check generator endpoints. class CycleganTest(tf.test.TestCase): def test_generator_inference(self): """Check one inference step.""" img_batch = tf.zeros([2, 32, 32, 3]) model_output, _ = cyclegan.cyclegan_generator_resnet(img_batch) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) sess.run(model_output) def _test_generator_graph_helper(self, shape): """Check that generator can take small and non-square inputs.""" output_imgs, _ = cyclegan.cyclegan_generator_resnet(tf.ones(shape)) self.assertAllEqual(shape, output_imgs.shape.as_list()) def test_generator_graph_small(self): self._test_generator_graph_helper([4, 32, 32, 3]) def test_generator_graph_medium(self): self._test_generator_graph_helper([3, 128, 128, 3]) def test_generator_graph_nonsquare(self): self._test_generator_graph_helper([2, 80, 400, 3]) def test_generator_unknown_batch_dim(self): """Check that generator can take unknown batch dimension inputs.""" img = tf.placeholder(tf.float32, shape=[None, 32, None, 3]) output_imgs, _ = cyclegan.cyclegan_generator_resnet(img) self.assertAllEqual([None, 32, None, 3], output_imgs.shape.as_list()) def _input_and_output_same_shape_helper(self, kernel_size): img_batch = tf.placeholder(tf.float32, shape=[None, 32, 32, 3]) output_img_batch, _ = cyclegan.cyclegan_generator_resnet( img_batch, kernel_size=kernel_size) self.assertAllEqual(img_batch.shape.as_list(), output_img_batch.shape.as_list()) def input_and_output_same_shape_kernel3(self): self._input_and_output_same_shape_helper(3) def input_and_output_same_shape_kernel4(self): self._input_and_output_same_shape_helper(4) def input_and_output_same_shape_kernel5(self): self._input_and_output_same_shape_helper(5) def input_and_output_same_shape_kernel6(self): self._input_and_output_same_shape_helper(6) def _error_if_height_not_multiple_of_four_helper(self, height): self.assertRaisesRegexp( ValueError, 'The input height must be a multiple of 4.', cyclegan.cyclegan_generator_resnet, tf.placeholder(tf.float32, shape=[None, height, 32, 3])) def test_error_if_height_not_multiple_of_four_height29(self): self._error_if_height_not_multiple_of_four_helper(29) def test_error_if_height_not_multiple_of_four_height30(self): self._error_if_height_not_multiple_of_four_helper(30) def test_error_if_height_not_multiple_of_four_height31(self): self._error_if_height_not_multiple_of_four_helper(31) def _error_if_width_not_multiple_of_four_helper(self, width): self.assertRaisesRegexp( ValueError, 'The input width must be a multiple of 4.', cyclegan.cyclegan_generator_resnet, tf.placeholder(tf.float32, shape=[None, 32, width, 3])) def test_error_if_width_not_multiple_of_four_width29(self): self._error_if_width_not_multiple_of_four_helper(29) def test_error_if_width_not_multiple_of_four_width30(self): self._error_if_width_not_multiple_of_four_helper(30) def test_error_if_width_not_multiple_of_four_width31(self): self._error_if_width_not_multiple_of_four_helper(31) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/cyclegan_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Tests for pix2pix.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import pix2pix class GeneratorTest(tf.test.TestCase): def _reduced_default_blocks(self): """Returns the default blocks, scaled down to make test run faster.""" return [pix2pix.Block(b.num_filters // 32, b.decoder_keep_prob) for b in pix2pix._default_generator_blocks()] def test_output_size_nn_upsample_conv(self): batch_size = 2 height, width = 256, 256 num_outputs = 4 images = tf.ones((batch_size, height, width, 3)) with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()): logits, _ = pix2pix.pix2pix_generator( images, num_outputs, blocks=self._reduced_default_blocks(), upsample_method='nn_upsample_conv') with self.test_session() as session: session.run(tf.global_variables_initializer()) np_outputs = session.run(logits) self.assertListEqual([batch_size, height, width, num_outputs], list(np_outputs.shape)) def test_output_size_conv2d_transpose(self): batch_size = 2 height, width = 256, 256 num_outputs = 4 images = tf.ones((batch_size, height, width, 3)) with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()): logits, _ = pix2pix.pix2pix_generator( images, num_outputs, blocks=self._reduced_default_blocks(), upsample_method='conv2d_transpose') with self.test_session() as session: session.run(tf.global_variables_initializer()) np_outputs = session.run(logits) self.assertListEqual([batch_size, height, width, num_outputs], list(np_outputs.shape)) def test_block_number_dictates_number_of_layers(self): batch_size = 2 height, width = 256, 256 num_outputs = 4 images = tf.ones((batch_size, height, width, 3)) blocks = [ pix2pix.Block(64, 0.5), pix2pix.Block(128, 0), ] with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()): _, end_points = pix2pix.pix2pix_generator( images, num_outputs, blocks) num_encoder_layers = 0 num_decoder_layers = 0 for end_point in end_points: if end_point.startswith('encoder'): num_encoder_layers += 1 elif end_point.startswith('decoder'): num_decoder_layers += 1 self.assertEqual(num_encoder_layers, len(blocks)) self.assertEqual(num_decoder_layers, len(blocks)) class DiscriminatorTest(tf.test.TestCase): def _layer_output_size(self, input_size, kernel_size=4, stride=2, pad=2): return (input_size + pad * 2 - kernel_size) // stride + 1 def test_four_layers(self): batch_size = 2 input_size = 256 output_size = self._layer_output_size(input_size) output_size = self._layer_output_size(output_size) output_size = self._layer_output_size(output_size) output_size = self._layer_output_size(output_size, stride=1) output_size = self._layer_output_size(output_size, stride=1) images = tf.ones((batch_size, input_size, input_size, 3)) with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()): logits, end_points = pix2pix.pix2pix_discriminator( images, num_filters=[64, 128, 256, 512]) self.assertListEqual([batch_size, output_size, output_size, 1], logits.shape.as_list()) self.assertListEqual([batch_size, output_size, output_size, 1], end_points['predictions'].shape.as_list()) def test_four_layers_no_padding(self): batch_size = 2 input_size = 256 output_size = self._layer_output_size(input_size, pad=0) output_size = self._layer_output_size(output_size, pad=0) output_size = self._layer_output_size(output_size, pad=0) output_size = self._layer_output_size(output_size, stride=1, pad=0) output_size = self._layer_output_size(output_size, stride=1, pad=0) images = tf.ones((batch_size, input_size, input_size, 3)) with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()): logits, end_points = pix2pix.pix2pix_discriminator( images, num_filters=[64, 128, 256, 512], padding=0) self.assertListEqual([batch_size, output_size, output_size, 1], logits.shape.as_list()) self.assertListEqual([batch_size, output_size, output_size, 1], end_points['predictions'].shape.as_list()) def test_four_layers_wrog_paddig(self): batch_size = 2 input_size = 256 images = tf.ones((batch_size, input_size, input_size, 3)) with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()): with self.assertRaises(TypeError): pix2pix.pix2pix_discriminator( images, num_filters=[64, 128, 256, 512], padding=1.5) def test_four_layers_negative_padding(self): batch_size = 2 input_size = 256 images = tf.ones((batch_size, input_size, input_size, 3)) with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()): with self.assertRaises(ValueError): pix2pix.pix2pix_discriminator( images, num_filters=[64, 128, 256, 512], padding=-1) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/pix2pix_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains a variant of the LeNet model definition.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim def lenet(images, num_classes=10, is_training=False, dropout_keep_prob=0.5, prediction_fn=slim.softmax, scope='LeNet'): """Creates a variant of the LeNet model. Note that since the output is a set of 'logits', the values fall in the interval of (-infinity, infinity). Consequently, to convert the outputs to a probability distribution over the characters, one will need to convert them using the softmax function: logits = lenet.lenet(images, is_training=False) probabilities = tf.nn.softmax(logits) predictions = tf.argmax(logits, 1) Args: images: A batch of `Tensors` of size [batch_size, height, width, channels]. num_classes: the number of classes in the dataset. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: specifies whether or not we're currently training the model. This variable will determine the behaviour of the dropout layer. dropout_keep_prob: the percentage of activation values that are retained. prediction_fn: a function to get predictions out of logits. scope: Optional variable_scope. Returns: net: a 2D Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the inon-dropped-out nput to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. """ end_points = {} with tf.variable_scope(scope, 'LeNet', [images]): net = end_points['conv1'] = slim.conv2d(images, 32, [5, 5], scope='conv1') net = end_points['pool1'] = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = end_points['conv2'] = slim.conv2d(net, 64, [5, 5], scope='conv2') net = end_points['pool2'] = slim.max_pool2d(net, [2, 2], 2, scope='pool2') net = slim.flatten(net) end_points['Flatten'] = net net = end_points['fc3'] = slim.fully_connected(net, 1024, scope='fc3') if not num_classes: return net, end_points net = end_points['dropout3'] = slim.dropout( net, dropout_keep_prob, is_training=is_training, scope='dropout3') logits = end_points['Logits'] = slim.fully_connected( net, num_classes, activation_fn=None, scope='fc4') end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points lenet.default_image_size = 28 def lenet_arg_scope(weight_decay=0.0): """Defines the default lenet argument scope. Args: weight_decay: The weight decay to use for regularizing the model. Returns: An `arg_scope` to use for the inception v3 model. """ with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/lenet.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """DCGAN generator and discriminator from https://arxiv.org/abs/1511.06434.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from math import log from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf slim = tf.contrib.slim def _validate_image_inputs(inputs): inputs.get_shape().assert_has_rank(4) inputs.get_shape()[1:3].assert_is_fully_defined() if inputs.get_shape()[1] != inputs.get_shape()[2]: raise ValueError('Input tensor does not have equal width and height: ', inputs.get_shape()[1:3]) width = inputs.get_shape().as_list()[1] if log(width, 2) != int(log(width, 2)): raise ValueError('Input tensor `width` is not a power of 2: ', width) # TODO(joelshor): Use fused batch norm by default. Investigate why some GAN # setups need the gradient of gradient FusedBatchNormGrad. def discriminator(inputs, depth=64, is_training=True, reuse=None, scope='Discriminator', fused_batch_norm=False): """Discriminator network for DCGAN. Construct discriminator network from inputs to the final endpoint. Args: inputs: A tensor of size [batch_size, height, width, channels]. Must be floating point. depth: Number of channels in first convolution layer. is_training: Whether the network is for training or not. reuse: Whether or not the network variables should be reused. `scope` must be given to be reused. scope: Optional variable_scope. fused_batch_norm: If `True`, use a faster, fused implementation of batch norm. Returns: logits: The pre-softmax activations, a tensor of size [batch_size, 1] end_points: a dictionary from components of the network to their activation. Raises: ValueError: If the input image shape is not 4-dimensional, if the spatial dimensions aren't defined at graph construction time, if the spatial dimensions aren't square, or if the spatial dimensions aren't a power of two. """ normalizer_fn = slim.batch_norm normalizer_fn_args = { 'is_training': is_training, 'zero_debias_moving_mean': True, 'fused': fused_batch_norm, } _validate_image_inputs(inputs) inp_shape = inputs.get_shape().as_list()[1] end_points = {} with tf.variable_scope(scope, values=[inputs], reuse=reuse) as scope: with slim.arg_scope([normalizer_fn], **normalizer_fn_args): with slim.arg_scope([slim.conv2d], stride=2, kernel_size=4, activation_fn=tf.nn.leaky_relu): net = inputs for i in xrange(int(log(inp_shape, 2))): scope = 'conv%i' % (i + 1) current_depth = depth * 2**i normalizer_fn_ = None if i == 0 else normalizer_fn net = slim.conv2d( net, current_depth, normalizer_fn=normalizer_fn_, scope=scope) end_points[scope] = net logits = slim.conv2d(net, 1, kernel_size=1, stride=1, padding='VALID', normalizer_fn=None, activation_fn=None) logits = tf.reshape(logits, [-1, 1]) end_points['logits'] = logits return logits, end_points # TODO(joelshor): Use fused batch norm by default. Investigate why some GAN # setups need the gradient of gradient FusedBatchNormGrad. def generator(inputs, depth=64, final_size=32, num_outputs=3, is_training=True, reuse=None, scope='Generator', fused_batch_norm=False): """Generator network for DCGAN. Construct generator network from inputs to the final endpoint. Args: inputs: A tensor with any size N. [batch_size, N] depth: Number of channels in last deconvolution layer. final_size: The shape of the final output. num_outputs: Number of output features. For images, this is the number of channels. is_training: whether is training or not. reuse: Whether or not the network has its variables should be reused. scope must be given to be reused. scope: Optional variable_scope. fused_batch_norm: If `True`, use a faster, fused implementation of batch norm. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, 32, 32, channels] end_points: a dictionary from components of the network to their activation. Raises: ValueError: If `inputs` is not 2-dimensional. ValueError: If `final_size` isn't a power of 2 or is less than 8. """ normalizer_fn = slim.batch_norm normalizer_fn_args = { 'is_training': is_training, 'zero_debias_moving_mean': True, 'fused': fused_batch_norm, } inputs.get_shape().assert_has_rank(2) if log(final_size, 2) != int(log(final_size, 2)): raise ValueError('`final_size` (%i) must be a power of 2.' % final_size) if final_size < 8: raise ValueError('`final_size` (%i) must be greater than 8.' % final_size) end_points = {} num_layers = int(log(final_size, 2)) - 1 with tf.variable_scope(scope, values=[inputs], reuse=reuse) as scope: with slim.arg_scope([normalizer_fn], **normalizer_fn_args): with slim.arg_scope([slim.conv2d_transpose], normalizer_fn=normalizer_fn, stride=2, kernel_size=4): net = tf.expand_dims(tf.expand_dims(inputs, 1), 1) # First upscaling is different because it takes the input vector. current_depth = depth * 2 ** (num_layers - 1) scope = 'deconv1' net = slim.conv2d_transpose( net, current_depth, stride=1, padding='VALID', scope=scope) end_points[scope] = net for i in xrange(2, num_layers): scope = 'deconv%i' % (i) current_depth = depth * 2 ** (num_layers - i) net = slim.conv2d_transpose(net, current_depth, scope=scope) end_points[scope] = net # Last layer has different normalizer and activation. scope = 'deconv%i' % (num_layers) net = slim.conv2d_transpose( net, depth, normalizer_fn=None, activation_fn=None, scope=scope) end_points[scope] = net # Convert to proper channels. scope = 'logits' logits = slim.conv2d( net, num_outputs, normalizer_fn=None, activation_fn=None, kernel_size=1, stride=1, padding='VALID', scope=scope) end_points[scope] = logits logits.get_shape().assert_has_rank(4) logits.get_shape().assert_is_compatible_with( [None, final_size, final_size, num_outputs]) return logits, end_points
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/dcgan.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition for inception v3 classification network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception_utils slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) def inception_v3_base(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None): """Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints registered by this function although they build the same network. Here is a mapping from the old_names to the new names: Old name | New name ======================================= conv0 | Conv2d_1a_3x3 conv1 | Conv2d_2a_3x3 conv2 | Conv2d_2b_3x3 pool1 | MaxPool_3a_3x3 conv3 | Conv2d_3b_1x1 conv4 | Conv2d_4a_3x3 pool2 | MaxPool_5a_3x3 mixed_35x35x256a | Mixed_5b mixed_35x35x288a | Mixed_5c mixed_35x35x288b | Mixed_5d mixed_17x17x768a | Mixed_6a mixed_17x17x768b | Mixed_6b mixed_17x17x768c | Mixed_6c mixed_17x17x768d | Mixed_6d mixed_17x17x768e | Mixed_6e mixed_8x8x1280a | Mixed_7a mixed_8x8x2048a | Mixed_7b mixed_8x8x2048b | Mixed_7c Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0 """ # end_points will collect relevant activations for external use, for example # summaries or losses. end_points = {} if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV3', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='VALID'): # 299 x 299 x 3 end_point = 'Conv2d_1a_3x3' net = slim.conv2d(inputs, depth(32), [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 149 x 149 x 32 end_point = 'Conv2d_2a_3x3' net = slim.conv2d(net, depth(32), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 32 end_point = 'Conv2d_2b_3x3' net = slim.conv2d(net, depth(64), [3, 3], padding='SAME', scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 64 end_point = 'MaxPool_3a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 64 end_point = 'Conv2d_3b_1x1' net = slim.conv2d(net, depth(80), [1, 1], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 80. end_point = 'Conv2d_4a_3x3' net = slim.conv2d(net, depth(192), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 71 x 71 x 192. end_point = 'MaxPool_5a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 35 x 35 x 192. # Inception blocks with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # mixed: 35 x 35 x 256. end_point = 'Mixed_5b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(32), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_1: 35 x 35 x 288. end_point = 'Mixed_5c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0b_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv_1_0c_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_2: 35 x 35 x 288. end_point = 'Mixed_5d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_3: 17 x 17 x 768. end_point = 'Mixed_6a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(384), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed4: 17 x 17 x 768. end_point = 'Mixed_6b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(128), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(128), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_5: 17 x 17 x 768. end_point = 'Mixed_6c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_6: 17 x 17 x 768. end_point = 'Mixed_6d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_7: 17 x 17 x 768. end_point = 'Mixed_6e' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_8: 8 x 8 x 1280. end_point = 'Mixed_7a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, depth(320), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') branch_1 = slim.conv2d(branch_1, depth(192), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_9: 8 x 8 x 2048. end_point = 'Mixed_7b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0b_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_10: 8 x 8 x 2048. end_point = 'Mixed_7c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0c_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def inception_v3(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, min_depth=16, depth_multiplier=1.0, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, create_aux_logits=True, scope='InceptionV3', global_pool=False): """Inception model from http://arxiv.org/abs/1512.00567. "Rethinking the Inception Architecture for Computer Vision" Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, Zbigniew Wojna. With the default arguments this method constructs the exact model defined in the paper. However, one can experiment with variations of the inception_v3 network by changing arguments dropout_keep_prob, min_depth and depth_multiplier. The default image size used to train this network is 299x299. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. is_training: whether is training or not. dropout_keep_prob: the percentage of activation values that are retained. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. create_aux_logits: Whether to create the auxiliary logits. scope: Optional variable_scope. global_pool: Optional boolean flag to control the avgpooling before the logits layer. If false or unset, pooling is done with a fixed window that reduces default-sized inputs to 1x1, while larger inputs lead to larger outputs. If true, any input size is pooled down to 1x1. Returns: net: a Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped-out input to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: if 'depth_multiplier' is less than or equal to zero. """ if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV3', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_v3_base( inputs, scope=scope, min_depth=min_depth, depth_multiplier=depth_multiplier) # Auxiliary Head logits if create_aux_logits and num_classes: with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): aux_logits = end_points['Mixed_6e'] with tf.variable_scope('AuxLogits'): aux_logits = slim.avg_pool2d( aux_logits, [5, 5], stride=3, padding='VALID', scope='AvgPool_1a_5x5') aux_logits = slim.conv2d(aux_logits, depth(128), [1, 1], scope='Conv2d_1b_1x1') # Shape of feature map before the final layer. kernel_size = _reduced_kernel_size_for_small_input( aux_logits, [5, 5]) aux_logits = slim.conv2d( aux_logits, depth(768), kernel_size, weights_initializer=trunc_normal(0.01), padding='VALID', scope='Conv2d_2a_{}x{}'.format(*kernel_size)) aux_logits = slim.conv2d( aux_logits, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, weights_initializer=trunc_normal(0.001), scope='Conv2d_2b_1x1') if spatial_squeeze: aux_logits = tf.squeeze(aux_logits, [1, 2], name='SpatialSqueeze') end_points['AuxLogits'] = aux_logits # Final pooling and prediction with tf.variable_scope('Logits'): if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='GlobalPool') end_points['global_pool'] = net else: # Pooling with a fixed kernel size. kernel_size = _reduced_kernel_size_for_small_input(net, [8, 8]) net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a_{}x{}'.format(*kernel_size)) end_points['AvgPool_1a'] = net if not num_classes: return net, end_points # 1 x 1 x 2048 net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b') end_points['PreLogits'] = net # 2048 logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_1c_1x1') if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') # 1000 end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points inception_v3.default_image_size = 299 def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough. Args: input_tensor: input tensor of size [batch_size, height, width, channels]. kernel_size: desired kernel size of length 2: [kernel_height, kernel_width] Returns: a tensor with the kernel size. TODO(jrru): Make this function work with unknown shapes. Theoretically, this can be done with the code below. Problems are two-fold: (1) If the shape was known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot handle tensors that define the kernel size. shape = tf.shape(input_tensor) return = tf.stack([tf.minimum(shape[1], kernel_size[0]), tf.minimum(shape[2], kernel_size[1])]) """ shape = input_tensor.get_shape().as_list() if shape[1] is None or shape[2] is None: kernel_size_out = kernel_size else: kernel_size_out = [min(shape[1], kernel_size[0]), min(shape[2], kernel_size[1])] return kernel_size_out inception_v3_arg_scope = inception_utils.inception_arg_scope
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v3.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition for inception v2 classification network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception_utils slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) def inception_v2_base(inputs, final_endpoint='Mixed_5c', min_depth=16, depth_multiplier=1.0, use_separable_conv=True, data_format='NHWC', scope=None): """Inception v2 (6a2). Constructs an Inception v2 network from inputs to the given final endpoint. This method can construct the network up to the layer inception(5b) as described in http://arxiv.org/abs/1502.03167. Args: inputs: a tensor of shape [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'Mixed_4a', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. use_separable_conv: Use a separable convolution for the first layer Conv2d_1a_7x7. If this is False, use a normal convolution instead. data_format: Data format of the activations ('NHWC' or 'NCHW'). scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0 """ # end_points will collect relevant activations for external use, for example # summaries or losses. end_points = {} # Used to find thinned depths for each layer. if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) if data_format != 'NHWC' and data_format != 'NCHW': raise ValueError('data_format must be either NHWC or NCHW.') if data_format == 'NCHW' and use_separable_conv: raise ValueError( 'separable convolution only supports NHWC layout. NCHW data format can' ' only be used when use_separable_conv is False.' ) concat_dim = 3 if data_format == 'NHWC' else 1 with tf.variable_scope(scope, 'InceptionV2', [inputs]): with slim.arg_scope( [slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME', data_format=data_format): # Note that sizes in the comments below assume an input spatial size of # 224x224, however, the inputs can be of any size greater 32x32. # 224 x 224 x 3 end_point = 'Conv2d_1a_7x7' if use_separable_conv: # depthwise_multiplier here is different from depth_multiplier. # depthwise_multiplier determines the output channels of the initial # depthwise conv (see docs for tf.nn.separable_conv2d), while # depth_multiplier controls the # channels of the subsequent 1x1 # convolution. Must have # in_channels * depthwise_multipler <= out_channels # so that the separable convolution is not overparameterized. depthwise_multiplier = min(int(depth(64) / 3), 8) net = slim.separable_conv2d( inputs, depth(64), [7, 7], depth_multiplier=depthwise_multiplier, stride=2, padding='SAME', weights_initializer=trunc_normal(1.0), scope=end_point) else: # Use a normal convolution instead of a separable convolution. net = slim.conv2d( inputs, depth(64), [7, 7], stride=2, weights_initializer=trunc_normal(1.0), scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 112 x 112 x 64 end_point = 'MaxPool_2a_3x3' net = slim.max_pool2d(net, [3, 3], scope=end_point, stride=2) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 56 x 56 x 64 end_point = 'Conv2d_2b_1x1' net = slim.conv2d(net, depth(64), [1, 1], scope=end_point, weights_initializer=trunc_normal(0.1)) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 56 x 56 x 64 end_point = 'Conv2d_2c_3x3' net = slim.conv2d(net, depth(192), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 56 x 56 x 192 end_point = 'MaxPool_3a_3x3' net = slim.max_pool2d(net, [3, 3], scope=end_point, stride=2) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 28 x 28 x 192 # Inception module. end_point = 'Mixed_3b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(64), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(64), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(32), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 28 x 28 x 256 end_point = 'Mixed_3c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(64), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(64), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(64), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 28 x 28 x 320 end_point = 'Mixed_4a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d( net, depth(128), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, depth(160), [3, 3], stride=2, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(64), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d( branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_1 = slim.conv2d( branch_1, depth(96), [3, 3], stride=2, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d( net, [3, 3], stride=2, scope='MaxPool_1a_3x3') net = tf.concat(axis=concat_dim, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 14 x 14 x 576 end_point = 'Mixed_4b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(224), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(64), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d( branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(96), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(128), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(128), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(128), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 14 x 14 x 576 end_point = 'Mixed_4c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(96), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(128), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(96), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(128), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(128), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(128), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 14 x 14 x 576 end_point = 'Mixed_4d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(128), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(128), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(160), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(96), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 14 x 14 x 576 end_point = 'Mixed_4e' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(96), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(128), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(160), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(192), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(192), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(96), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 14 x 14 x 576 end_point = 'Mixed_5a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d( net, depth(128), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, depth(192), [3, 3], stride=2, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(192), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(256), [3, 3], scope='Conv2d_0b_3x3') branch_1 = slim.conv2d(branch_1, depth(256), [3, 3], stride=2, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, scope='MaxPool_1a_3x3') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 7 x 7 x 1024 end_point = 'Mixed_5b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(352), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(192), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(320), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(160), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(224), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(224), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(128), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 7 x 7 x 1024 end_point = 'Mixed_5c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(352), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d( net, depth(192), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(320), [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d( net, depth(192), [1, 1], weights_initializer=trunc_normal(0.09), scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(224), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(224), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(128), [1, 1], weights_initializer=trunc_normal(0.1), scope='Conv2d_0b_1x1') net = tf.concat( axis=concat_dim, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def inception_v2(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, min_depth=16, depth_multiplier=1.0, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, scope='InceptionV2', global_pool=False): """Inception v2 model for classification. Constructs an Inception v2 network for classification as described in http://arxiv.org/abs/1502.03167. The default image size used to train this network is 224x224. Args: inputs: a tensor of shape [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. is_training: whether is training or not. dropout_keep_prob: the percentage of activation values that are retained. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. global_pool: Optional boolean flag to control the avgpooling before the logits layer. If false or unset, pooling is done with a fixed window that reduces default-sized inputs to 1x1, while larger inputs lead to larger outputs. If true, any input size is pooled down to 1x1. Returns: net: a Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped-out input to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0 """ if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') # Final pooling and prediction with tf.variable_scope(scope, 'InceptionV2', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_v2_base( inputs, scope=scope, min_depth=min_depth, depth_multiplier=depth_multiplier) with tf.variable_scope('Logits'): if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net else: # Pooling with a fixed kernel size. kernel_size = _reduced_kernel_size_for_small_input(net, [7, 7]) net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a_{}x{}'.format(*kernel_size)) end_points['AvgPool_1a'] = net if not num_classes: return net, end_points # 1 x 1 x 1024 net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b') logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_1c_1x1') if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points inception_v2.default_image_size = 224 def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough. Args: input_tensor: input tensor of size [batch_size, height, width, channels]. kernel_size: desired kernel size of length 2: [kernel_height, kernel_width] Returns: a tensor with the kernel size. TODO(jrru): Make this function work with unknown shapes. Theoretically, this can be done with the code below. Problems are two-fold: (1) If the shape was known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot handle tensors that define the kernel size. shape = tf.shape(input_tensor) return = tf.stack([tf.minimum(shape[1], kernel_size[0]), tf.minimum(shape[2], kernel_size[1])]) """ shape = input_tensor.get_shape().as_list() if shape[1] is None or shape[2] is None: kernel_size_out = kernel_size else: kernel_size_out = [min(shape[1], kernel_size[0]), min(shape[2], kernel_size[1])] return kernel_size_out inception_v2_arg_scope = inception_utils.inception_arg_scope
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v2.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains common code shared by all inception models. Usage of arg scope: with slim.arg_scope(inception_arg_scope()): logits, end_points = inception.inception_v3(images, num_classes, is_training=is_training) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim def inception_arg_scope(weight_decay=0.00004, use_batch_norm=True, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, activation_fn=tf.nn.relu, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS, batch_norm_scale=False): """Defines the default arg scope for inception models. Args: weight_decay: The weight decay to use for regularizing the model. use_batch_norm: "If `True`, batch_norm is applied after each convolution. batch_norm_decay: Decay for batch norm moving average. batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. activation_fn: Activation function for conv2d. batch_norm_updates_collections: Collection for the update ops for batch norm. batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the activations in the batch normalization layer. Returns: An `arg_scope` to use for the inception models. """ batch_norm_params = { # Decay for the moving averages. 'decay': batch_norm_decay, # epsilon to prevent 0s in variance. 'epsilon': batch_norm_epsilon, # collection containing update_ops. 'updates_collections': batch_norm_updates_collections, # use fused batch norm if possible. 'fused': None, 'scale': batch_norm_scale, } if use_batch_norm: normalizer_fn = slim.batch_norm normalizer_params = batch_norm_params else: normalizer_fn = None normalizer_params = {} # Set weight_decay for weights in Conv and FC layers. with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay)): with slim.arg_scope( [slim.conv2d], weights_initializer=slim.variance_scaling_initializer(), activation_fn=activation_fn, normalizer_fn=normalizer_fn, normalizer_params=normalizer_params) as sc: return sc
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_utils.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition for Inflated 3D Inception V1 (I3D). The network architecture is proposed by: Joao Carreira and Andrew Zisserman, Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset. https://arxiv.org/abs/1705.07750 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import i3d_utils from nets import s3dg slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) conv3d_spatiotemporal = i3d_utils.conv3d_spatiotemporal def i3d_arg_scope(weight_decay=1e-7, batch_norm_decay=0.999, batch_norm_epsilon=0.001, use_renorm=False, separable_conv3d=False): """Defines default arg_scope for I3D. Args: weight_decay: The weight decay to use for regularizing the model. batch_norm_decay: Decay for batch norm moving average. batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. use_renorm: Whether to use batch renormalization or not. separable_conv3d: Whether to use separable 3d Convs. Returns: sc: An arg_scope to use for the models. """ batch_norm_params = { # Decay for the moving averages. 'decay': batch_norm_decay, # epsilon to prevent 0s in variance. 'epsilon': batch_norm_epsilon, # Turns off fused batch norm. 'fused': False, 'renorm': use_renorm, # collection containing the moving mean and moving variance. 'variables_collections': { 'beta': None, 'gamma': None, 'moving_mean': ['moving_vars'], 'moving_variance': ['moving_vars'], } } with slim.arg_scope( [slim.conv3d, conv3d_spatiotemporal], weights_regularizer=slim.l2_regularizer(weight_decay), activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params): with slim.arg_scope( [conv3d_spatiotemporal], separable=separable_conv3d) as sc: return sc def i3d_base(inputs, final_endpoint='Mixed_5c', scope='InceptionV1'): """Defines the I3D base architecture. Note that we use the names as defined in Inception V1 to facilitate checkpoint conversion from an image-trained Inception V1 checkpoint to I3D checkpoint. Args: inputs: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. final_endpoint: Specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] scope: Optional variable_scope. Returns: A dictionary from components of the network to the corresponding activation. Raises: ValueError: if final_endpoint is not set to one of the predefined values. """ return s3dg.s3dg_base( inputs, first_temporal_kernel_size=7, temporal_conv_startat='Conv2d_2c_3x3', gating_startat=None, final_endpoint=final_endpoint, min_depth=16, depth_multiplier=1.0, data_format='NDHWC', scope=scope) def i3d(inputs, num_classes=1000, dropout_keep_prob=0.8, is_training=True, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, scope='InceptionV1'): """Defines the I3D architecture. The default image size used to train this network is 224x224. Args: inputs: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. num_classes: number of predicted classes. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, num_classes] end_points: a dictionary from components of the network to the corresponding activation. """ # Final pooling and prediction with tf.variable_scope( scope, 'InceptionV1', [inputs, num_classes], reuse=reuse) as scope: with slim.arg_scope( [slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = i3d_base(inputs, scope=scope) with tf.variable_scope('Logits'): kernel_size = i3d_utils.reduced_kernel_size_3d(net, [2, 7, 7]) net = slim.avg_pool3d( net, kernel_size, stride=1, scope='AvgPool_0a_7x7') net = slim.dropout(net, dropout_keep_prob, scope='Dropout_0b') logits = slim.conv3d( net, num_classes, [1, 1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_0c_1x1') # Temporal average pooling. logits = tf.reduce_mean(logits, axis=1) if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points i3d.default_image_size = 224
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/i3d.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for nets.inception_v2.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nets import inception slim = tf.contrib.slim class InceptionV2Test(tf.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v2(inputs, num_classes) self.assertTrue(logits.op.name.startswith( 'InceptionV2/Logits/SpatialSqueeze')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Predictions' in end_points) self.assertListEqual(end_points['Predictions'].get_shape().as_list(), [batch_size, num_classes]) def testBuildPreLogitsNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = inception.inception_v2(inputs, num_classes) self.assertTrue(net.op.name.startswith('InceptionV2/Logits/AvgPool')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 1024]) self.assertFalse('Logits' in end_points) self.assertFalse('Predictions' in end_points) def testBuildBaseNetwork(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) mixed_5c, end_points = inception.inception_v2_base(inputs) self.assertTrue(mixed_5c.op.name.startswith('InceptionV2/Mixed_5c')) self.assertListEqual(mixed_5c.get_shape().as_list(), [batch_size, 7, 7, 1024]) expected_endpoints = ['Mixed_3b', 'Mixed_3c', 'Mixed_4a', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c', 'Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpoint(self): batch_size = 5 height, width = 224, 224 endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'Mixed_4a', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = inception.inception_v2_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'InceptionV2/' + endpoint)) self.assertItemsEqual(endpoints[:index+1], end_points.keys()) def testBuildAndCheckAllEndPointsUptoMixed5c(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v2_base(inputs, final_endpoint='Mixed_5c') endpoints_shapes = {'Mixed_3b': [batch_size, 28, 28, 256], 'Mixed_3c': [batch_size, 28, 28, 320], 'Mixed_4a': [batch_size, 14, 14, 576], 'Mixed_4b': [batch_size, 14, 14, 576], 'Mixed_4c': [batch_size, 14, 14, 576], 'Mixed_4d': [batch_size, 14, 14, 576], 'Mixed_4e': [batch_size, 14, 14, 576], 'Mixed_5a': [batch_size, 7, 7, 1024], 'Mixed_5b': [batch_size, 7, 7, 1024], 'Mixed_5c': [batch_size, 7, 7, 1024], 'Conv2d_1a_7x7': [batch_size, 112, 112, 64], 'MaxPool_2a_3x3': [batch_size, 56, 56, 64], 'Conv2d_2b_1x1': [batch_size, 56, 56, 64], 'Conv2d_2c_3x3': [batch_size, 56, 56, 192], 'MaxPool_3a_3x3': [batch_size, 28, 28, 192]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testModelHasExpectedNumberOfParameters(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope(inception.inception_v2_arg_scope()): inception.inception_v2_base(inputs) total_params, _ = slim.model_analyzer.analyze_vars( slim.get_model_variables()) self.assertAlmostEqual(10173112, total_params) def testBuildEndPointsWithDepthMultiplierLessThanOne(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v2(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv')] _, end_points_with_multiplier = inception.inception_v2( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=0.5) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(0.5 * original_depth, new_depth) def testBuildEndPointsWithDepthMultiplierGreaterThanOne(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v2(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv')] _, end_points_with_multiplier = inception.inception_v2( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=2.0) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(2.0 * original_depth, new_depth) def testRaiseValueErrorWithInvalidDepthMultiplier(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) with self.assertRaises(ValueError): _ = inception.inception_v2(inputs, num_classes, depth_multiplier=-0.1) with self.assertRaises(ValueError): _ = inception.inception_v2(inputs, num_classes, depth_multiplier=0.0) def testBuildEndPointsWithUseSeparableConvolutionFalse(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v2_base(inputs) endpoint_keys = [ key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv') ] _, end_points_with_replacement = inception.inception_v2_base( inputs, use_separable_conv=False) # The endpoint shapes must be equal to the original shape even when the # separable convolution is replaced with a normal convolution. for key in endpoint_keys: original_shape = end_points[key].get_shape().as_list() self.assertTrue(key in end_points_with_replacement) new_shape = end_points_with_replacement[key].get_shape().as_list() self.assertListEqual(original_shape, new_shape) def testBuildEndPointsNCHWDataFormat(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v2_base(inputs) endpoint_keys = [ key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv') ] inputs_in_nchw = tf.random_uniform((batch_size, 3, height, width)) _, end_points_with_replacement = inception.inception_v2_base( inputs_in_nchw, use_separable_conv=False, data_format='NCHW') # With the 'NCHW' data format, all endpoint activations have a transposed # shape from the original shape with the 'NHWC' layout. for key in endpoint_keys: transposed_original_shape = tf.transpose( end_points[key], [0, 3, 1, 2]).get_shape().as_list() self.assertTrue(key in end_points_with_replacement) new_shape = end_points_with_replacement[key].get_shape().as_list() self.assertListEqual(transposed_original_shape, new_shape) def testBuildErrorsForDataFormats(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) # 'NCWH' data format is not supported. with self.assertRaises(ValueError): _ = inception.inception_v2_base(inputs, data_format='NCWH') # 'NCHW' data format is not supported for separable convolution. with self.assertRaises(ValueError): _ = inception.inception_v2_base(inputs, data_format='NCHW') def testHalfSizeImages(self): batch_size = 5 height, width = 112, 112 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v2(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_5c'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 4, 4, 1024]) def testUnknownImageShape(self): tf.reset_default_graph() batch_size = 2 height, width = 224, 224 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = inception.inception_v2(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_5c'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) def testGlobalPoolUnknownImageShape(self): tf.reset_default_graph() batch_size = 1 height, width = 250, 300 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = inception.inception_v2(inputs, num_classes, global_pool=True) self.assertTrue(logits.op.name.startswith('InceptionV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_5c'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 10, 1024]) def testUnknowBatchSize(self): batch_size = 1 height, width = 224, 224 num_classes = 1000 inputs = tf.placeholder(tf.float32, (None, height, width, 3)) logits, _ = inception.inception_v2(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV2/Logits')) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEquals(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = inception.inception_v2(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 150, 150 num_classes = 1000 train_inputs = tf.random_uniform((train_batch_size, height, width, 3)) inception.inception_v2(train_inputs, num_classes) eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3)) logits, _ = inception.inception_v2(eval_inputs, num_classes, reuse=True) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (eval_batch_size,)) def testLogitsNotSqueezed(self): num_classes = 25 images = tf.random_uniform([1, 224, 224, 3]) logits, _ = inception.inception_v2(images, num_classes=num_classes, spatial_squeeze=False) with self.test_session() as sess: tf.global_variables_initializer().run() logits_out = sess.run(logits) self.assertListEqual(list(logits_out.shape), [1, 1, 1, num_classes]) def testNoBatchNormScaleByDefault(self): height, width = 224, 224 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with slim.arg_scope(inception.inception_v2_arg_scope()): inception.inception_v2(inputs, num_classes, is_training=False) self.assertEqual(tf.global_variables('.*/BatchNorm/gamma:0$'), []) def testBatchNormScale(self): height, width = 224, 224 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with slim.arg_scope( inception.inception_v2_arg_scope(batch_norm_scale=True)): inception.inception_v2(inputs, num_classes, is_training=False) gamma_names = set( v.op.name for v in tf.global_variables('.*/BatchNorm/gamma:0$')) self.assertGreater(len(gamma_names), 0) for v in tf.global_variables('.*/BatchNorm/moving_mean:0$'): self.assertIn(v.op.name[:-len('moving_mean')] + 'gamma', gamma_names) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v2_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """MobileNet v1. MobileNet is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different head (for example: embeddings, localization and classification). As described in https://arxiv.org/abs/1704.04861. MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam 100% Mobilenet V1 (base) with input size 224x224: See mobilenet_v1() Layer params macs -------------------------------------------------------------------------------- MobilenetV1/Conv2d_0/Conv2D: 864 10,838,016 MobilenetV1/Conv2d_1_depthwise/depthwise: 288 3,612,672 MobilenetV1/Conv2d_1_pointwise/Conv2D: 2,048 25,690,112 MobilenetV1/Conv2d_2_depthwise/depthwise: 576 1,806,336 MobilenetV1/Conv2d_2_pointwise/Conv2D: 8,192 25,690,112 MobilenetV1/Conv2d_3_depthwise/depthwise: 1,152 3,612,672 MobilenetV1/Conv2d_3_pointwise/Conv2D: 16,384 51,380,224 MobilenetV1/Conv2d_4_depthwise/depthwise: 1,152 903,168 MobilenetV1/Conv2d_4_pointwise/Conv2D: 32,768 25,690,112 MobilenetV1/Conv2d_5_depthwise/depthwise: 2,304 1,806,336 MobilenetV1/Conv2d_5_pointwise/Conv2D: 65,536 51,380,224 MobilenetV1/Conv2d_6_depthwise/depthwise: 2,304 451,584 MobilenetV1/Conv2d_6_pointwise/Conv2D: 131,072 25,690,112 MobilenetV1/Conv2d_7_depthwise/depthwise: 4,608 903,168 MobilenetV1/Conv2d_7_pointwise/Conv2D: 262,144 51,380,224 MobilenetV1/Conv2d_8_depthwise/depthwise: 4,608 903,168 MobilenetV1/Conv2d_8_pointwise/Conv2D: 262,144 51,380,224 MobilenetV1/Conv2d_9_depthwise/depthwise: 4,608 903,168 MobilenetV1/Conv2d_9_pointwise/Conv2D: 262,144 51,380,224 MobilenetV1/Conv2d_10_depthwise/depthwise: 4,608 903,168 MobilenetV1/Conv2d_10_pointwise/Conv2D: 262,144 51,380,224 MobilenetV1/Conv2d_11_depthwise/depthwise: 4,608 903,168 MobilenetV1/Conv2d_11_pointwise/Conv2D: 262,144 51,380,224 MobilenetV1/Conv2d_12_depthwise/depthwise: 4,608 225,792 MobilenetV1/Conv2d_12_pointwise/Conv2D: 524,288 25,690,112 MobilenetV1/Conv2d_13_depthwise/depthwise: 9,216 451,584 MobilenetV1/Conv2d_13_pointwise/Conv2D: 1,048,576 51,380,224 -------------------------------------------------------------------------------- Total: 3,185,088 567,716,352 75% Mobilenet V1 (base) with input size 128x128: See mobilenet_v1_075() Layer params macs -------------------------------------------------------------------------------- MobilenetV1/Conv2d_0/Conv2D: 648 2,654,208 MobilenetV1/Conv2d_1_depthwise/depthwise: 216 884,736 MobilenetV1/Conv2d_1_pointwise/Conv2D: 1,152 4,718,592 MobilenetV1/Conv2d_2_depthwise/depthwise: 432 442,368 MobilenetV1/Conv2d_2_pointwise/Conv2D: 4,608 4,718,592 MobilenetV1/Conv2d_3_depthwise/depthwise: 864 884,736 MobilenetV1/Conv2d_3_pointwise/Conv2D: 9,216 9,437,184 MobilenetV1/Conv2d_4_depthwise/depthwise: 864 221,184 MobilenetV1/Conv2d_4_pointwise/Conv2D: 18,432 4,718,592 MobilenetV1/Conv2d_5_depthwise/depthwise: 1,728 442,368 MobilenetV1/Conv2d_5_pointwise/Conv2D: 36,864 9,437,184 MobilenetV1/Conv2d_6_depthwise/depthwise: 1,728 110,592 MobilenetV1/Conv2d_6_pointwise/Conv2D: 73,728 4,718,592 MobilenetV1/Conv2d_7_depthwise/depthwise: 3,456 221,184 MobilenetV1/Conv2d_7_pointwise/Conv2D: 147,456 9,437,184 MobilenetV1/Conv2d_8_depthwise/depthwise: 3,456 221,184 MobilenetV1/Conv2d_8_pointwise/Conv2D: 147,456 9,437,184 MobilenetV1/Conv2d_9_depthwise/depthwise: 3,456 221,184 MobilenetV1/Conv2d_9_pointwise/Conv2D: 147,456 9,437,184 MobilenetV1/Conv2d_10_depthwise/depthwise: 3,456 221,184 MobilenetV1/Conv2d_10_pointwise/Conv2D: 147,456 9,437,184 MobilenetV1/Conv2d_11_depthwise/depthwise: 3,456 221,184 MobilenetV1/Conv2d_11_pointwise/Conv2D: 147,456 9,437,184 MobilenetV1/Conv2d_12_depthwise/depthwise: 3,456 55,296 MobilenetV1/Conv2d_12_pointwise/Conv2D: 294,912 4,718,592 MobilenetV1/Conv2d_13_depthwise/depthwise: 6,912 110,592 MobilenetV1/Conv2d_13_pointwise/Conv2D: 589,824 9,437,184 -------------------------------------------------------------------------------- Total: 1,800,144 106,002,432 """ # Tensorflow mandates these. from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple import functools import tensorflow as tf slim = tf.contrib.slim # Conv and DepthSepConv namedtuple define layers of the MobileNet architecture # Conv defines 3x3 convolution layers # DepthSepConv defines 3x3 depthwise convolution followed by 1x1 convolution. # stride is the stride of the convolution # depth is the number of channels or filters in a layer Conv = namedtuple('Conv', ['kernel', 'stride', 'depth']) DepthSepConv = namedtuple('DepthSepConv', ['kernel', 'stride', 'depth']) # MOBILENETV1_CONV_DEFS specifies the MobileNet body MOBILENETV1_CONV_DEFS = [ Conv(kernel=[3, 3], stride=2, depth=32), DepthSepConv(kernel=[3, 3], stride=1, depth=64), DepthSepConv(kernel=[3, 3], stride=2, depth=128), DepthSepConv(kernel=[3, 3], stride=1, depth=128), DepthSepConv(kernel=[3, 3], stride=2, depth=256), DepthSepConv(kernel=[3, 3], stride=1, depth=256), DepthSepConv(kernel=[3, 3], stride=2, depth=512), DepthSepConv(kernel=[3, 3], stride=1, depth=512), DepthSepConv(kernel=[3, 3], stride=1, depth=512), DepthSepConv(kernel=[3, 3], stride=1, depth=512), DepthSepConv(kernel=[3, 3], stride=1, depth=512), DepthSepConv(kernel=[3, 3], stride=1, depth=512), DepthSepConv(kernel=[3, 3], stride=2, depth=1024), DepthSepConv(kernel=[3, 3], stride=1, depth=1024) ] def _fixed_padding(inputs, kernel_size, rate=1): """Pads the input along the spatial dimensions independently of input size. Pads the input such that if it was used in a convolution with 'VALID' padding, the output would have the same dimensions as if the unpadded input was used in a convolution with 'SAME' padding. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. rate: An integer, rate for atrous convolution. Returns: output: A tensor of size [batch, height_out, width_out, channels] with the input, either intact (if kernel_size == 1) or padded (if kernel_size > 1). """ kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1), kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)] pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1] pad_beg = [pad_total[0] // 2, pad_total[1] // 2] pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]] padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg[0], pad_end[0]], [pad_beg[1], pad_end[1]], [0, 0]]) return padded_inputs def mobilenet_v1_base(inputs, final_endpoint='Conv2d_13_pointwise', min_depth=8, depth_multiplier=1.0, conv_defs=None, output_stride=None, use_explicit_padding=False, scope=None): """Mobilenet v1. Constructs a Mobilenet v1 network from inputs to the given final endpoint. Args: inputs: a tensor of shape [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_0', 'Conv2d_1_pointwise', 'Conv2d_2_pointwise', 'Conv2d_3_pointwise', 'Conv2d_4_pointwise', 'Conv2d_5'_pointwise, 'Conv2d_6_pointwise', 'Conv2d_7_pointwise', 'Conv2d_8_pointwise', 'Conv2d_9_pointwise', 'Conv2d_10_pointwise', 'Conv2d_11_pointwise', 'Conv2d_12_pointwise', 'Conv2d_13_pointwise']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. output_stride: An integer that specifies the requested ratio of input to output spatial resolution. If not None, then we invoke atrous convolution if necessary to prevent the network from reducing the spatial resolution of the activation maps. Allowed values are 8 (accurate fully convolutional mode), 16 (fast fully convolutional mode), 32 (classification mode). use_explicit_padding: Use 'VALID' padding for convolutions, but prepad inputs so that the output dimensions are the same as if 'SAME' padding were used. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0, or the target output_stride is not allowed. """ depth = lambda d: max(int(d * depth_multiplier), min_depth) end_points = {} # Used to find thinned depths for each layer. if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') if conv_defs is None: conv_defs = MOBILENETV1_CONV_DEFS if output_stride is not None and output_stride not in [8, 16, 32]: raise ValueError('Only allowed output_stride values are 8, 16, 32.') padding = 'SAME' if use_explicit_padding: padding = 'VALID' with tf.variable_scope(scope, 'MobilenetV1', [inputs]): with slim.arg_scope([slim.conv2d, slim.separable_conv2d], padding=padding): # The current_stride variable keeps track of the output stride of the # activations, i.e., the running product of convolution strides up to the # current network layer. This allows us to invoke atrous convolution # whenever applying the next convolution would result in the activations # having output stride larger than the target output_stride. current_stride = 1 # The atrous convolution rate parameter. rate = 1 net = inputs for i, conv_def in enumerate(conv_defs): end_point_base = 'Conv2d_%d' % i if output_stride is not None and current_stride == output_stride: # If we have reached the target output_stride, then we need to employ # atrous convolution with stride=1 and multiply the atrous rate by the # current unit's stride for use in subsequent layers. layer_stride = 1 layer_rate = rate rate *= conv_def.stride else: layer_stride = conv_def.stride layer_rate = 1 current_stride *= conv_def.stride if isinstance(conv_def, Conv): end_point = end_point_base if use_explicit_padding: net = _fixed_padding(net, conv_def.kernel) net = slim.conv2d(net, depth(conv_def.depth), conv_def.kernel, stride=conv_def.stride, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points elif isinstance(conv_def, DepthSepConv): end_point = end_point_base + '_depthwise' # By passing filters=None # separable_conv2d produces only a depthwise convolution layer if use_explicit_padding: net = _fixed_padding(net, conv_def.kernel, layer_rate) net = slim.separable_conv2d(net, None, conv_def.kernel, depth_multiplier=1, stride=layer_stride, rate=layer_rate, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points end_point = end_point_base + '_pointwise' net = slim.conv2d(net, depth(conv_def.depth), [1, 1], stride=1, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points else: raise ValueError('Unknown convolution type %s for layer %d' % (conv_def.ltype, i)) raise ValueError('Unknown final endpoint %s' % final_endpoint) def mobilenet_v1(inputs, num_classes=1000, dropout_keep_prob=0.999, is_training=True, min_depth=8, depth_multiplier=1.0, conv_defs=None, prediction_fn=tf.contrib.layers.softmax, spatial_squeeze=True, reuse=None, scope='MobilenetV1', global_pool=False): """Mobilenet v1 model for classification. Args: inputs: a tensor of shape [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. global_pool: Optional boolean flag to control the avgpooling before the logits layer. If false or unset, pooling is done with a fixed window that reduces default-sized inputs to 1x1, while larger inputs lead to larger outputs. If true, any input size is pooled down to 1x1. Returns: net: a 2D Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped-out input to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: Input rank is invalid. """ input_shape = inputs.get_shape().as_list() if len(input_shape) != 4: raise ValueError('Invalid input tensor rank, expected 4, was: %d' % len(input_shape)) with tf.variable_scope(scope, 'MobilenetV1', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = mobilenet_v1_base(inputs, scope=scope, min_depth=min_depth, depth_multiplier=depth_multiplier, conv_defs=conv_defs) with tf.variable_scope('Logits'): if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net else: # Pooling with a fixed kernel size. kernel_size = _reduced_kernel_size_for_small_input(net, [7, 7]) net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a') end_points['AvgPool_1a'] = net if not num_classes: return net, end_points # 1 x 1 x 1024 net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b') logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_1c_1x1') if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits if prediction_fn: end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points mobilenet_v1.default_image_size = 224 def wrapped_partial(func, *args, **kwargs): partial_func = functools.partial(func, *args, **kwargs) functools.update_wrapper(partial_func, func) return partial_func mobilenet_v1_075 = wrapped_partial(mobilenet_v1, depth_multiplier=0.75) mobilenet_v1_050 = wrapped_partial(mobilenet_v1, depth_multiplier=0.50) mobilenet_v1_025 = wrapped_partial(mobilenet_v1, depth_multiplier=0.25) def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are large enough. Args: input_tensor: input tensor of size [batch_size, height, width, channels]. kernel_size: desired kernel size of length 2: [kernel_height, kernel_width] Returns: a tensor with the kernel size. """ shape = input_tensor.get_shape().as_list() if shape[1] is None or shape[2] is None: kernel_size_out = kernel_size else: kernel_size_out = [min(shape[1], kernel_size[0]), min(shape[2], kernel_size[1])] return kernel_size_out def mobilenet_v1_arg_scope( is_training=True, weight_decay=0.00004, stddev=0.09, regularize_depthwise=False, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS, normalizer_fn=slim.batch_norm): """Defines the default MobilenetV1 arg scope. Args: is_training: Whether or not we're training the model. If this is set to None, the parameter is not added to the batch_norm arg_scope. weight_decay: The weight decay to use for regularizing the model. stddev: The standard deviation of the trunctated normal weight initializer. regularize_depthwise: Whether or not apply regularization on depthwise. batch_norm_decay: Decay for batch norm moving average. batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. batch_norm_updates_collections: Collection for the update ops for batch norm. normalizer_fn: Normalization function to apply after convolution. Returns: An `arg_scope` to use for the mobilenet v1 model. """ batch_norm_params = { 'center': True, 'scale': True, 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'updates_collections': batch_norm_updates_collections, } if is_training is not None: batch_norm_params['is_training'] = is_training # Set weight_decay for weights in Conv and DepthSepConv layers. weights_init = tf.truncated_normal_initializer(stddev=stddev) regularizer = tf.contrib.layers.l2_regularizer(weight_decay) if regularize_depthwise: depthwise_regularizer = regularizer else: depthwise_regularizer = None with slim.arg_scope([slim.conv2d, slim.separable_conv2d], weights_initializer=weights_init, activation_fn=tf.nn.relu6, normalizer_fn=normalizer_fn): with slim.arg_scope([slim.batch_norm], **batch_norm_params): with slim.arg_scope([slim.conv2d], weights_regularizer=regularizer): with slim.arg_scope([slim.separable_conv2d], weights_regularizer=depthwise_regularizer) as sc: return sc
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet_v1.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for dcgan.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from nets import dcgan class DCGANTest(tf.test.TestCase): def test_generator_run(self): tf.set_random_seed(1234) noise = tf.random_normal([100, 64]) image, _ = dcgan.generator(noise) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) image.eval() def test_generator_graph(self): tf.set_random_seed(1234) # Check graph construction for a number of image size/depths and batch # sizes. for i, batch_size in zip(xrange(3, 7), xrange(3, 8)): tf.reset_default_graph() final_size = 2 ** i noise = tf.random_normal([batch_size, 64]) image, end_points = dcgan.generator( noise, depth=32, final_size=final_size) self.assertAllEqual([batch_size, final_size, final_size, 3], image.shape.as_list()) expected_names = ['deconv%i' % j for j in xrange(1, i)] + ['logits'] self.assertSetEqual(set(expected_names), set(end_points.keys())) # Check layer depths. for j in range(1, i): layer = end_points['deconv%i' % j] self.assertEqual(32 * 2**(i-j-1), layer.get_shape().as_list()[-1]) def test_generator_invalid_input(self): wrong_dim_input = tf.zeros([5, 32, 32]) with self.assertRaises(ValueError): dcgan.generator(wrong_dim_input) correct_input = tf.zeros([3, 2]) with self.assertRaisesRegexp(ValueError, 'must be a power of 2'): dcgan.generator(correct_input, final_size=30) with self.assertRaisesRegexp(ValueError, 'must be greater than 8'): dcgan.generator(correct_input, final_size=4) def test_discriminator_run(self): image = tf.random_uniform([5, 32, 32, 3], -1, 1) output, _ = dcgan.discriminator(image) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output.eval() def test_discriminator_graph(self): # Check graph construction for a number of image size/depths and batch # sizes. for i, batch_size in zip(xrange(1, 6), xrange(3, 8)): tf.reset_default_graph() img_w = 2 ** i image = tf.random_uniform([batch_size, img_w, img_w, 3], -1, 1) output, end_points = dcgan.discriminator( image, depth=32) self.assertAllEqual([batch_size, 1], output.get_shape().as_list()) expected_names = ['conv%i' % j for j in xrange(1, i+1)] + ['logits'] self.assertSetEqual(set(expected_names), set(end_points.keys())) # Check layer depths. for j in range(1, i+1): layer = end_points['conv%i' % j] self.assertEqual(32 * 2**(j-1), layer.get_shape().as_list()[-1]) def test_discriminator_invalid_input(self): wrong_dim_img = tf.zeros([5, 32, 32]) with self.assertRaises(ValueError): dcgan.discriminator(wrong_dim_img) spatially_undefined_shape = tf.placeholder(tf.float32, [5, 32, None, 3]) with self.assertRaises(ValueError): dcgan.discriminator(spatially_undefined_shape) not_square = tf.zeros([5, 32, 16, 3]) with self.assertRaisesRegexp(ValueError, 'not have equal width and height'): dcgan.discriminator(not_square) not_power_2 = tf.zeros([5, 30, 30, 3]) with self.assertRaisesRegexp(ValueError, 'not a power of 2'): dcgan.discriminator(not_power_2) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/dcgan_test.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.inception.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import nets_factory class NetworksTest(tf.test.TestCase): def testGetNetworkFnFirstHalf(self): batch_size = 5 num_classes = 1000 for net in list(nets_factory.networks_map.keys())[:10]: with tf.Graph().as_default() as g, self.test_session(g): net_fn = nets_factory.get_network_fn(net, num_classes=num_classes) # Most networks use 224 as their default_image_size image_size = getattr(net_fn, 'default_image_size', 224) if net not in ['i3d', 's3dg']: inputs = tf.random_uniform( (batch_size, image_size, image_size, 3)) logits, end_points = net_fn(inputs) self.assertTrue(isinstance(logits, tf.Tensor)) self.assertTrue(isinstance(end_points, dict)) self.assertEqual(logits.get_shape().as_list()[0], batch_size) self.assertEqual(logits.get_shape().as_list()[-1], num_classes) def testGetNetworkFnSecondHalf(self): batch_size = 5 num_classes = 1000 for net in list(nets_factory.networks_map.keys())[10:]: with tf.Graph().as_default() as g, self.test_session(g): net_fn = nets_factory.get_network_fn(net, num_classes=num_classes) # Most networks use 224 as their default_image_size image_size = getattr(net_fn, 'default_image_size', 224) if net not in ['i3d', 's3dg']: inputs = tf.random_uniform( (batch_size, image_size, image_size, 3)) logits, end_points = net_fn(inputs) self.assertTrue(isinstance(logits, tf.Tensor)) self.assertTrue(isinstance(end_points, dict)) self.assertEqual(logits.get_shape().as_list()[0], batch_size) self.assertEqual(logits.get_shape().as_list()[-1], num_classes) def testGetNetworkFnVideoModels(self): batch_size = 5 num_classes = 400 for net in ['i3d', 's3dg']: with tf.Graph().as_default() as g, self.test_session(g): net_fn = nets_factory.get_network_fn(net, num_classes=num_classes) # Most networks use 224 as their default_image_size image_size = getattr(net_fn, 'default_image_size', 224) // 2 inputs = tf.random_uniform( (batch_size, 10, image_size, image_size, 3)) logits, end_points = net_fn(inputs) self.assertTrue(isinstance(logits, tf.Tensor)) self.assertTrue(isinstance(end_points, dict)) self.assertEqual(logits.get_shape().as_list()[0], batch_size) self.assertEqual(logits.get_shape().as_list()[-1], num_classes) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/nets_factory_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains a variant of the CIFAR-10 model definition.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(stddev=stddev) def cifarnet(images, num_classes=10, is_training=False, dropout_keep_prob=0.5, prediction_fn=slim.softmax, scope='CifarNet'): """Creates a variant of the CifarNet model. Note that since the output is a set of 'logits', the values fall in the interval of (-infinity, infinity). Consequently, to convert the outputs to a probability distribution over the characters, one will need to convert them using the softmax function: logits = cifarnet.cifarnet(images, is_training=False) probabilities = tf.nn.softmax(logits) predictions = tf.argmax(logits, 1) Args: images: A batch of `Tensors` of size [batch_size, height, width, channels]. num_classes: the number of classes in the dataset. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: specifies whether or not we're currently training the model. This variable will determine the behaviour of the dropout layer. dropout_keep_prob: the percentage of activation values that are retained. prediction_fn: a function to get predictions out of logits. scope: Optional variable_scope. Returns: net: a 2D Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the input to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. """ end_points = {} with tf.variable_scope(scope, 'CifarNet', [images]): net = slim.conv2d(images, 64, [5, 5], scope='conv1') end_points['conv1'] = net net = slim.max_pool2d(net, [2, 2], 2, scope='pool1') end_points['pool1'] = net net = tf.nn.lrn(net, 4, bias=1.0, alpha=0.001/9.0, beta=0.75, name='norm1') net = slim.conv2d(net, 64, [5, 5], scope='conv2') end_points['conv2'] = net net = tf.nn.lrn(net, 4, bias=1.0, alpha=0.001/9.0, beta=0.75, name='norm2') net = slim.max_pool2d(net, [2, 2], 2, scope='pool2') end_points['pool2'] = net net = slim.flatten(net) end_points['Flatten'] = net net = slim.fully_connected(net, 384, scope='fc3') end_points['fc3'] = net net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout3') net = slim.fully_connected(net, 192, scope='fc4') end_points['fc4'] = net if not num_classes: return net, end_points logits = slim.fully_connected(net, num_classes, biases_initializer=tf.zeros_initializer(), weights_initializer=trunc_normal(1/192.0), weights_regularizer=None, activation_fn=None, scope='logits') end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points cifarnet.default_image_size = 32 def cifarnet_arg_scope(weight_decay=0.004): """Defines the default cifarnet argument scope. Args: weight_decay: The weight decay to use for regularizing the model. Returns: An `arg_scope` to use for the inception v3 model. """ with slim.arg_scope( [slim.conv2d], weights_initializer=tf.truncated_normal_initializer(stddev=5e-2), activation_fn=tf.nn.relu): with slim.arg_scope( [slim.fully_connected], biases_initializer=tf.constant_initializer(0.1), weights_initializer=trunc_normal(0.04), weights_regularizer=slim.l2_regularizer(weight_decay), activation_fn=tf.nn.relu) as sc: return sc
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/cifarnet.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for building I3D network models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf # Orignaly, add_arg_scope = slim.add_arg_scope and layers = slim, now switch to # more update-to-date tf.contrib.* API. add_arg_scope = tf.contrib.framework.add_arg_scope layers = tf.contrib.layers def center_initializer(): """Centering Initializer for I3D. This initializer allows identity mapping for temporal convolution at the initialization, which is critical for a desired convergence behavior for training a seprable I3D model. The centering behavior of this initializer requires an odd-sized kernel, typically set to 3. Returns: A weight initializer op used in temporal convolutional layers. Raises: ValueError: Input tensor data type has to be tf.float32. ValueError: If input tensor is not a 5-D tensor. ValueError: If input and output channel dimensions are different. ValueError: If spatial kernel sizes are not 1. ValueError: If temporal kernel size is even. """ def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument """Initializer op.""" if dtype != tf.float32 and dtype != tf.bfloat16: raise ValueError( 'Input tensor data type has to be tf.float32 or tf.bfloat16.') if len(shape) != 5: raise ValueError('Input tensor has to be 5-D.') if shape[3] != shape[4]: raise ValueError('Input and output channel dimensions must be the same.') if shape[1] != 1 or shape[2] != 1: raise ValueError('Spatial kernel sizes must be 1 (pointwise conv).') if shape[0] % 2 == 0: raise ValueError('Temporal kernel size has to be odd.') center_pos = int(shape[0] / 2) init_mat = np.zeros( [shape[0], shape[1], shape[2], shape[3], shape[4]], dtype=np.float32) for i in range(0, shape[3]): init_mat[center_pos, 0, 0, i, i] = 1.0 init_op = tf.constant(init_mat, dtype=dtype) return init_op return _initializer @add_arg_scope def conv3d_spatiotemporal(inputs, num_outputs, kernel_size, stride=1, padding='SAME', activation_fn=None, normalizer_fn=None, normalizer_params=None, weights_regularizer=None, separable=False, data_format='NDHWC', scope=''): """A wrapper for conv3d to model spatiotemporal representations. This allows switching between original 3D convolution and separable 3D convolutions for spatial and temporal features respectively. On Kinetics, seprable 3D convolutions yields better classification performance. Args: inputs: a 5-D tensor `[batch_size, depth, height, width, channels]`. num_outputs: integer, the number of output filters. kernel_size: a list of length 3 `[kernel_depth, kernel_height, kernel_width]` of the filters. Can be an int if all values are the same. stride: a list of length 3 `[stride_depth, stride_height, stride_width]`. Can be an int if all strides are the same. padding: one of `VALID` or `SAME`. activation_fn: activation function. normalizer_fn: normalization function to use instead of `biases`. normalizer_params: dictionary of normalization function parameters. weights_regularizer: Optional regularizer for the weights. separable: If `True`, use separable spatiotemporal convolutions. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. scope: scope for `variable_scope`. Returns: A tensor representing the output of the (separable) conv3d operation. """ assert len(kernel_size) == 3 if separable and kernel_size[0] != 1: spatial_kernel_size = [1, kernel_size[1], kernel_size[2]] temporal_kernel_size = [kernel_size[0], 1, 1] if isinstance(stride, list) and len(stride) == 3: spatial_stride = [1, stride[1], stride[2]] temporal_stride = [stride[0], 1, 1] else: spatial_stride = [1, stride, stride] temporal_stride = [stride, 1, 1] net = layers.conv3d( inputs, num_outputs, spatial_kernel_size, stride=spatial_stride, padding=padding, activation_fn=activation_fn, normalizer_fn=normalizer_fn, normalizer_params=normalizer_params, weights_regularizer=weights_regularizer, data_format=data_format, scope=scope) net = layers.conv3d( net, num_outputs, temporal_kernel_size, stride=temporal_stride, padding=padding, scope=scope + '/temporal', activation_fn=activation_fn, normalizer_fn=None, data_format=data_format, weights_initializer=center_initializer()) return net else: return layers.conv3d( inputs, num_outputs, kernel_size, stride=stride, padding=padding, activation_fn=activation_fn, normalizer_fn=normalizer_fn, normalizer_params=normalizer_params, weights_regularizer=weights_regularizer, data_format=data_format, scope=scope) @add_arg_scope def inception_block_v1_3d(inputs, num_outputs_0_0a, num_outputs_1_0a, num_outputs_1_0b, num_outputs_2_0a, num_outputs_2_0b, num_outputs_3_0b, temporal_kernel_size=3, self_gating_fn=None, data_format='NDHWC', scope=''): """A 3D Inception v1 block. This allows use of separable 3D convolutions and self-gating, as described in: Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Murphy, Rethinking Spatiotemporal Feature Learning For Video Understanding. https://arxiv.org/abs/1712.04851. Args: inputs: a 5-D tensor `[batch_size, depth, height, width, channels]`. num_outputs_0_0a: integer, the number of output filters for Branch 0, operation Conv2d_0a_1x1. num_outputs_1_0a: integer, the number of output filters for Branch 1, operation Conv2d_0a_1x1. num_outputs_1_0b: integer, the number of output filters for Branch 1, operation Conv2d_0b_3x3. num_outputs_2_0a: integer, the number of output filters for Branch 2, operation Conv2d_0a_1x1. num_outputs_2_0b: integer, the number of output filters for Branch 2, operation Conv2d_0b_3x3. num_outputs_3_0b: integer, the number of output filters for Branch 3, operation Conv2d_0b_1x1. temporal_kernel_size: integer, the size of the temporal convolutional filters in the conv3d_spatiotemporal blocks. self_gating_fn: function which optionally performs self-gating. Must have two arguments, `inputs` and `scope`, and return one output tensor the same size as `inputs`. If `None`, no self-gating is applied. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. scope: scope for `variable_scope`. Returns: A 5-D tensor `[batch_size, depth, height, width, out_channels]`, where `out_channels = num_outputs_0_0a + num_outputs_1_0b + num_outputs_2_0b + num_outputs_3_0b`. """ use_gating = self_gating_fn is not None with tf.variable_scope(scope): with tf.variable_scope('Branch_0'): branch_0 = layers.conv3d( inputs, num_outputs_0_0a, [1, 1, 1], scope='Conv2d_0a_1x1') if use_gating: branch_0 = self_gating_fn(branch_0, scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = layers.conv3d( inputs, num_outputs_1_0a, [1, 1, 1], scope='Conv2d_0a_1x1') branch_1 = conv3d_spatiotemporal( branch_1, num_outputs_1_0b, [temporal_kernel_size, 3, 3], scope='Conv2d_0b_3x3') if use_gating: branch_1 = self_gating_fn(branch_1, scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = layers.conv3d( inputs, num_outputs_2_0a, [1, 1, 1], scope='Conv2d_0a_1x1') branch_2 = conv3d_spatiotemporal( branch_2, num_outputs_2_0b, [temporal_kernel_size, 3, 3], scope='Conv2d_0b_3x3') if use_gating: branch_2 = self_gating_fn(branch_2, scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_3'): branch_3 = layers.max_pool3d(inputs, [3, 3, 3], scope='MaxPool_0a_3x3') branch_3 = layers.conv3d( branch_3, num_outputs_3_0b, [1, 1, 1], scope='Conv2d_0b_1x1') if use_gating: branch_3 = self_gating_fn(branch_3, scope='Conv2d_0b_1x1') index_c = data_format.index('C') assert 1 <= index_c <= 4, 'Cannot identify channel dimension.' output = tf.concat([branch_0, branch_1, branch_2, branch_3], index_c) return output def reduced_kernel_size_3d(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are large enough. Args: input_tensor: input tensor of size [batch_size, time, height, width, channels]. kernel_size: desired kernel size of length 3, corresponding to time, height and width. Returns: a tensor with the kernel size. """ assert len(kernel_size) == 3 shape = input_tensor.get_shape().as_list() assert len(shape) == 5 if None in shape[1:4]: kernel_size_out = kernel_size else: kernel_size_out = [min(shape[1], kernel_size[0]), min(shape[2], kernel_size[1]), min(shape[3], kernel_size[2])] return kernel_size_out
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/i3d_utils.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the model definition for the OverFeat network. The definition for the network was obtained from: OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus and Yann LeCun, 2014 http://arxiv.org/abs/1312.6229 Usage: with slim.arg_scope(overfeat.overfeat_arg_scope()): outputs, end_points = overfeat.overfeat(inputs) @@overfeat """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) def overfeat_arg_scope(weight_decay=0.0005): with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(weight_decay), biases_initializer=tf.zeros_initializer()): with slim.arg_scope([slim.conv2d], padding='SAME'): with slim.arg_scope([slim.max_pool2d], padding='VALID') as arg_sc: return arg_sc def overfeat(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='overfeat', global_pool=False): """Contains the model definition for the OverFeat network. The definition for the network was obtained from: OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus and Yann LeCun, 2014 http://arxiv.org/abs/1312.6229 Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 231x231. To use in fully convolutional mode, set spatial_squeeze to false. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. global_pool: Optional boolean flag. If True, the input to the classification layer is avgpooled to size 1x1, for any input size. (This is not part of the original OverFeat.) Returns: net: the output of the logits layer (if num_classes is a non-zero integer), or the non-dropped-out input to the logits layer (if num_classes is 0 or None). end_points: a dict of tensors with intermediate activations. """ with tf.variable_scope(scope, 'overfeat', [inputs]) as sc: end_points_collection = sc.original_name_scope + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d], outputs_collections=end_points_collection): net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID', scope='conv1') net = slim.max_pool2d(net, [2, 2], scope='pool1') net = slim.conv2d(net, 256, [5, 5], padding='VALID', scope='conv2') net = slim.max_pool2d(net, [2, 2], scope='pool2') net = slim.conv2d(net, 512, [3, 3], scope='conv3') net = slim.conv2d(net, 1024, [3, 3], scope='conv4') net = slim.conv2d(net, 1024, [3, 3], scope='conv5') net = slim.max_pool2d(net, [2, 2], scope='pool5') # Use conv2d instead of fully_connected layers. with slim.arg_scope([slim.conv2d], weights_initializer=trunc_normal(0.005), biases_initializer=tf.constant_initializer(0.1)): net = slim.conv2d(net, 3072, [6, 6], padding='VALID', scope='fc6') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = slim.conv2d(net, 4096, [1, 1], scope='fc7') # Convert end_points_collection into a end_point dict. end_points = slim.utils.convert_collection_to_dict( end_points_collection) if global_pool: net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if num_classes: net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, biases_initializer=tf.zeros_initializer(), scope='fc8') if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='fc8/squeezed') end_points[sc.name + '/fc8'] = net return net, end_points overfeat.default_image_size = 231
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/overfeat.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for nets.inception_v1.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from nets import inception slim = tf.contrib.slim class InceptionV1Test(tf.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) logits, end_points = inception.inception_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith( 'InceptionV1/Logits/SpatialSqueeze')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Predictions' in end_points) self.assertListEqual(end_points['Predictions'].get_shape().as_list(), [batch_size, num_classes]) def testBuildPreLogitsNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) net, end_points = inception.inception_v1(inputs, num_classes) self.assertTrue(net.op.name.startswith('InceptionV1/Logits/AvgPool')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 1024]) self.assertFalse('Logits' in end_points) self.assertFalse('Predictions' in end_points) def testBuildBaseNetwork(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) mixed_6c, end_points = inception.inception_v1_base(inputs) self.assertTrue(mixed_6c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_6c.get_shape().as_list(), [batch_size, 7, 7, 1024]) expected_endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpoint(self): batch_size = 5 height, width = 224, 224 endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] for index, endpoint in enumerate(endpoints): with tf.Graph().as_default(): inputs = tf.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = inception.inception_v1_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'InceptionV1/' + endpoint)) self.assertItemsEqual(endpoints[:index+1], end_points.keys()) def testBuildAndCheckAllEndPointsUptoMixed5c(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) _, end_points = inception.inception_v1_base(inputs, final_endpoint='Mixed_5c') endpoints_shapes = {'Conv2d_1a_7x7': [5, 112, 112, 64], 'MaxPool_2a_3x3': [5, 56, 56, 64], 'Conv2d_2b_1x1': [5, 56, 56, 64], 'Conv2d_2c_3x3': [5, 56, 56, 192], 'MaxPool_3a_3x3': [5, 28, 28, 192], 'Mixed_3b': [5, 28, 28, 256], 'Mixed_3c': [5, 28, 28, 480], 'MaxPool_4a_3x3': [5, 14, 14, 480], 'Mixed_4b': [5, 14, 14, 512], 'Mixed_4c': [5, 14, 14, 512], 'Mixed_4d': [5, 14, 14, 512], 'Mixed_4e': [5, 14, 14, 528], 'Mixed_4f': [5, 14, 14, 832], 'MaxPool_5a_2x2': [5, 7, 7, 832], 'Mixed_5b': [5, 7, 7, 832], 'Mixed_5c': [5, 7, 7, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testModelHasExpectedNumberOfParameters(self): batch_size = 5 height, width = 224, 224 inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope(inception.inception_v1_arg_scope()): inception.inception_v1_base(inputs) total_params, _ = slim.model_analyzer.analyze_vars( slim.get_model_variables()) self.assertAlmostEqual(5607184, total_params) def testHalfSizeImages(self): batch_size = 5 height, width = 112, 112 inputs = tf.random_uniform((batch_size, height, width, 3)) mixed_5c, _ = inception.inception_v1_base(inputs) self.assertTrue(mixed_5c.op.name.startswith('InceptionV1/Mixed_5c')) self.assertListEqual(mixed_5c.get_shape().as_list(), [batch_size, 4, 4, 1024]) def testUnknownImageShape(self): tf.reset_default_graph() batch_size = 2 height, width = 224, 224 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = inception.inception_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_5c'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) def testGlobalPoolUnknownImageShape(self): tf.reset_default_graph() batch_size = 1 height, width = 250, 300 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3)) logits, end_points = inception.inception_v1(inputs, num_classes, global_pool=True) self.assertTrue(logits.op.name.startswith('InceptionV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Mixed_5c'] feed_dict = {inputs: input_np} tf.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 10, 1024]) def testUnknowBatchSize(self): batch_size = 1 height, width = 224, 224 num_classes = 1000 inputs = tf.placeholder(tf.float32, (None, height, width, 3)) logits, _ = inception.inception_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('InceptionV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEquals(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 eval_inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = inception.inception_v1(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 224, 224 num_classes = 1000 train_inputs = tf.random_uniform((train_batch_size, height, width, 3)) inception.inception_v1(train_inputs, num_classes) eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3)) logits, _ = inception.inception_v1(eval_inputs, num_classes, reuse=True) predictions = tf.argmax(logits, 1) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (eval_batch_size,)) def testLogitsNotSqueezed(self): num_classes = 25 images = tf.random_uniform([1, 224, 224, 3]) logits, _ = inception.inception_v1(images, num_classes=num_classes, spatial_squeeze=False) with self.test_session() as sess: tf.global_variables_initializer().run() logits_out = sess.run(logits) self.assertListEqual(list(logits_out.shape), [1, 1, 1, num_classes]) def testNoBatchNormScaleByDefault(self): height, width = 224, 224 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with slim.arg_scope(inception.inception_v1_arg_scope()): inception.inception_v1(inputs, num_classes, is_training=False) self.assertEqual(tf.global_variables('.*/BatchNorm/gamma:0$'), []) def testBatchNormScale(self): height, width = 224, 224 num_classes = 1000 inputs = tf.placeholder(tf.float32, (1, height, width, 3)) with slim.arg_scope( inception.inception_v1_arg_scope(batch_norm_scale=True)): inception.inception_v1(inputs, num_classes, is_training=False) gamma_names = set( v.op.name for v in tf.global_variables('.*/BatchNorm/gamma:0$')) self.assertGreater(len(gamma_names), 0) for v in tf.global_variables('.*/BatchNorm/moving_mean:0$'): self.assertIn(v.op.name[:-len('moving_mean')] + 'gamma', gamma_names) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/inception_v1_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains a model definition for AlexNet. This work was first described in: ImageNet Classification with Deep Convolutional Neural Networks Alex Krizhevsky, Ilya Sutskever and Geoffrey E. Hinton and later refined in: One weird trick for parallelizing convolutional neural networks Alex Krizhevsky, 2014 Here we provide the implementation proposed in "One weird trick" and not "ImageNet Classification", as per the paper, the LRN layers have been removed. Usage: with slim.arg_scope(alexnet.alexnet_v2_arg_scope()): outputs, end_points = alexnet.alexnet_v2(inputs) @@alexnet_v2 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) def alexnet_v2_arg_scope(weight_decay=0.0005): with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, biases_initializer=tf.constant_initializer(0.1), weights_regularizer=slim.l2_regularizer(weight_decay)): with slim.arg_scope([slim.conv2d], padding='SAME'): with slim.arg_scope([slim.max_pool2d], padding='VALID') as arg_sc: return arg_sc def alexnet_v2(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='alexnet_v2', global_pool=False): """AlexNet version 2. Described in: http://arxiv.org/pdf/1404.5997v2.pdf Parameters from: github.com/akrizhevsky/cuda-convnet2/blob/master/layers/ layers-imagenet-1gpu.cfg Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224 or set global_pool=True. To use in fully convolutional mode, set spatial_squeeze to false. The LRN layers have been removed and change the initializers from random_normal_initializer to xavier_initializer. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: the number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the logits. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. global_pool: Optional boolean flag. If True, the input to the classification layer is avgpooled to size 1x1, for any input size. (This is not part of the original AlexNet.) Returns: net: the output of the logits layer (if num_classes is a non-zero integer), or the non-dropped-out input to the logits layer (if num_classes is 0 or None). end_points: a dict of tensors with intermediate activations. """ with tf.variable_scope(scope, 'alexnet_v2', [inputs]) as sc: end_points_collection = sc.original_name_scope + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d. with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d], outputs_collections=[end_points_collection]): net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID', scope='conv1') net = slim.max_pool2d(net, [3, 3], 2, scope='pool1') net = slim.conv2d(net, 192, [5, 5], scope='conv2') net = slim.max_pool2d(net, [3, 3], 2, scope='pool2') net = slim.conv2d(net, 384, [3, 3], scope='conv3') net = slim.conv2d(net, 384, [3, 3], scope='conv4') net = slim.conv2d(net, 256, [3, 3], scope='conv5') net = slim.max_pool2d(net, [3, 3], 2, scope='pool5') # Use conv2d instead of fully_connected layers. with slim.arg_scope([slim.conv2d], weights_initializer=trunc_normal(0.005), biases_initializer=tf.constant_initializer(0.1)): net = slim.conv2d(net, 4096, [5, 5], padding='VALID', scope='fc6') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = slim.conv2d(net, 4096, [1, 1], scope='fc7') # Convert end_points_collection into a end_point dict. end_points = slim.utils.convert_collection_to_dict( end_points_collection) if global_pool: net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if num_classes: net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, biases_initializer=tf.zeros_initializer(), scope='fc8') if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='fc8/squeezed') end_points[sc.name + '/fc8'] = net return net, end_points alexnet_v2.default_image_size = 224
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/alexnet.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains definitions for the preactivation form of Residual Networks. Residual networks (ResNets) were originally proposed in: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 The full preactivation 'v2' ResNet variant implemented in this module was introduced by: [2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks. arXiv: 1603.05027 The key difference of the full preactivation 'v2' variant compared to the 'v1' variant in [1] is the use of batch normalization before every weight layer. Typical use: from tensorflow.contrib.slim.nets import resnet_v2 ResNet-101 for image classification into 1000 classes: # inputs has shape [batch, 224, 224, 3] with slim.arg_scope(resnet_v2.resnet_arg_scope()): net, end_points = resnet_v2.resnet_v2_101(inputs, 1000, is_training=False) ResNet-101 for semantic segmentation into 21 classes: # inputs has shape [batch, 513, 513, 3] with slim.arg_scope(resnet_v2.resnet_arg_scope()): net, end_points = resnet_v2.resnet_v2_101(inputs, 21, is_training=False, global_pool=False, output_stride=16) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import resnet_utils slim = tf.contrib.slim resnet_arg_scope = resnet_utils.resnet_arg_scope @slim.add_arg_scope def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None): """Bottleneck residual unit variant with BN before convolutions. This is the full preactivation residual unit variant proposed in [2]. See Fig. 1(b) of [2] for its definition. Note that we use here the bottleneck variant which has an extra bottleneck layer. When putting together two consecutive ResNet blocks that use this unit, one should use stride = 2 in the last unit of the first block. Args: inputs: A tensor of size [batch, height, width, channels]. depth: The depth of the ResNet unit output. depth_bottleneck: The depth of the bottleneck layers. stride: The ResNet unit's stride. Determines the amount of downsampling of the units output compared to its input. rate: An integer, rate for atrous convolution. outputs_collections: Collection to add the ResNet unit output. scope: Optional variable_scope. Returns: The ResNet unit's output. """ with tf.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc: depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4) preact = slim.batch_norm(inputs, activation_fn=tf.nn.relu, scope='preact') if depth == depth_in: shortcut = resnet_utils.subsample(inputs, stride, 'shortcut') else: shortcut = slim.conv2d(preact, depth, [1, 1], stride=stride, normalizer_fn=None, activation_fn=None, scope='shortcut') residual = slim.conv2d(preact, depth_bottleneck, [1, 1], stride=1, scope='conv1') residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2') residual = slim.conv2d(residual, depth, [1, 1], stride=1, normalizer_fn=None, activation_fn=None, scope='conv3') output = shortcut + residual return slim.utils.collect_named_outputs(outputs_collections, sc.name, output) def resnet_v2(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope=None): """Generator for v2 (preactivation) ResNet models. This function generates a family of ResNet v2 models. See the resnet_v2_*() methods for specific model instantiations, obtained by selecting different block instantiations that produce ResNets of various depths. Training for image classification on Imagenet is usually done with [224, 224] inputs, resulting in [7, 7] feature maps at the output of the last ResNet block for the ResNets defined in [1] that have nominal stride equal to 32. However, for dense prediction tasks we advise that one uses inputs with spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In this case the feature maps at the ResNet output will have spatial shape [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1] and corners exactly aligned with the input image corners, which greatly facilitates alignment of the features to the image. Using as input [225, 225] images results in [8, 8] feature maps at the output of the last ResNet block. For dense prediction tasks, the ResNet needs to run in fully-convolutional (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all have nominal stride equal to 32 and a good choice in FCN mode is to use output_stride=16 in order to increase the density of the computed features at small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. blocks: A list of length equal to the number of ResNet blocks. Each element is a resnet_utils.Block object describing the units in the block. num_classes: Number of predicted classes for classification tasks. If 0 or None, we return the features before the logit layer. is_training: whether batch_norm layers are in training mode. global_pool: If True, we perform global average pooling before computing the logits. Set to True for image classification, False for dense prediction. output_stride: If None, then the output will be computed at the nominal network stride. If output_stride is not None, it specifies the requested ratio of input to output spatial resolution. include_root_block: If True, include the initial convolution followed by max-pooling, if False excludes it. If excluded, `inputs` should be the results of an activation-less convolution. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. To use this parameter, the input images must be smaller than 300x300 pixels, in which case the output logit layer does not contain spatial information and can be removed. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: net: A rank-4 tensor of size [batch, height_out, width_out, channels_out]. If global_pool is False, then height_out and width_out are reduced by a factor of output_stride compared to the respective height_in and width_in, else both height_out and width_out equal one. If num_classes is 0 or None, then net is the output of the last ResNet block, potentially after global average pooling. If num_classes is a non-zero integer, net contains the pre-softmax activations. end_points: A dictionary from components of the network to the corresponding activation. Raises: ValueError: If the target output_stride is not valid. """ with tf.variable_scope(scope, 'resnet_v2', [inputs], reuse=reuse) as sc: end_points_collection = sc.original_name_scope + '_end_points' with slim.arg_scope([slim.conv2d, bottleneck, resnet_utils.stack_blocks_dense], outputs_collections=end_points_collection): with slim.arg_scope([slim.batch_norm], is_training=is_training): net = inputs if include_root_block: if output_stride is not None: if output_stride % 4 != 0: raise ValueError('The output_stride needs to be a multiple of 4.') output_stride /= 4 # We do not include batch normalization or activation functions in # conv1 because the first ResNet unit will perform these. Cf. # Appendix of [2]. with slim.arg_scope([slim.conv2d], activation_fn=None, normalizer_fn=None): net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1') net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1') net = resnet_utils.stack_blocks_dense(net, blocks, output_stride) # This is needed because the pre-activation variant does not have batch # normalization or activation functions in the residual unit output. See # Appendix of [2]. net = slim.batch_norm(net, activation_fn=tf.nn.relu, scope='postnorm') # Convert end_points_collection into a dictionary of end_points. end_points = slim.utils.convert_collection_to_dict( end_points_collection) if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], name='pool5', keep_dims=True) end_points['global_pool'] = net if num_classes: net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='logits') end_points[sc.name + '/logits'] = net if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='SpatialSqueeze') end_points[sc.name + '/spatial_squeeze'] = net end_points['predictions'] = slim.softmax(net, scope='predictions') return net, end_points resnet_v2.default_image_size = 224 def resnet_v2_block(scope, base_depth, num_units, stride): """Helper function for creating a resnet_v2 bottleneck block. Args: scope: The scope of the block. base_depth: The depth of the bottleneck layer for each unit. num_units: The number of units in the block. stride: The stride of the block, implemented as a stride in the last unit. All other units have stride=1. Returns: A resnet_v2 bottleneck block. """ return resnet_utils.Block(scope, bottleneck, [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1 }] * (num_units - 1) + [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride }]) resnet_v2.default_image_size = 224 def resnet_v2_50(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v2_50'): """ResNet-50 model of [1]. See resnet_v2() for arg and return description.""" blocks = [ resnet_v2_block('block1', base_depth=64, num_units=3, stride=2), resnet_v2_block('block2', base_depth=128, num_units=4, stride=2), resnet_v2_block('block3', base_depth=256, num_units=6, stride=2), resnet_v2_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v2(inputs, blocks, num_classes, is_training=is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, reuse=reuse, scope=scope) resnet_v2_50.default_image_size = resnet_v2.default_image_size def resnet_v2_101(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v2_101'): """ResNet-101 model of [1]. See resnet_v2() for arg and return description.""" blocks = [ resnet_v2_block('block1', base_depth=64, num_units=3, stride=2), resnet_v2_block('block2', base_depth=128, num_units=4, stride=2), resnet_v2_block('block3', base_depth=256, num_units=23, stride=2), resnet_v2_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v2(inputs, blocks, num_classes, is_training=is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, reuse=reuse, scope=scope) resnet_v2_101.default_image_size = resnet_v2.default_image_size def resnet_v2_152(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v2_152'): """ResNet-152 model of [1]. See resnet_v2() for arg and return description.""" blocks = [ resnet_v2_block('block1', base_depth=64, num_units=3, stride=2), resnet_v2_block('block2', base_depth=128, num_units=8, stride=2), resnet_v2_block('block3', base_depth=256, num_units=36, stride=2), resnet_v2_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v2(inputs, blocks, num_classes, is_training=is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, reuse=reuse, scope=scope) resnet_v2_152.default_image_size = resnet_v2.default_image_size def resnet_v2_200(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v2_200'): """ResNet-200 model of [2]. See resnet_v2() for arg and return description.""" blocks = [ resnet_v2_block('block1', base_depth=64, num_units=3, stride=2), resnet_v2_block('block2', base_depth=128, num_units=24, stride=2), resnet_v2_block('block3', base_depth=256, num_units=36, stride=2), resnet_v2_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v2(inputs, blocks, num_classes, is_training=is_training, global_pool=global_pool, output_stride=output_stride, include_root_block=True, spatial_squeeze=spatial_squeeze, reuse=reuse, scope=scope) resnet_v2_200.default_image_size = resnet_v2.default_image_size
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/resnet_v2.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Implementation of the Image-to-Image Translation model. This network represents a port of the following work: Image-to-Image Translation with Conditional Adversarial Networks Phillip Isola, Jun-Yan Zhu, Tinghui Zhou and Alexei A. Efros Arxiv, 2017 https://phillipi.github.io/pix2pix/ A reference implementation written in Lua can be found at: https://github.com/phillipi/pix2pix/blob/master/models.lua """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import tensorflow as tf layers = tf.contrib.layers def pix2pix_arg_scope(): """Returns a default argument scope for isola_net. Returns: An arg scope. """ # These parameters come from the online port, which don't necessarily match # those in the paper. # TODO(nsilberman): confirm these values with Philip. instance_norm_params = { 'center': True, 'scale': True, 'epsilon': 0.00001, } with tf.contrib.framework.arg_scope( [layers.conv2d, layers.conv2d_transpose], normalizer_fn=layers.instance_norm, normalizer_params=instance_norm_params, weights_initializer=tf.random_normal_initializer(0, 0.02)) as sc: return sc def upsample(net, num_outputs, kernel_size, method='nn_upsample_conv'): """Upsamples the given inputs. Args: net: A `Tensor` of size [batch_size, height, width, filters]. num_outputs: The number of output filters. kernel_size: A list of 2 scalars or a 1x2 `Tensor` indicating the scale, relative to the inputs, of the output dimensions. For example, if kernel size is [2, 3], then the output height and width will be twice and three times the input size. method: The upsampling method. Returns: An `Tensor` which was upsampled using the specified method. Raises: ValueError: if `method` is not recognized. """ net_shape = tf.shape(net) height = net_shape[1] width = net_shape[2] if method == 'nn_upsample_conv': net = tf.image.resize_nearest_neighbor( net, [kernel_size[0] * height, kernel_size[1] * width]) net = layers.conv2d(net, num_outputs, [4, 4], activation_fn=None) elif method == 'conv2d_transpose': net = layers.conv2d_transpose( net, num_outputs, [4, 4], stride=kernel_size, activation_fn=None) else: raise ValueError('Unknown method: [%s]' % method) return net class Block( collections.namedtuple('Block', ['num_filters', 'decoder_keep_prob'])): """Represents a single block of encoder and decoder processing. The Image-to-Image translation paper works a bit differently than the original U-Net model. In particular, each block represents a single operation in the encoder which is concatenated with the corresponding decoder representation. A dropout layer follows the concatenation and convolution of the concatenated features. """ pass def _default_generator_blocks(): """Returns the default generator block definitions. Returns: A list of generator blocks. """ return [ Block(64, 0.5), Block(128, 0.5), Block(256, 0.5), Block(512, 0), Block(512, 0), Block(512, 0), Block(512, 0), ] def pix2pix_generator(net, num_outputs, blocks=None, upsample_method='nn_upsample_conv', is_training=False): # pylint: disable=unused-argument """Defines the network architecture. Args: net: A `Tensor` of size [batch, height, width, channels]. Note that the generator currently requires square inputs (e.g. height=width). num_outputs: The number of (per-pixel) outputs. blocks: A list of generator blocks or `None` to use the default generator definition. upsample_method: The method of upsampling images, one of 'nn_upsample_conv' or 'conv2d_transpose' is_training: Whether or not we're in training or testing mode. Returns: A `Tensor` representing the model output and a dictionary of model end points. Raises: ValueError: if the input heights do not match their widths. """ end_points = {} blocks = blocks or _default_generator_blocks() input_size = net.get_shape().as_list() input_size[3] = num_outputs upsample_fn = functools.partial(upsample, method=upsample_method) encoder_activations = [] ########### # Encoder # ########### with tf.variable_scope('encoder'): with tf.contrib.framework.arg_scope( [layers.conv2d], kernel_size=[4, 4], stride=2, activation_fn=tf.nn.leaky_relu): for block_id, block in enumerate(blocks): # No normalizer for the first encoder layers as per 'Image-to-Image', # Section 5.1.1 if block_id == 0: # First layer doesn't use normalizer_fn net = layers.conv2d(net, block.num_filters, normalizer_fn=None) elif block_id < len(blocks) - 1: net = layers.conv2d(net, block.num_filters) else: # Last layer doesn't use activation_fn nor normalizer_fn net = layers.conv2d( net, block.num_filters, activation_fn=None, normalizer_fn=None) encoder_activations.append(net) end_points['encoder%d' % block_id] = net ########### # Decoder # ########### reversed_blocks = list(blocks) reversed_blocks.reverse() with tf.variable_scope('decoder'): # Dropout is used at both train and test time as per 'Image-to-Image', # Section 2.1 (last paragraph). with tf.contrib.framework.arg_scope([layers.dropout], is_training=True): for block_id, block in enumerate(reversed_blocks): if block_id > 0: net = tf.concat([net, encoder_activations[-block_id - 1]], axis=3) # The Relu comes BEFORE the upsample op: net = tf.nn.relu(net) net = upsample_fn(net, block.num_filters, [2, 2]) if block.decoder_keep_prob > 0: net = layers.dropout(net, keep_prob=block.decoder_keep_prob) end_points['decoder%d' % block_id] = net with tf.variable_scope('output'): # Explicitly set the normalizer_fn to None to override any default value # that may come from an arg_scope, such as pix2pix_arg_scope. logits = layers.conv2d( net, num_outputs, [4, 4], activation_fn=None, normalizer_fn=None) logits = tf.reshape(logits, input_size) end_points['logits'] = logits end_points['predictions'] = tf.tanh(logits) return logits, end_points def pix2pix_discriminator(net, num_filters, padding=2, pad_mode='REFLECT', activation_fn=tf.nn.leaky_relu, is_training=False): """Creates the Image2Image Translation Discriminator. Args: net: A `Tensor` of size [batch_size, height, width, channels] representing the input. num_filters: A list of the filters in the discriminator. The length of the list determines the number of layers in the discriminator. padding: Amount of reflection padding applied before each convolution. pad_mode: mode for tf.pad, one of "CONSTANT", "REFLECT", or "SYMMETRIC". activation_fn: activation fn for layers.conv2d. is_training: Whether or not the model is training or testing. Returns: A logits `Tensor` of size [batch_size, N, N, 1] where N is the number of 'patches' we're attempting to discriminate and a dictionary of model end points. """ del is_training end_points = {} num_layers = len(num_filters) def padded(net, scope): if padding: with tf.variable_scope(scope): spatial_pad = tf.constant( [[0, 0], [padding, padding], [padding, padding], [0, 0]], dtype=tf.int32) return tf.pad(net, spatial_pad, pad_mode) else: return net with tf.contrib.framework.arg_scope( [layers.conv2d], kernel_size=[4, 4], stride=2, padding='valid', activation_fn=activation_fn): # No normalization on the input layer. net = layers.conv2d( padded(net, 'conv0'), num_filters[0], normalizer_fn=None, scope='conv0') end_points['conv0'] = net for i in range(1, num_layers - 1): net = layers.conv2d( padded(net, 'conv%d' % i), num_filters[i], scope='conv%d' % i) end_points['conv%d' % i] = net # Stride 1 on the last layer. net = layers.conv2d( padded(net, 'conv%d' % (num_layers - 1)), num_filters[-1], stride=1, scope='conv%d' % (num_layers - 1)) end_points['conv%d' % (num_layers - 1)] = net # 1-dim logits, stride 1, no activation, no normalization. logits = layers.conv2d( padded(net, 'conv%d' % num_layers), 1, stride=1, activation_fn=None, normalizer_fn=None, scope='conv%d' % num_layers) end_points['logits'] = logits end_points['predictions'] = tf.sigmoid(logits) return logits, end_points
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/pix2pix.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Build and train mobilenet_v1 with options for quantization.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from datasets import dataset_factory from nets import mobilenet_v1 from preprocessing import preprocessing_factory slim = tf.contrib.slim flags = tf.app.flags flags.DEFINE_string('master', '', 'Session master') flags.DEFINE_integer('task', 0, 'Task') flags.DEFINE_integer('ps_tasks', 0, 'Number of ps') flags.DEFINE_integer('batch_size', 64, 'Batch size') flags.DEFINE_integer('num_classes', 1001, 'Number of classes to distinguish') flags.DEFINE_integer('number_of_steps', None, 'Number of training steps to perform before stopping') flags.DEFINE_integer('image_size', 224, 'Input image resolution') flags.DEFINE_float('depth_multiplier', 1.0, 'Depth multiplier for mobilenet') flags.DEFINE_bool('quantize', False, 'Quantize training') flags.DEFINE_string('fine_tune_checkpoint', '', 'Checkpoint from which to start finetuning.') flags.DEFINE_string('checkpoint_dir', '', 'Directory for writing training checkpoints and logs') flags.DEFINE_string('dataset_dir', '', 'Location of dataset') flags.DEFINE_integer('log_every_n_steps', 100, 'Number of steps per log') flags.DEFINE_integer('save_summaries_secs', 100, 'How often to save summaries, secs') flags.DEFINE_integer('save_interval_secs', 100, 'How often to save checkpoints, secs') FLAGS = flags.FLAGS _LEARNING_RATE_DECAY_FACTOR = 0.94 def get_learning_rate(): if FLAGS.fine_tune_checkpoint: # If we are fine tuning a checkpoint we need to start at a lower learning # rate since we are farther along on training. return 1e-4 else: return 0.045 def get_quant_delay(): if FLAGS.fine_tune_checkpoint: # We can start quantizing immediately if we are finetuning. return 0 else: # We need to wait for the model to train a bit before we quantize if we are # training from scratch. return 250000 def imagenet_input(is_training): """Data reader for imagenet. Reads in imagenet data and performs pre-processing on the images. Args: is_training: bool specifying if train or validation dataset is needed. Returns: A batch of images and labels. """ if is_training: dataset = dataset_factory.get_dataset('imagenet', 'train', FLAGS.dataset_dir) else: dataset = dataset_factory.get_dataset('imagenet', 'validation', FLAGS.dataset_dir) provider = slim.dataset_data_provider.DatasetDataProvider( dataset, shuffle=is_training, common_queue_capacity=2 * FLAGS.batch_size, common_queue_min=FLAGS.batch_size) [image, label] = provider.get(['image', 'label']) image_preprocessing_fn = preprocessing_factory.get_preprocessing( 'mobilenet_v1', is_training=is_training) image = image_preprocessing_fn(image, FLAGS.image_size, FLAGS.image_size) images, labels = tf.train.batch( [image, label], batch_size=FLAGS.batch_size, num_threads=4, capacity=5 * FLAGS.batch_size) labels = slim.one_hot_encoding(labels, FLAGS.num_classes) return images, labels def build_model(): """Builds graph for model to train with rewrites for quantization. Returns: g: Graph with fake quantization ops and batch norm folding suitable for training quantized weights. train_tensor: Train op for execution during training. """ g = tf.Graph() with g.as_default(), tf.device( tf.train.replica_device_setter(FLAGS.ps_tasks)): inputs, labels = imagenet_input(is_training=True) with slim.arg_scope(mobilenet_v1.mobilenet_v1_arg_scope(is_training=True)): logits, _ = mobilenet_v1.mobilenet_v1( inputs, is_training=True, depth_multiplier=FLAGS.depth_multiplier, num_classes=FLAGS.num_classes) tf.losses.softmax_cross_entropy(labels, logits) # Call rewriter to produce graph with fake quant ops and folded batch norms # quant_delay delays start of quantization till quant_delay steps, allowing # for better model accuracy. if FLAGS.quantize: tf.contrib.quantize.create_training_graph(quant_delay=get_quant_delay()) total_loss = tf.losses.get_total_loss(name='total_loss') # Configure the learning rate using an exponential decay. num_epochs_per_decay = 2.5 imagenet_size = 1271167 decay_steps = int(imagenet_size / FLAGS.batch_size * num_epochs_per_decay) learning_rate = tf.train.exponential_decay( get_learning_rate(), tf.train.get_or_create_global_step(), decay_steps, _LEARNING_RATE_DECAY_FACTOR, staircase=True) opt = tf.train.GradientDescentOptimizer(learning_rate) train_tensor = slim.learning.create_train_op( total_loss, optimizer=opt) slim.summaries.add_scalar_summary(total_loss, 'total_loss', 'losses') slim.summaries.add_scalar_summary(learning_rate, 'learning_rate', 'training') return g, train_tensor def get_checkpoint_init_fn(): """Returns the checkpoint init_fn if the checkpoint is provided.""" if FLAGS.fine_tune_checkpoint: variables_to_restore = slim.get_variables_to_restore() global_step_reset = tf.assign(tf.train.get_or_create_global_step(), 0) # When restoring from a floating point model, the min/max values for # quantized weights and activations are not present. # We instruct slim to ignore variables that are missing during restoration # by setting ignore_missing_vars=True slim_init_fn = slim.assign_from_checkpoint_fn( FLAGS.fine_tune_checkpoint, variables_to_restore, ignore_missing_vars=True) def init_fn(sess): slim_init_fn(sess) # If we are restoring from a floating point model, we need to initialize # the global step to zero for the exponential decay to result in # reasonable learning rates. sess.run(global_step_reset) return init_fn else: return None def train_model(): """Trains mobilenet_v1.""" g, train_tensor = build_model() with g.as_default(): slim.learning.train( train_tensor, FLAGS.checkpoint_dir, is_chief=(FLAGS.task == 0), master=FLAGS.master, log_every_n_steps=FLAGS.log_every_n_steps, graph=g, number_of_steps=FLAGS.number_of_steps, save_summaries_secs=FLAGS.save_summaries_secs, save_interval_secs=FLAGS.save_interval_secs, init_fn=get_checkpoint_init_fn(), global_step=tf.train.get_global_step()) def main(unused_arg): train_model() if __name__ == '__main__': tf.app.run(main)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet_v1_train.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Defines the CycleGAN generator and discriminator networks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf layers = tf.contrib.layers def cyclegan_arg_scope(instance_norm_center=True, instance_norm_scale=True, instance_norm_epsilon=0.001, weights_init_stddev=0.02, weight_decay=0.0): """Returns a default argument scope for all generators and discriminators. Args: instance_norm_center: Whether instance normalization applies centering. instance_norm_scale: Whether instance normalization applies scaling. instance_norm_epsilon: Small float added to the variance in the instance normalization to avoid dividing by zero. weights_init_stddev: Standard deviation of the random values to initialize the convolution kernels with. weight_decay: Magnitude of weight decay applied to all convolution kernel variables of the generator. Returns: An arg-scope. """ instance_norm_params = { 'center': instance_norm_center, 'scale': instance_norm_scale, 'epsilon': instance_norm_epsilon, } weights_regularizer = None if weight_decay and weight_decay > 0.0: weights_regularizer = layers.l2_regularizer(weight_decay) with tf.contrib.framework.arg_scope( [layers.conv2d], normalizer_fn=layers.instance_norm, normalizer_params=instance_norm_params, weights_initializer=tf.random_normal_initializer(0, weights_init_stddev), weights_regularizer=weights_regularizer) as sc: return sc def cyclegan_upsample(net, num_outputs, stride, method='conv2d_transpose', pad_mode='REFLECT', align_corners=False): """Upsamples the given inputs. Args: net: A Tensor of size [batch_size, height, width, filters]. num_outputs: The number of output filters. stride: A list of 2 scalars or a 1x2 Tensor indicating the scale, relative to the inputs, of the output dimensions. For example, if kernel size is [2, 3], then the output height and width will be twice and three times the input size. method: The upsampling method: 'nn_upsample_conv', 'bilinear_upsample_conv', or 'conv2d_transpose'. pad_mode: mode for tf.pad, one of "CONSTANT", "REFLECT", or "SYMMETRIC". align_corners: option for method, 'bilinear_upsample_conv'. If true, the centers of the 4 corner pixels of the input and output tensors are aligned, preserving the values at the corner pixels. Returns: A Tensor which was upsampled using the specified method. Raises: ValueError: if `method` is not recognized. """ with tf.variable_scope('upconv'): net_shape = tf.shape(net) height = net_shape[1] width = net_shape[2] # Reflection pad by 1 in spatial dimensions (axes 1, 2 = h, w) to make a 3x3 # 'valid' convolution produce an output with the same dimension as the # input. spatial_pad_1 = np.array([[0, 0], [1, 1], [1, 1], [0, 0]]) if method == 'nn_upsample_conv': net = tf.image.resize_nearest_neighbor( net, [stride[0] * height, stride[1] * width]) net = tf.pad(net, spatial_pad_1, pad_mode) net = layers.conv2d(net, num_outputs, kernel_size=[3, 3], padding='valid') elif method == 'bilinear_upsample_conv': net = tf.image.resize_bilinear( net, [stride[0] * height, stride[1] * width], align_corners=align_corners) net = tf.pad(net, spatial_pad_1, pad_mode) net = layers.conv2d(net, num_outputs, kernel_size=[3, 3], padding='valid') elif method == 'conv2d_transpose': # This corrects 1 pixel offset for images with even width and height. # conv2d is left aligned and conv2d_transpose is right aligned for even # sized images (while doing 'SAME' padding). # Note: This doesn't reflect actual model in paper. net = layers.conv2d_transpose( net, num_outputs, kernel_size=[3, 3], stride=stride, padding='valid') net = net[:, 1:, 1:, :] else: raise ValueError('Unknown method: [%s]' % method) return net def _dynamic_or_static_shape(tensor): shape = tf.shape(tensor) static_shape = tf.contrib.util.constant_value(shape) return static_shape if static_shape is not None else shape def cyclegan_generator_resnet(images, arg_scope_fn=cyclegan_arg_scope, num_resnet_blocks=6, num_filters=64, upsample_fn=cyclegan_upsample, kernel_size=3, tanh_linear_slope=0.0, is_training=False): """Defines the cyclegan resnet network architecture. As closely as possible following https://github.com/junyanz/CycleGAN/blob/master/models/architectures.lua#L232 FYI: This network requires input height and width to be divisible by 4 in order to generate an output with shape equal to input shape. Assertions will catch this if input dimensions are known at graph construction time, but there's no protection if unknown at graph construction time (you'll see an error). Args: images: Input image tensor of shape [batch_size, h, w, 3]. arg_scope_fn: Function to create the global arg_scope for the network. num_resnet_blocks: Number of ResNet blocks in the middle of the generator. num_filters: Number of filters of the first hidden layer. upsample_fn: Upsampling function for the decoder part of the generator. kernel_size: Size w or list/tuple [h, w] of the filter kernels for all inner layers. tanh_linear_slope: Slope of the linear function to add to the tanh over the logits. is_training: Whether the network is created in training mode or inference only mode. Not actually needed, just for compliance with other generator network functions. Returns: A `Tensor` representing the model output and a dictionary of model end points. Raises: ValueError: If the input height or width is known at graph construction time and not a multiple of 4. """ # Neither dropout nor batch norm -> dont need is_training del is_training end_points = {} input_size = images.shape.as_list() height, width = input_size[1], input_size[2] if height and height % 4 != 0: raise ValueError('The input height must be a multiple of 4.') if width and width % 4 != 0: raise ValueError('The input width must be a multiple of 4.') num_outputs = input_size[3] if not isinstance(kernel_size, (list, tuple)): kernel_size = [kernel_size, kernel_size] kernel_height = kernel_size[0] kernel_width = kernel_size[1] pad_top = (kernel_height - 1) // 2 pad_bottom = kernel_height // 2 pad_left = (kernel_width - 1) // 2 pad_right = kernel_width // 2 paddings = np.array( [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]], dtype=np.int32) spatial_pad_3 = np.array([[0, 0], [3, 3], [3, 3], [0, 0]]) with tf.contrib.framework.arg_scope(arg_scope_fn()): ########### # Encoder # ########### with tf.variable_scope('input'): # 7x7 input stage net = tf.pad(images, spatial_pad_3, 'REFLECT') net = layers.conv2d(net, num_filters, kernel_size=[7, 7], padding='VALID') end_points['encoder_0'] = net with tf.variable_scope('encoder'): with tf.contrib.framework.arg_scope( [layers.conv2d], kernel_size=kernel_size, stride=2, activation_fn=tf.nn.relu, padding='VALID'): net = tf.pad(net, paddings, 'REFLECT') net = layers.conv2d(net, num_filters * 2) end_points['encoder_1'] = net net = tf.pad(net, paddings, 'REFLECT') net = layers.conv2d(net, num_filters * 4) end_points['encoder_2'] = net ################### # Residual Blocks # ################### with tf.variable_scope('residual_blocks'): with tf.contrib.framework.arg_scope( [layers.conv2d], kernel_size=kernel_size, stride=1, activation_fn=tf.nn.relu, padding='VALID'): for block_id in xrange(num_resnet_blocks): with tf.variable_scope('block_{}'.format(block_id)): res_net = tf.pad(net, paddings, 'REFLECT') res_net = layers.conv2d(res_net, num_filters * 4) res_net = tf.pad(res_net, paddings, 'REFLECT') res_net = layers.conv2d(res_net, num_filters * 4, activation_fn=None) net += res_net end_points['resnet_block_%d' % block_id] = net ########### # Decoder # ########### with tf.variable_scope('decoder'): with tf.contrib.framework.arg_scope( [layers.conv2d], kernel_size=kernel_size, stride=1, activation_fn=tf.nn.relu): with tf.variable_scope('decoder1'): net = upsample_fn(net, num_outputs=num_filters * 2, stride=[2, 2]) end_points['decoder1'] = net with tf.variable_scope('decoder2'): net = upsample_fn(net, num_outputs=num_filters, stride=[2, 2]) end_points['decoder2'] = net with tf.variable_scope('output'): net = tf.pad(net, spatial_pad_3, 'REFLECT') logits = layers.conv2d( net, num_outputs, [7, 7], activation_fn=None, normalizer_fn=None, padding='valid') logits = tf.reshape(logits, _dynamic_or_static_shape(images)) end_points['logits'] = logits end_points['predictions'] = tf.tanh(logits) + logits * tanh_linear_slope return end_points['predictions'], end_points
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/cyclegan.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of Mobilenet V2. Architecture: https://arxiv.org/abs/1801.04381 The base model gives 72.2% accuracy on ImageNet, with 300MMadds, 3.4 M parameters. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import functools import tensorflow as tf from nets.mobilenet import conv_blocks as ops from nets.mobilenet import mobilenet as lib slim = tf.contrib.slim op = lib.op expand_input = ops.expand_input_by_factor # pyformat: disable # Architecture: https://arxiv.org/abs/1801.04381 V2_DEF = dict( defaults={ # Note: these parameters of batch norm affect the architecture # that's why they are here and not in training_scope. (slim.batch_norm,): {'center': True, 'scale': True}, (slim.conv2d, slim.fully_connected, slim.separable_conv2d): { 'normalizer_fn': slim.batch_norm, 'activation_fn': tf.nn.relu6 }, (ops.expanded_conv,): { 'expansion_size': expand_input(6), 'split_expansion': 1, 'normalizer_fn': slim.batch_norm, 'residual': True }, (slim.conv2d, slim.separable_conv2d): {'padding': 'SAME'} }, spec=[ op(slim.conv2d, stride=2, num_outputs=32, kernel_size=[3, 3]), op(ops.expanded_conv, expansion_size=expand_input(1, divisible_by=1), num_outputs=16), op(ops.expanded_conv, stride=2, num_outputs=24), op(ops.expanded_conv, stride=1, num_outputs=24), op(ops.expanded_conv, stride=2, num_outputs=32), op(ops.expanded_conv, stride=1, num_outputs=32), op(ops.expanded_conv, stride=1, num_outputs=32), op(ops.expanded_conv, stride=2, num_outputs=64), op(ops.expanded_conv, stride=1, num_outputs=64), op(ops.expanded_conv, stride=1, num_outputs=64), op(ops.expanded_conv, stride=1, num_outputs=64), op(ops.expanded_conv, stride=1, num_outputs=96), op(ops.expanded_conv, stride=1, num_outputs=96), op(ops.expanded_conv, stride=1, num_outputs=96), op(ops.expanded_conv, stride=2, num_outputs=160), op(ops.expanded_conv, stride=1, num_outputs=160), op(ops.expanded_conv, stride=1, num_outputs=160), op(ops.expanded_conv, stride=1, num_outputs=320), op(slim.conv2d, stride=1, kernel_size=[1, 1], num_outputs=1280) ], ) # pyformat: enable @slim.add_arg_scope def mobilenet(input_tensor, num_classes=1001, depth_multiplier=1.0, scope='MobilenetV2', conv_defs=None, finegrain_classification_mode=False, min_depth=None, divisible_by=None, activation_fn=None, **kwargs): """Creates mobilenet V2 network. Inference mode is created by default. To create training use training_scope below. with tf.contrib.slim.arg_scope(mobilenet_v2.training_scope()): logits, endpoints = mobilenet_v2.mobilenet(input_tensor) Args: input_tensor: The input tensor num_classes: number of classes depth_multiplier: The multiplier applied to scale number of channels in each layer. Note: this is called depth multiplier in the paper but the name is kept for consistency with slim's model builder. scope: Scope of the operator conv_defs: Allows to override default conv def. finegrain_classification_mode: When set to True, the model will keep the last layer large even for small multipliers. Following https://arxiv.org/abs/1801.04381 suggests that it improves performance for ImageNet-type of problems. *Note* ignored if final_endpoint makes the builder exit earlier. min_depth: If provided, will ensure that all layers will have that many channels after application of depth multiplier. divisible_by: If provided will ensure that all layers # channels will be divisible by this number. activation_fn: Activation function to use, defaults to tf.nn.relu6 if not specified. **kwargs: passed directly to mobilenet.mobilenet: prediction_fn- what prediction function to use. reuse-: whether to reuse variables (if reuse set to true, scope must be given). Returns: logits/endpoints pair Raises: ValueError: On invalid arguments """ if conv_defs is None: conv_defs = V2_DEF if 'multiplier' in kwargs: raise ValueError('mobilenetv2 doesn\'t support generic ' 'multiplier parameter use "depth_multiplier" instead.') if finegrain_classification_mode: conv_defs = copy.deepcopy(conv_defs) if depth_multiplier < 1: conv_defs['spec'][-1].params['num_outputs'] /= depth_multiplier if activation_fn: conv_defs = copy.deepcopy(conv_defs) defaults = conv_defs['defaults'] conv_defaults = ( defaults[(slim.conv2d, slim.fully_connected, slim.separable_conv2d)]) conv_defaults['activation_fn'] = activation_fn depth_args = {} # NB: do not set depth_args unless they are provided to avoid overriding # whatever default depth_multiplier might have thanks to arg_scope. if min_depth is not None: depth_args['min_depth'] = min_depth if divisible_by is not None: depth_args['divisible_by'] = divisible_by with slim.arg_scope((lib.depth_multiplier,), **depth_args): return lib.mobilenet( input_tensor, num_classes=num_classes, conv_defs=conv_defs, scope=scope, multiplier=depth_multiplier, **kwargs) mobilenet.default_image_size = 224 def wrapped_partial(func, *args, **kwargs): partial_func = functools.partial(func, *args, **kwargs) functools.update_wrapper(partial_func, func) return partial_func # Wrappers for mobilenet v2 with depth-multipliers. Be noticed that # 'finegrain_classification_mode' is set to True, which means the embedding # layer will not be shrinked when given a depth-multiplier < 1.0. mobilenet_v2_140 = wrapped_partial(mobilenet, depth_multiplier=1.4) mobilenet_v2_050 = wrapped_partial(mobilenet, depth_multiplier=0.50, finegrain_classification_mode=True) mobilenet_v2_035 = wrapped_partial(mobilenet, depth_multiplier=0.35, finegrain_classification_mode=True) @slim.add_arg_scope def mobilenet_base(input_tensor, depth_multiplier=1.0, **kwargs): """Creates base of the mobilenet (no pooling and no logits) .""" return mobilenet(input_tensor, depth_multiplier=depth_multiplier, base_only=True, **kwargs) def training_scope(**kwargs): """Defines MobilenetV2 training scope. Usage: with tf.contrib.slim.arg_scope(mobilenet_v2.training_scope()): logits, endpoints = mobilenet_v2.mobilenet(input_tensor) with slim. Args: **kwargs: Passed to mobilenet.training_scope. The following parameters are supported: weight_decay- The weight decay to use for regularizing the model. stddev- Standard deviation for initialization, if negative uses xavier. dropout_keep_prob- dropout keep probability bn_decay- decay for the batch norm moving averages. Returns: An `arg_scope` to use for the mobilenet v2 model. """ return lib.training_scope(**kwargs) __all__ = ['training_scope', 'mobilenet_base', 'mobilenet', 'V2_DEF']
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet/mobilenet_v2.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet/__init__.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Mobilenet Base Class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import contextlib import copy import os import tensorflow as tf slim = tf.contrib.slim @slim.add_arg_scope def apply_activation(x, name=None, activation_fn=None): return activation_fn(x, name=name) if activation_fn else x def _fixed_padding(inputs, kernel_size, rate=1): """Pads the input along the spatial dimensions independently of input size. Pads the input such that if it was used in a convolution with 'VALID' padding, the output would have the same dimensions as if the unpadded input was used in a convolution with 'SAME' padding. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. rate: An integer, rate for atrous convolution. Returns: output: A tensor of size [batch, height_out, width_out, channels] with the input, either intact (if kernel_size == 1) or padded (if kernel_size > 1). """ kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1), kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)] pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1] pad_beg = [pad_total[0] // 2, pad_total[1] // 2] pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]] padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg[0], pad_end[0]], [pad_beg[1], pad_end[1]], [0, 0]]) return padded_inputs def _make_divisible(v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v @contextlib.contextmanager def _set_arg_scope_defaults(defaults): """Sets arg scope defaults for all items present in defaults. Args: defaults: dictionary/list of pairs, containing a mapping from function to a dictionary of default args. Yields: context manager where all defaults are set. """ if hasattr(defaults, 'items'): items = list(defaults.items()) else: items = defaults if not items: yield else: func, default_arg = items[0] with slim.arg_scope(func, **default_arg): with _set_arg_scope_defaults(items[1:]): yield @slim.add_arg_scope def depth_multiplier(output_params, multiplier, divisible_by=8, min_depth=8, **unused_kwargs): if 'num_outputs' not in output_params: return d = output_params['num_outputs'] output_params['num_outputs'] = _make_divisible(d * multiplier, divisible_by, min_depth) _Op = collections.namedtuple('Op', ['op', 'params', 'multiplier_func']) def op(opfunc, **params): multiplier = params.pop('multiplier_transorm', depth_multiplier) return _Op(opfunc, params=params, multiplier_func=multiplier) class NoOpScope(object): """No-op context manager.""" def __enter__(self): return None def __exit__(self, exc_type, exc_value, traceback): return False def safe_arg_scope(funcs, **kwargs): """Returns `slim.arg_scope` with all None arguments removed. Arguments: funcs: Functions to pass to `arg_scope`. **kwargs: Arguments to pass to `arg_scope`. Returns: arg_scope or No-op context manager. Note: can be useful if None value should be interpreted as "do not overwrite this parameter value". """ filtered_args = {name: value for name, value in kwargs.items() if value is not None} if filtered_args: return slim.arg_scope(funcs, **filtered_args) else: return NoOpScope() @slim.add_arg_scope def mobilenet_base( # pylint: disable=invalid-name inputs, conv_defs, multiplier=1.0, final_endpoint=None, output_stride=None, use_explicit_padding=False, scope=None, is_training=False): """Mobilenet base network. Constructs a network from inputs to the given final endpoint. By default the network is constructed in inference mode. To create network in training mode use: with slim.arg_scope(mobilenet.training_scope()): logits, endpoints = mobilenet_base(...) Args: inputs: a tensor of shape [batch_size, height, width, channels]. conv_defs: A list of op(...) layers specifying the net architecture. multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. final_endpoint: The name of last layer, for early termination for for V1-based networks: last layer is "layer_14", for V2: "layer_20" output_stride: An integer that specifies the requested ratio of input to output spatial resolution. If not None, then we invoke atrous convolution if necessary to prevent the network from reducing the spatial resolution of the activation maps. Allowed values are 1 or any even number, excluding zero. Typical values are 8 (accurate fully convolutional mode), 16 (fast fully convolutional mode), and 32 (classification mode). NOTE- output_stride relies on all consequent operators to support dilated operators via "rate" parameter. This might require wrapping non-conv operators to operate properly. use_explicit_padding: Use 'VALID' padding for convolutions, but prepad inputs so that the output dimensions are the same as if 'SAME' padding were used. scope: optional variable scope. is_training: How to setup batch_norm and other ops. Note: most of the time this does not need be set directly. Use mobilenet.training_scope() to set up training instead. This parameter is here for backward compatibility only. It is safe to set it to the value matching training_scope(is_training=...). It is also safe to explicitly set it to False, even if there is outer training_scope set to to training. (The network will be built in inference mode). If this is set to None, no arg_scope is added for slim.batch_norm's is_training parameter. Returns: tensor_out: output tensor. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: depth_multiplier <= 0, or the target output_stride is not allowed. """ if multiplier <= 0: raise ValueError('multiplier is not greater than zero.') # Set conv defs defaults and overrides. conv_defs_defaults = conv_defs.get('defaults', {}) conv_defs_overrides = conv_defs.get('overrides', {}) if use_explicit_padding: conv_defs_overrides = copy.deepcopy(conv_defs_overrides) conv_defs_overrides[ (slim.conv2d, slim.separable_conv2d)] = {'padding': 'VALID'} if output_stride is not None: if output_stride == 0 or (output_stride > 1 and output_stride % 2): raise ValueError('Output stride must be None, 1 or a multiple of 2.') # a) Set the tensorflow scope # b) set padding to default: note we might consider removing this # since it is also set by mobilenet_scope # c) set all defaults # d) set all extra overrides. with _scope_all(scope, default_scope='Mobilenet'), \ safe_arg_scope([slim.batch_norm], is_training=is_training), \ _set_arg_scope_defaults(conv_defs_defaults), \ _set_arg_scope_defaults(conv_defs_overrides): # The current_stride variable keeps track of the output stride of the # activations, i.e., the running product of convolution strides up to the # current network layer. This allows us to invoke atrous convolution # whenever applying the next convolution would result in the activations # having output stride larger than the target output_stride. current_stride = 1 # The atrous convolution rate parameter. rate = 1 net = inputs # Insert default parameters before the base scope which includes # any custom overrides set in mobilenet. end_points = {} scopes = {} for i, opdef in enumerate(conv_defs['spec']): params = dict(opdef.params) opdef.multiplier_func(params, multiplier) stride = params.get('stride', 1) if output_stride is not None and current_stride == output_stride: # If we have reached the target output_stride, then we need to employ # atrous convolution with stride=1 and multiply the atrous rate by the # current unit's stride for use in subsequent layers. layer_stride = 1 layer_rate = rate rate *= stride else: layer_stride = stride layer_rate = 1 current_stride *= stride # Update params. params['stride'] = layer_stride # Only insert rate to params if rate > 1. if layer_rate > 1: params['rate'] = layer_rate # Set padding if use_explicit_padding: if 'kernel_size' in params: net = _fixed_padding(net, params['kernel_size'], layer_rate) else: params['use_explicit_padding'] = True end_point = 'layer_%d' % (i + 1) try: net = opdef.op(net, **params) except Exception: print('Failed to create op %i: %r params: %r' % (i, opdef, params)) raise end_points[end_point] = net scope = os.path.dirname(net.name) scopes[scope] = end_point if final_endpoint is not None and end_point == final_endpoint: break # Add all tensors that end with 'output' to # endpoints for t in net.graph.get_operations(): scope = os.path.dirname(t.name) bn = os.path.basename(t.name) if scope in scopes and t.name.endswith('output'): end_points[scopes[scope] + '/' + bn] = t.outputs[0] return net, end_points @contextlib.contextmanager def _scope_all(scope, default_scope=None): with tf.variable_scope(scope, default_name=default_scope) as s,\ tf.name_scope(s.original_name_scope): yield s @slim.add_arg_scope def mobilenet(inputs, num_classes=1001, prediction_fn=slim.softmax, reuse=None, scope='Mobilenet', base_only=False, **mobilenet_args): """Mobilenet model for classification, supports both V1 and V2. Note: default mode is inference, use mobilenet.training_scope to create training network. Args: inputs: a tensor of shape [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. prediction_fn: a function to get predictions out of logits (default softmax). reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. base_only: if True will only create the base of the network (no pooling and no logits). **mobilenet_args: passed to mobilenet_base verbatim. - conv_defs: list of conv defs - multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. - output_stride: will ensure that the last layer has at most total stride. If the architecture calls for more stride than that provided (e.g. output_stride=16, but the architecture has 5 stride=2 operators), it will replace output_stride with fractional convolutions using Atrous Convolutions. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, num_classes] end_points: a dictionary from components of the network to the corresponding activation tensor. Raises: ValueError: Input rank is invalid. """ is_training = mobilenet_args.get('is_training', False) input_shape = inputs.get_shape().as_list() if len(input_shape) != 4: raise ValueError('Expected rank 4 input, was: %d' % len(input_shape)) with tf.variable_scope(scope, 'Mobilenet', reuse=reuse) as scope: inputs = tf.identity(inputs, 'input') net, end_points = mobilenet_base(inputs, scope=scope, **mobilenet_args) if base_only: return net, end_points net = tf.identity(net, name='embedding') with tf.variable_scope('Logits'): net = global_pool(net) end_points['global_pool'] = net if not num_classes: return net, end_points net = slim.dropout(net, scope='Dropout', is_training=is_training) # 1 x 1 x num_classes # Note: legacy scope name. logits = slim.conv2d( net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, biases_initializer=tf.zeros_initializer(), scope='Conv2d_1c_1x1') logits = tf.squeeze(logits, [1, 2]) logits = tf.identity(logits, name='output') end_points['Logits'] = logits if prediction_fn: end_points['Predictions'] = prediction_fn(logits, 'Predictions') return logits, end_points def global_pool(input_tensor, pool_op=tf.nn.avg_pool): """Applies avg pool to produce 1x1 output. NOTE: This function is funcitonally equivalenet to reduce_mean, but it has baked in average pool which has better support across hardware. Args: input_tensor: input tensor pool_op: pooling op (avg pool is default) Returns: a tensor batch_size x 1 x 1 x depth. """ shape = input_tensor.get_shape().as_list() if shape[1] is None or shape[2] is None: kernel_size = tf.convert_to_tensor( [1, tf.shape(input_tensor)[1], tf.shape(input_tensor)[2], 1]) else: kernel_size = [1, shape[1], shape[2], 1] output = pool_op( input_tensor, ksize=kernel_size, strides=[1, 1, 1, 1], padding='VALID') # Recover output shape, for unknown shape. output.set_shape([None, 1, 1, None]) return output def training_scope(is_training=True, weight_decay=0.00004, stddev=0.09, dropout_keep_prob=0.8, bn_decay=0.997): """Defines Mobilenet training scope. Usage: with tf.contrib.slim.arg_scope(mobilenet.training_scope()): logits, endpoints = mobilenet_v2.mobilenet(input_tensor) # the network created will be trainble with dropout/batch norm # initialized appropriately. Args: is_training: if set to False this will ensure that all customizations are set to non-training mode. This might be helpful for code that is reused across both training/evaluation, but most of the time training_scope with value False is not needed. If this is set to None, the parameters is not added to the batch_norm arg_scope. weight_decay: The weight decay to use for regularizing the model. stddev: Standard deviation for initialization, if negative uses xavier. dropout_keep_prob: dropout keep probability (not set if equals to None). bn_decay: decay for the batch norm moving averages (not set if equals to None). Returns: An argument scope to use via arg_scope. """ # Note: do not introduce parameters that would change the inference # model here (for example whether to use bias), modify conv_def instead. batch_norm_params = { 'decay': bn_decay, 'is_training': is_training } if stddev < 0: weight_intitializer = slim.initializers.xavier_initializer() else: weight_intitializer = tf.truncated_normal_initializer(stddev=stddev) # Set weight_decay for weights in Conv and FC layers. with slim.arg_scope( [slim.conv2d, slim.fully_connected, slim.separable_conv2d], weights_initializer=weight_intitializer, normalizer_fn=slim.batch_norm), \ slim.arg_scope([mobilenet_base, mobilenet], is_training=is_training),\ safe_arg_scope([slim.batch_norm], **batch_norm_params), \ safe_arg_scope([slim.dropout], is_training=is_training, keep_prob=dropout_keep_prob), \ slim.arg_scope([slim.conv2d], \ weights_regularizer=slim.l2_regularizer(weight_decay)), \ slim.arg_scope([slim.separable_conv2d], weights_regularizer=None) as s: return s
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet/mobilenet.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for mobilenet_v2.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import tensorflow as tf from nets.mobilenet import conv_blocks as ops from nets.mobilenet import mobilenet from nets.mobilenet import mobilenet_v2 slim = tf.contrib.slim def find_ops(optype): """Find ops of a given type in graphdef or a graph. Args: optype: operation type (e.g. Conv2D) Returns: List of operations. """ gd = tf.get_default_graph() return [var for var in gd.get_operations() if var.type == optype] class MobilenetV2Test(tf.test.TestCase): def setUp(self): tf.reset_default_graph() def testCreation(self): spec = dict(mobilenet_v2.V2_DEF) _, ep = mobilenet.mobilenet( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=spec) num_convs = len(find_ops('Conv2D')) # This is mostly a sanity test. No deep reason for these particular # constants. # # All but first 2 and last one have two convolutions, and there is one # extra conv that is not in the spec. (logits) self.assertEqual(num_convs, len(spec['spec']) * 2 - 2) # Check that depthwise are exposed. for i in range(2, 17): self.assertIn('layer_%d/depthwise_output' % i, ep) def testCreationNoClasses(self): spec = copy.deepcopy(mobilenet_v2.V2_DEF) net, ep = mobilenet.mobilenet( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=spec, num_classes=None) self.assertIs(net, ep['global_pool']) def testImageSizes(self): for input_size, output_size in [(224, 7), (192, 6), (160, 5), (128, 4), (96, 3)]: tf.reset_default_graph() _, ep = mobilenet_v2.mobilenet( tf.placeholder(tf.float32, (10, input_size, input_size, 3))) self.assertEqual(ep['layer_18/output'].get_shape().as_list()[1:3], [output_size] * 2) def testWithSplits(self): spec = copy.deepcopy(mobilenet_v2.V2_DEF) spec['overrides'] = { (ops.expanded_conv,): dict(split_expansion=2), } _, _ = mobilenet.mobilenet( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=spec) num_convs = len(find_ops('Conv2D')) # All but 3 op has 3 conv operatore, the remainign 3 have one # and there is one unaccounted. self.assertEqual(num_convs, len(spec['spec']) * 3 - 5) def testWithOutputStride8(self): out, _ = mobilenet.mobilenet_base( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=mobilenet_v2.V2_DEF, output_stride=8, scope='MobilenetV2') self.assertEqual(out.get_shape().as_list()[1:3], [28, 28]) def testDivisibleBy(self): tf.reset_default_graph() mobilenet_v2.mobilenet( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=mobilenet_v2.V2_DEF, divisible_by=16, min_depth=32) s = [op.outputs[0].get_shape().as_list()[-1] for op in find_ops('Conv2D')] s = set(s) self.assertSameElements([32, 64, 96, 160, 192, 320, 384, 576, 960, 1280, 1001], s) def testDivisibleByWithArgScope(self): tf.reset_default_graph() # Verifies that depth_multiplier arg scope actually works # if no default min_depth is provided. with slim.arg_scope((mobilenet.depth_multiplier,), min_depth=32): mobilenet_v2.mobilenet( tf.placeholder(tf.float32, (10, 224, 224, 2)), conv_defs=mobilenet_v2.V2_DEF, depth_multiplier=0.1) s = [op.outputs[0].get_shape().as_list()[-1] for op in find_ops('Conv2D')] s = set(s) self.assertSameElements(s, [32, 192, 128, 1001]) def testFineGrained(self): tf.reset_default_graph() # Verifies that depth_multiplier arg scope actually works # if no default min_depth is provided. mobilenet_v2.mobilenet( tf.placeholder(tf.float32, (10, 224, 224, 2)), conv_defs=mobilenet_v2.V2_DEF, depth_multiplier=0.01, finegrain_classification_mode=True) s = [op.outputs[0].get_shape().as_list()[-1] for op in find_ops('Conv2D')] s = set(s) # All convolutions will be 8->48, except for the last one. self.assertSameElements(s, [8, 48, 1001, 1280]) def testMobilenetBase(self): tf.reset_default_graph() # Verifies that mobilenet_base returns pre-pooling layer. with slim.arg_scope((mobilenet.depth_multiplier,), min_depth=32): net, _ = mobilenet_v2.mobilenet_base( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=mobilenet_v2.V2_DEF, depth_multiplier=0.1) self.assertEqual(net.get_shape().as_list(), [10, 7, 7, 128]) def testWithOutputStride16(self): tf.reset_default_graph() out, _ = mobilenet.mobilenet_base( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=mobilenet_v2.V2_DEF, output_stride=16) self.assertEqual(out.get_shape().as_list()[1:3], [14, 14]) def testWithOutputStride8AndExplicitPadding(self): tf.reset_default_graph() out, _ = mobilenet.mobilenet_base( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=mobilenet_v2.V2_DEF, output_stride=8, use_explicit_padding=True, scope='MobilenetV2') self.assertEqual(out.get_shape().as_list()[1:3], [28, 28]) def testWithOutputStride16AndExplicitPadding(self): tf.reset_default_graph() out, _ = mobilenet.mobilenet_base( tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=mobilenet_v2.V2_DEF, output_stride=16, use_explicit_padding=True) self.assertEqual(out.get_shape().as_list()[1:3], [14, 14]) def testBatchNormScopeDoesNotHaveIsTrainingWhenItsSetToNone(self): sc = mobilenet.training_scope(is_training=None) self.assertNotIn('is_training', sc[slim.arg_scope_func_key( slim.batch_norm)]) def testBatchNormScopeDoesHasIsTrainingWhenItsNotNone(self): sc = mobilenet.training_scope(is_training=False) self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) sc = mobilenet.training_scope(is_training=True) self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) sc = mobilenet.training_scope() self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet/mobilenet_v2_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Convolution blocks for mobilenet.""" import contextlib import functools import tensorflow as tf slim = tf.contrib.slim def _fixed_padding(inputs, kernel_size, rate=1): """Pads the input along the spatial dimensions independently of input size. Pads the input such that if it was used in a convolution with 'VALID' padding, the output would have the same dimensions as if the unpadded input was used in a convolution with 'SAME' padding. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. rate: An integer, rate for atrous convolution. Returns: output: A tensor of size [batch, height_out, width_out, channels] with the input, either intact (if kernel_size == 1) or padded (if kernel_size > 1). """ kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1), kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)] pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1] pad_beg = [pad_total[0] // 2, pad_total[1] // 2] pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]] padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg[0], pad_end[0]], [pad_beg[1], pad_end[1]], [0, 0]]) return padded_inputs def _make_divisible(v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v def _split_divisible(num, num_ways, divisible_by=8): """Evenly splits num, num_ways so each piece is a multiple of divisible_by.""" assert num % divisible_by == 0 assert num / num_ways >= divisible_by # Note: want to round down, we adjust each split to match the total. base = num // num_ways // divisible_by * divisible_by result = [] accumulated = 0 for i in range(num_ways): r = base while accumulated + r < num * (i + 1) / num_ways: r += divisible_by result.append(r) accumulated += r assert accumulated == num return result @contextlib.contextmanager def _v1_compatible_scope_naming(scope): if scope is None: # Create uniqified separable blocks. with tf.variable_scope(None, default_name='separable') as s, \ tf.name_scope(s.original_name_scope): yield '' else: # We use scope_depthwise, scope_pointwise for compatibility with V1 ckpts. # which provide numbered scopes. scope += '_' yield scope @slim.add_arg_scope def split_separable_conv2d(input_tensor, num_outputs, scope=None, normalizer_fn=None, stride=1, rate=1, endpoints=None, use_explicit_padding=False): """Separable mobilenet V1 style convolution. Depthwise convolution, with default non-linearity, followed by 1x1 depthwise convolution. This is similar to slim.separable_conv2d, but differs in tha it applies batch normalization and non-linearity to depthwise. This matches the basic building of Mobilenet Paper (https://arxiv.org/abs/1704.04861) Args: input_tensor: input num_outputs: number of outputs scope: optional name of the scope. Note if provided it will use scope_depthwise for deptwhise, and scope_pointwise for pointwise. normalizer_fn: which normalizer function to use for depthwise/pointwise stride: stride rate: output rate (also known as dilation rate) endpoints: optional, if provided, will export additional tensors to it. use_explicit_padding: Use 'VALID' padding for convolutions, but prepad inputs so that the output dimensions are the same as if 'SAME' padding were used. Returns: output tesnor """ with _v1_compatible_scope_naming(scope) as scope: dw_scope = scope + 'depthwise' endpoints = endpoints if endpoints is not None else {} kernel_size = [3, 3] padding = 'SAME' if use_explicit_padding: padding = 'VALID' input_tensor = _fixed_padding(input_tensor, kernel_size, rate) net = slim.separable_conv2d( input_tensor, None, kernel_size, depth_multiplier=1, stride=stride, rate=rate, normalizer_fn=normalizer_fn, padding=padding, scope=dw_scope) endpoints[dw_scope] = net pw_scope = scope + 'pointwise' net = slim.conv2d( net, num_outputs, [1, 1], stride=1, normalizer_fn=normalizer_fn, scope=pw_scope) endpoints[pw_scope] = net return net def expand_input_by_factor(n, divisible_by=8): return lambda num_inputs, **_: _make_divisible(num_inputs * n, divisible_by) @slim.add_arg_scope def expanded_conv(input_tensor, num_outputs, expansion_size=expand_input_by_factor(6), stride=1, rate=1, kernel_size=(3, 3), residual=True, normalizer_fn=None, project_activation_fn=tf.identity, split_projection=1, split_expansion=1, expansion_transform=None, depthwise_location='expansion', depthwise_channel_multiplier=1, endpoints=None, use_explicit_padding=False, padding='SAME', scope=None): """Depthwise Convolution Block with expansion. Builds a composite convolution that has the following structure expansion (1x1) -> depthwise (kernel_size) -> projection (1x1) Args: input_tensor: input num_outputs: number of outputs in the final layer. expansion_size: the size of expansion, could be a constant or a callable. If latter it will be provided 'num_inputs' as an input. For forward compatibility it should accept arbitrary keyword arguments. Default will expand the input by factor of 6. stride: depthwise stride rate: depthwise rate kernel_size: depthwise kernel residual: whether to include residual connection between input and output. normalizer_fn: batchnorm or otherwise project_activation_fn: activation function for the project layer split_projection: how many ways to split projection operator (that is conv expansion->bottleneck) split_expansion: how many ways to split expansion op (that is conv bottleneck->expansion) ops will keep depth divisible by this value. expansion_transform: Optional function that takes expansion as a single input and returns output. depthwise_location: where to put depthwise covnvolutions supported values None, 'input', 'output', 'expansion' depthwise_channel_multiplier: depthwise channel multiplier: each input will replicated (with different filters) that many times. So if input had c channels, output will have c x depthwise_channel_multpilier. endpoints: An optional dictionary into which intermediate endpoints are placed. The keys "expansion_output", "depthwise_output", "projection_output" and "expansion_transform" are always populated, even if the corresponding functions are not invoked. use_explicit_padding: Use 'VALID' padding for convolutions, but prepad inputs so that the output dimensions are the same as if 'SAME' padding were used. padding: Padding type to use if `use_explicit_padding` is not set. scope: optional scope. Returns: Tensor of depth num_outputs Raises: TypeError: on inval """ with tf.variable_scope(scope, default_name='expanded_conv') as s, \ tf.name_scope(s.original_name_scope): prev_depth = input_tensor.get_shape().as_list()[3] if depthwise_location not in [None, 'input', 'output', 'expansion']: raise TypeError('%r is unknown value for depthwise_location' % depthwise_location) if use_explicit_padding: if padding != 'SAME': raise TypeError('`use_explicit_padding` should only be used with ' '"SAME" padding.') padding = 'VALID' depthwise_func = functools.partial( slim.separable_conv2d, num_outputs=None, kernel_size=kernel_size, depth_multiplier=depthwise_channel_multiplier, stride=stride, rate=rate, normalizer_fn=normalizer_fn, padding=padding, scope='depthwise') # b1 -> b2 * r -> b2 # i -> (o * r) (bottleneck) -> o input_tensor = tf.identity(input_tensor, 'input') net = input_tensor if depthwise_location == 'input': if use_explicit_padding: net = _fixed_padding(net, kernel_size, rate) net = depthwise_func(net, activation_fn=None) if callable(expansion_size): inner_size = expansion_size(num_inputs=prev_depth) else: inner_size = expansion_size if inner_size > net.shape[3]: net = split_conv( net, inner_size, num_ways=split_expansion, scope='expand', stride=1, normalizer_fn=normalizer_fn) net = tf.identity(net, 'expansion_output') if endpoints is not None: endpoints['expansion_output'] = net if depthwise_location == 'expansion': if use_explicit_padding: net = _fixed_padding(net, kernel_size, rate) net = depthwise_func(net) net = tf.identity(net, name='depthwise_output') if endpoints is not None: endpoints['depthwise_output'] = net if expansion_transform: net = expansion_transform(expansion_tensor=net, input_tensor=input_tensor) # Note in contrast with expansion, we always have # projection to produce the desired output size. net = split_conv( net, num_outputs, num_ways=split_projection, stride=1, scope='project', normalizer_fn=normalizer_fn, activation_fn=project_activation_fn) if endpoints is not None: endpoints['projection_output'] = net if depthwise_location == 'output': if use_explicit_padding: net = _fixed_padding(net, kernel_size, rate) net = depthwise_func(net, activation_fn=None) if callable(residual): # custom residual net = residual(input_tensor=input_tensor, output_tensor=net) elif (residual and # stride check enforces that we don't add residuals when spatial # dimensions are None stride == 1 and # Depth matches net.get_shape().as_list()[3] == input_tensor.get_shape().as_list()[3]): net += input_tensor return tf.identity(net, name='output') def split_conv(input_tensor, num_outputs, num_ways, scope, divisible_by=8, **kwargs): """Creates a split convolution. Split convolution splits the input and output into 'num_blocks' blocks of approximately the same size each, and only connects $i$-th input to $i$ output. Args: input_tensor: input tensor num_outputs: number of output filters num_ways: num blocks to split by. scope: scope for all the operators. divisible_by: make sure that every part is divisiable by this. **kwargs: will be passed directly into conv2d operator Returns: tensor """ b = input_tensor.get_shape().as_list()[3] if num_ways == 1 or min(b // num_ways, num_outputs // num_ways) < divisible_by: # Don't do any splitting if we end up with less than 8 filters # on either side. return slim.conv2d(input_tensor, num_outputs, [1, 1], scope=scope, **kwargs) outs = [] input_splits = _split_divisible(b, num_ways, divisible_by=divisible_by) output_splits = _split_divisible( num_outputs, num_ways, divisible_by=divisible_by) inputs = tf.split(input_tensor, input_splits, axis=3, name='split_' + scope) base = scope for i, (input_tensor, out_size) in enumerate(zip(inputs, output_splits)): scope = base + '_part_%d' % (i,) n = slim.conv2d(input_tensor, out_size, [1, 1], scope=scope, **kwargs) n = tf.identity(n, scope + '_output') outs.append(n) return tf.concat(outs, 3, name=scope + '_concat')
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet/conv_blocks.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nets.nasnet.nasnet_utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets.nasnet import nasnet_utils class NasnetUtilsTest(tf.test.TestCase): def testCalcReductionLayers(self): num_cells = 18 num_reduction_layers = 2 reduction_layers = nasnet_utils.calc_reduction_layers( num_cells, num_reduction_layers) self.assertEqual(len(reduction_layers), 2) self.assertEqual(reduction_layers[0], 6) self.assertEqual(reduction_layers[1], 12) def testGetChannelIndex(self): data_formats = ['NHWC', 'NCHW'] for data_format in data_formats: index = nasnet_utils.get_channel_index(data_format) correct_index = 3 if data_format == 'NHWC' else 1 self.assertEqual(index, correct_index) def testGetChannelDim(self): data_formats = ['NHWC', 'NCHW'] shape = [10, 20, 30, 40] for data_format in data_formats: dim = nasnet_utils.get_channel_dim(shape, data_format) correct_dim = shape[3] if data_format == 'NHWC' else shape[1] self.assertEqual(dim, correct_dim) def testGlobalAvgPool(self): data_formats = ['NHWC', 'NCHW'] inputs = tf.placeholder(tf.float32, (5, 10, 20, 10)) for data_format in data_formats: output = nasnet_utils.global_avg_pool( inputs, data_format) self.assertEqual(output.shape, [5, 10]) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/nasnet/nasnet_utils_test.py
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/nasnet/__init__.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition for the PNASNet classification networks. Paper: https://arxiv.org/abs/1712.00559 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import tensorflow as tf from nets.nasnet import nasnet from nets.nasnet import nasnet_utils arg_scope = tf.contrib.framework.arg_scope slim = tf.contrib.slim def large_imagenet_config(): """Large ImageNet configuration based on PNASNet-5.""" return tf.contrib.training.HParams( stem_multiplier=3.0, dense_dropout_keep_prob=0.5, num_cells=12, filter_scaling_rate=2.0, num_conv_filters=216, drop_path_keep_prob=0.6, use_aux_head=1, num_reduction_layers=2, data_format='NHWC', skip_reduction_layer_input=1, total_training_steps=250000, use_bounded_activation=False, ) def mobile_imagenet_config(): """Mobile ImageNet configuration based on PNASNet-5.""" return tf.contrib.training.HParams( stem_multiplier=1.0, dense_dropout_keep_prob=0.5, num_cells=9, filter_scaling_rate=2.0, num_conv_filters=54, drop_path_keep_prob=1.0, use_aux_head=1, num_reduction_layers=2, data_format='NHWC', skip_reduction_layer_input=1, total_training_steps=250000, use_bounded_activation=False, ) def pnasnet_large_arg_scope(weight_decay=4e-5, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Default arg scope for the PNASNet Large ImageNet model.""" return nasnet.nasnet_large_arg_scope( weight_decay, batch_norm_decay, batch_norm_epsilon) def pnasnet_mobile_arg_scope(weight_decay=4e-5, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Default arg scope for the PNASNet Mobile ImageNet model.""" return nasnet.nasnet_mobile_arg_scope(weight_decay, batch_norm_decay, batch_norm_epsilon) def _build_pnasnet_base(images, normal_cell, num_classes, hparams, is_training, final_endpoint=None): """Constructs a PNASNet image model.""" end_points = {} def add_and_check_endpoint(endpoint_name, net): end_points[endpoint_name] = net return final_endpoint and (endpoint_name == final_endpoint) # Find where to place the reduction cells or stride normal cells reduction_indices = nasnet_utils.calc_reduction_layers( hparams.num_cells, hparams.num_reduction_layers) # pylint: disable=protected-access stem = lambda: nasnet._imagenet_stem(images, hparams, normal_cell) # pylint: enable=protected-access net, cell_outputs = stem() if add_and_check_endpoint('Stem', net): return net, end_points # Setup for building in the auxiliary head. aux_head_cell_idxes = [] if len(reduction_indices) >= 2: aux_head_cell_idxes.append(reduction_indices[1] - 1) # Run the cells filter_scaling = 1.0 # true_cell_num accounts for the stem cells true_cell_num = 2 activation_fn = tf.nn.relu6 if hparams.use_bounded_activation else tf.nn.relu for cell_num in range(hparams.num_cells): is_reduction = cell_num in reduction_indices stride = 2 if is_reduction else 1 if is_reduction: filter_scaling *= hparams.filter_scaling_rate if hparams.skip_reduction_layer_input or not is_reduction: prev_layer = cell_outputs[-2] net = normal_cell( net, scope='cell_{}'.format(cell_num), filter_scaling=filter_scaling, stride=stride, prev_layer=prev_layer, cell_num=true_cell_num) if add_and_check_endpoint('Cell_{}'.format(cell_num), net): return net, end_points true_cell_num += 1 cell_outputs.append(net) if (hparams.use_aux_head and cell_num in aux_head_cell_idxes and num_classes and is_training): aux_net = activation_fn(net) # pylint: disable=protected-access nasnet._build_aux_head(aux_net, end_points, num_classes, hparams, scope='aux_{}'.format(cell_num)) # pylint: enable=protected-access # Final softmax layer with tf.variable_scope('final_layer'): net = activation_fn(net) net = nasnet_utils.global_avg_pool(net) if add_and_check_endpoint('global_pool', net) or not num_classes: return net, end_points net = slim.dropout(net, hparams.dense_dropout_keep_prob, scope='dropout') logits = slim.fully_connected(net, num_classes) if add_and_check_endpoint('Logits', logits): return net, end_points predictions = tf.nn.softmax(logits, name='predictions') if add_and_check_endpoint('Predictions', predictions): return net, end_points return logits, end_points def build_pnasnet_large(images, num_classes, is_training=True, final_endpoint=None, config=None): """Build PNASNet Large model for the ImageNet Dataset.""" hparams = copy.deepcopy(config) if config else large_imagenet_config() # pylint: disable=protected-access nasnet._update_hparams(hparams, is_training) # pylint: enable=protected-access if tf.test.is_gpu_available() and hparams.data_format == 'NHWC': tf.logging.info('A GPU is available on the machine, consider using NCHW ' 'data format for increased speed on GPU.') if hparams.data_format == 'NCHW': images = tf.transpose(images, [0, 3, 1, 2]) # Calculate the total number of cells in the network. # There is no distinction between reduction and normal cells in PNAS so the # total number of cells is equal to the number normal cells plus the number # of stem cells (two by default). total_num_cells = hparams.num_cells + 2 normal_cell = PNasNetNormalCell(hparams.num_conv_filters, hparams.drop_path_keep_prob, total_num_cells, hparams.total_training_steps, hparams.use_bounded_activation) with arg_scope( [slim.dropout, nasnet_utils.drop_path, slim.batch_norm], is_training=is_training): with arg_scope([slim.avg_pool2d, slim.max_pool2d, slim.conv2d, slim.batch_norm, slim.separable_conv2d, nasnet_utils.factorized_reduction, nasnet_utils.global_avg_pool, nasnet_utils.get_channel_index, nasnet_utils.get_channel_dim], data_format=hparams.data_format): return _build_pnasnet_base( images, normal_cell=normal_cell, num_classes=num_classes, hparams=hparams, is_training=is_training, final_endpoint=final_endpoint) build_pnasnet_large.default_image_size = 331 def build_pnasnet_mobile(images, num_classes, is_training=True, final_endpoint=None, config=None): """Build PNASNet Mobile model for the ImageNet Dataset.""" hparams = copy.deepcopy(config) if config else mobile_imagenet_config() # pylint: disable=protected-access nasnet._update_hparams(hparams, is_training) # pylint: enable=protected-access if tf.test.is_gpu_available() and hparams.data_format == 'NHWC': tf.logging.info('A GPU is available on the machine, consider using NCHW ' 'data format for increased speed on GPU.') if hparams.data_format == 'NCHW': images = tf.transpose(images, [0, 3, 1, 2]) # Calculate the total number of cells in the network. # There is no distinction between reduction and normal cells in PNAS so the # total number of cells is equal to the number normal cells plus the number # of stem cells (two by default). total_num_cells = hparams.num_cells + 2 normal_cell = PNasNetNormalCell(hparams.num_conv_filters, hparams.drop_path_keep_prob, total_num_cells, hparams.total_training_steps, hparams.use_bounded_activation) with arg_scope( [slim.dropout, nasnet_utils.drop_path, slim.batch_norm], is_training=is_training): with arg_scope( [ slim.avg_pool2d, slim.max_pool2d, slim.conv2d, slim.batch_norm, slim.separable_conv2d, nasnet_utils.factorized_reduction, nasnet_utils.global_avg_pool, nasnet_utils.get_channel_index, nasnet_utils.get_channel_dim ], data_format=hparams.data_format): return _build_pnasnet_base( images, normal_cell=normal_cell, num_classes=num_classes, hparams=hparams, is_training=is_training, final_endpoint=final_endpoint) build_pnasnet_mobile.default_image_size = 224 class PNasNetNormalCell(nasnet_utils.NasNetABaseCell): """PNASNet Normal Cell.""" def __init__(self, num_conv_filters, drop_path_keep_prob, total_num_cells, total_training_steps, use_bounded_activation=False): # Configuration for the PNASNet-5 model. operations = [ 'separable_5x5_2', 'max_pool_3x3', 'separable_7x7_2', 'max_pool_3x3', 'separable_5x5_2', 'separable_3x3_2', 'separable_3x3_2', 'max_pool_3x3', 'separable_3x3_2', 'none' ] used_hiddenstates = [1, 1, 0, 0, 0, 0, 0] hiddenstate_indices = [1, 1, 0, 0, 0, 0, 4, 0, 1, 0] super(PNasNetNormalCell, self).__init__( num_conv_filters, operations, used_hiddenstates, hiddenstate_indices, drop_path_keep_prob, total_num_cells, total_training_steps, use_bounded_activation)
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/nasnet/pnasnet.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.nasnet.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets.nasnet import nasnet slim = tf.contrib.slim class NASNetTest(tf.test.TestCase): def testBuildLogitsCifarModel(self): batch_size = 5 height, width = 32, 32 num_classes = 10 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()): logits, end_points = nasnet.build_nasnet_cifar(inputs, num_classes) auxlogits = end_points['AuxLogits'] predictions = end_points['Predictions'] self.assertListEqual(auxlogits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(predictions.get_shape().as_list(), [batch_size, num_classes]) def testBuildLogitsMobileModel(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): logits, end_points = nasnet.build_nasnet_mobile(inputs, num_classes) auxlogits = end_points['AuxLogits'] predictions = end_points['Predictions'] self.assertListEqual(auxlogits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(predictions.get_shape().as_list(), [batch_size, num_classes]) def testBuildLogitsLargeModel(self): batch_size = 5 height, width = 331, 331 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_large_arg_scope()): logits, end_points = nasnet.build_nasnet_large(inputs, num_classes) auxlogits = end_points['AuxLogits'] predictions = end_points['Predictions'] self.assertListEqual(auxlogits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(predictions.get_shape().as_list(), [batch_size, num_classes]) def testBuildPreLogitsCifarModel(self): batch_size = 5 height, width = 32, 32 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()): net, end_points = nasnet.build_nasnet_cifar(inputs, num_classes) self.assertFalse('AuxLogits' in end_points) self.assertFalse('Predictions' in end_points) self.assertTrue(net.op.name.startswith('final_layer/Mean')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 768]) def testBuildPreLogitsMobileModel(self): batch_size = 5 height, width = 224, 224 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): net, end_points = nasnet.build_nasnet_mobile(inputs, num_classes) self.assertFalse('AuxLogits' in end_points) self.assertFalse('Predictions' in end_points) self.assertTrue(net.op.name.startswith('final_layer/Mean')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1056]) def testBuildPreLogitsLargeModel(self): batch_size = 5 height, width = 331, 331 num_classes = None inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_large_arg_scope()): net, end_points = nasnet.build_nasnet_large(inputs, num_classes) self.assertFalse('AuxLogits' in end_points) self.assertFalse('Predictions' in end_points) self.assertTrue(net.op.name.startswith('final_layer/Mean')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 4032]) def testAllEndPointsShapesCifarModel(self): batch_size = 5 height, width = 32, 32 num_classes = 10 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()): _, end_points = nasnet.build_nasnet_cifar(inputs, num_classes) endpoints_shapes = {'Stem': [batch_size, 32, 32, 96], 'Cell_0': [batch_size, 32, 32, 192], 'Cell_1': [batch_size, 32, 32, 192], 'Cell_2': [batch_size, 32, 32, 192], 'Cell_3': [batch_size, 32, 32, 192], 'Cell_4': [batch_size, 32, 32, 192], 'Cell_5': [batch_size, 32, 32, 192], 'Cell_6': [batch_size, 16, 16, 384], 'Cell_7': [batch_size, 16, 16, 384], 'Cell_8': [batch_size, 16, 16, 384], 'Cell_9': [batch_size, 16, 16, 384], 'Cell_10': [batch_size, 16, 16, 384], 'Cell_11': [batch_size, 16, 16, 384], 'Cell_12': [batch_size, 8, 8, 768], 'Cell_13': [batch_size, 8, 8, 768], 'Cell_14': [batch_size, 8, 8, 768], 'Cell_15': [batch_size, 8, 8, 768], 'Cell_16': [batch_size, 8, 8, 768], 'Cell_17': [batch_size, 8, 8, 768], 'Reduction_Cell_0': [batch_size, 16, 16, 256], 'Reduction_Cell_1': [batch_size, 8, 8, 512], 'global_pool': [batch_size, 768], # Logits and predictions 'AuxLogits': [batch_size, num_classes], 'Logits': [batch_size, num_classes], 'Predictions': [batch_size, num_classes]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: tf.logging.info('Endpoint name: {}'.format(endpoint_name)) expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testNoAuxHeadCifarModel(self): batch_size = 5 height, width = 32, 32 num_classes = 10 for use_aux_head in (True, False): tf.reset_default_graph() inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() config = nasnet.cifar_config() config.set_hparam('use_aux_head', int(use_aux_head)) with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()): _, end_points = nasnet.build_nasnet_cifar(inputs, num_classes, config=config) self.assertEqual('AuxLogits' in end_points, use_aux_head) def testAllEndPointsShapesMobileModel(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): _, end_points = nasnet.build_nasnet_mobile(inputs, num_classes) endpoints_shapes = {'Stem': [batch_size, 28, 28, 88], 'Cell_0': [batch_size, 28, 28, 264], 'Cell_1': [batch_size, 28, 28, 264], 'Cell_2': [batch_size, 28, 28, 264], 'Cell_3': [batch_size, 28, 28, 264], 'Cell_4': [batch_size, 14, 14, 528], 'Cell_5': [batch_size, 14, 14, 528], 'Cell_6': [batch_size, 14, 14, 528], 'Cell_7': [batch_size, 14, 14, 528], 'Cell_8': [batch_size, 7, 7, 1056], 'Cell_9': [batch_size, 7, 7, 1056], 'Cell_10': [batch_size, 7, 7, 1056], 'Cell_11': [batch_size, 7, 7, 1056], 'Reduction_Cell_0': [batch_size, 14, 14, 352], 'Reduction_Cell_1': [batch_size, 7, 7, 704], 'global_pool': [batch_size, 1056], # Logits and predictions 'AuxLogits': [batch_size, num_classes], 'Logits': [batch_size, num_classes], 'Predictions': [batch_size, num_classes]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: tf.logging.info('Endpoint name: {}'.format(endpoint_name)) expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testNoAuxHeadMobileModel(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 for use_aux_head in (True, False): tf.reset_default_graph() inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() config = nasnet.mobile_imagenet_config() config.set_hparam('use_aux_head', int(use_aux_head)) with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): _, end_points = nasnet.build_nasnet_mobile(inputs, num_classes, config=config) self.assertEqual('AuxLogits' in end_points, use_aux_head) def testAllEndPointsShapesLargeModel(self): batch_size = 5 height, width = 331, 331 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_large_arg_scope()): _, end_points = nasnet.build_nasnet_large(inputs, num_classes) endpoints_shapes = {'Stem': [batch_size, 42, 42, 336], 'Cell_0': [batch_size, 42, 42, 1008], 'Cell_1': [batch_size, 42, 42, 1008], 'Cell_2': [batch_size, 42, 42, 1008], 'Cell_3': [batch_size, 42, 42, 1008], 'Cell_4': [batch_size, 42, 42, 1008], 'Cell_5': [batch_size, 42, 42, 1008], 'Cell_6': [batch_size, 21, 21, 2016], 'Cell_7': [batch_size, 21, 21, 2016], 'Cell_8': [batch_size, 21, 21, 2016], 'Cell_9': [batch_size, 21, 21, 2016], 'Cell_10': [batch_size, 21, 21, 2016], 'Cell_11': [batch_size, 21, 21, 2016], 'Cell_12': [batch_size, 11, 11, 4032], 'Cell_13': [batch_size, 11, 11, 4032], 'Cell_14': [batch_size, 11, 11, 4032], 'Cell_15': [batch_size, 11, 11, 4032], 'Cell_16': [batch_size, 11, 11, 4032], 'Cell_17': [batch_size, 11, 11, 4032], 'Reduction_Cell_0': [batch_size, 21, 21, 1344], 'Reduction_Cell_1': [batch_size, 11, 11, 2688], 'global_pool': [batch_size, 4032], # Logits and predictions 'AuxLogits': [batch_size, num_classes], 'Logits': [batch_size, num_classes], 'Predictions': [batch_size, num_classes]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name in endpoints_shapes: tf.logging.info('Endpoint name: {}'.format(endpoint_name)) expected_shape = endpoints_shapes[endpoint_name] self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) def testNoAuxHeadLargeModel(self): batch_size = 5 height, width = 331, 331 num_classes = 1000 for use_aux_head in (True, False): tf.reset_default_graph() inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() config = nasnet.large_imagenet_config() config.set_hparam('use_aux_head', int(use_aux_head)) with slim.arg_scope(nasnet.nasnet_large_arg_scope()): _, end_points = nasnet.build_nasnet_large(inputs, num_classes, config=config) self.assertEqual('AuxLogits' in end_points, use_aux_head) def testVariablesSetDeviceMobileModel(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() # Force all Variables to reside on the device. with tf.variable_scope('on_cpu'), tf.device('/cpu:0'): with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): nasnet.build_nasnet_mobile(inputs, num_classes) with tf.variable_scope('on_gpu'), tf.device('/gpu:0'): with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): nasnet.build_nasnet_mobile(inputs, num_classes) for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='on_cpu'): self.assertDeviceEqual(v.device, '/cpu:0') for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='on_gpu'): self.assertDeviceEqual(v.device, '/gpu:0') def testUnknownBatchSizeMobileModel(self): batch_size = 1 height, width = 224, 224 num_classes = 1000 with self.test_session() as sess: inputs = tf.placeholder(tf.float32, (None, height, width, 3)) with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): logits, _ = nasnet.build_nasnet_mobile(inputs, num_classes) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = tf.random_uniform((batch_size, height, width, 3)) sess.run(tf.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEquals(output.shape, (batch_size, num_classes)) def testEvaluationMobileModel(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 with self.test_session() as sess: eval_inputs = tf.random_uniform((batch_size, height, width, 3)) with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): logits, _ = nasnet.build_nasnet_mobile(eval_inputs, num_classes, is_training=False) predictions = tf.argmax(logits, 1) sess.run(tf.global_variables_initializer()) output = sess.run(predictions) self.assertEquals(output.shape, (batch_size,)) def testOverrideHParamsCifarModel(self): batch_size = 5 height, width = 32, 32 num_classes = 10 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() config = nasnet.cifar_config() config.set_hparam('data_format', 'NCHW') with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()): _, end_points = nasnet.build_nasnet_cifar( inputs, num_classes, config=config) self.assertListEqual( end_points['Stem'].shape.as_list(), [batch_size, 96, 32, 32]) def testOverrideHParamsMobileModel(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() config = nasnet.mobile_imagenet_config() config.set_hparam('data_format', 'NCHW') with slim.arg_scope(nasnet.nasnet_mobile_arg_scope()): _, end_points = nasnet.build_nasnet_mobile( inputs, num_classes, config=config) self.assertListEqual( end_points['Stem'].shape.as_list(), [batch_size, 88, 28, 28]) def testOverrideHParamsLargeModel(self): batch_size = 5 height, width = 331, 331 num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() config = nasnet.large_imagenet_config() config.set_hparam('data_format', 'NCHW') with slim.arg_scope(nasnet.nasnet_large_arg_scope()): _, end_points = nasnet.build_nasnet_large( inputs, num_classes, config=config) self.assertListEqual( end_points['Stem'].shape.as_list(), [batch_size, 336, 42, 42]) def testCurrentStepCifarModel(self): batch_size = 5 height, width = 32, 32 num_classes = 10 inputs = tf.random_uniform((batch_size, height, width, 3)) global_step = tf.train.create_global_step() with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()): logits, end_points = nasnet.build_nasnet_cifar(inputs, num_classes, current_step=global_step) auxlogits = end_points['AuxLogits'] predictions = end_points['Predictions'] self.assertListEqual(auxlogits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertListEqual(predictions.get_shape().as_list(), [batch_size, num_classes]) def testUseBoundedAcitvationCifarModel(self): batch_size = 1 height, width = 32, 32 num_classes = 10 for use_bounded_activation in (True, False): tf.reset_default_graph() inputs = tf.random_uniform((batch_size, height, width, 3)) config = nasnet.cifar_config() config.set_hparam('use_bounded_activation', use_bounded_activation) with slim.arg_scope(nasnet.nasnet_cifar_arg_scope()): _, _ = nasnet.build_nasnet_cifar( inputs, num_classes, config=config) for node in tf.get_default_graph().as_graph_def().node: if node.op.startswith('Relu'): self.assertEqual(node.op == 'Relu6', use_bounded_activation) if __name__ == '__main__': tf.test.main()
DeepLearningExamples-master
TensorFlow/Detection/SSD/models/research/slim/nets/nasnet/nasnet_test.py