code
stringlengths
17
6.64M
class Cifar10(CifarBase): def __init__(self, train_or_test, shuffle=True, dir=None): super(Cifar10, self).__init__(train_or_test, shuffle, dir, 10)
class Cifar100(CifarBase): def __init__(self, train_or_test, shuffle=True, dir=None): super(Cifar100, self).__init__(train_or_test, shuffle, dir, 100)
class ILSVRCMeta(object): '\n Some metadata for ILSVRC dataset.\n ' def __init__(self, dir=None): if (dir is None): dir = get_dataset_path('ilsvrc_metadata') self.dir = dir mkdir_p(self.dir) self.caffepb = get_caffe_pb() f = os.path.join(self.dir, 'synsets.txt') if (not os.path.isfile(f)): self._download_caffe_meta() def get_synset_words_1000(self): '\n :returns a dict of {cls_number: cls_name}\n ' fname = os.path.join(self.dir, 'synset_words.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines)) def get_synset_1000(self): '\n :returns a dict of {cls_number: synset_id}\n ' fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines)) def _download_caffe_meta(self): fpath = download(CAFFE_ILSVRC12_URL, self.dir) tarfile.open(fpath, 'r:gz').extractall(self.dir) def get_image_list(self, name): "\n :param name: 'train' or 'val' or 'test'\n :returns: list of (image filename, cls)\n " assert (name in ['train', 'val', 'test']) fname = os.path.join(self.dir, (name + '.txt')) assert os.path.isfile(fname) with open(fname) as f: ret = [] for line in f.readlines(): (name, cls) = line.strip().split() ret.append((name, int(cls))) assert len(ret) return ret def get_per_pixel_mean(self, size=None): '\n :param size: return image size in [h, w]. default to (256, 256)\n :returns: per-pixel mean as an array of shape (h, w, 3) in range [0, 255]\n ' obj = self.caffepb.BlobProto() mean_file = os.path.join(self.dir, 'imagenet_mean.binaryproto') with open(mean_file, 'rb') as f: obj.ParseFromString(f.read()) arr = np.array(obj.data).reshape((3, 256, 256)).astype('float32') arr = np.transpose(arr, [1, 2, 0]) if (size is not None): arr = cv2.resize(arr, size[::(- 1)]) return arr
class ILSVRC12(RNGDataFlow): def __init__(self, dir, name, meta_dir=None, shuffle=True, dir_structure='original', include_bb=False): "\n :param dir: A directory containing a subdir named `name`, where the\n original ILSVRC12_`name`.tar gets decompressed.\n :param name: 'train' or 'val' or 'test'\n :param dir_structure: The dir structure of 'val' and 'test'.\n If is 'original' then keep the original decompressed directory with list\n of image files (as below). If set to 'train', use the the same\n directory structure as 'train/', with class name as subdirectories.\n :param include_bb: Include the bounding box. Maybe useful in training.\n\n When `dir_structure=='original'`, `dir` should have the following structure:\n\n .. code-block:: none\n\n dir/\n train/\n n02134418/\n n02134418_198.JPEG\n ...\n ...\n val/\n ILSVRC2012_val_00000001.JPEG\n ...\n test/\n ILSVRC2012_test_00000001.JPEG\n ...\n bbox/\n n02134418/\n n02134418_198.xml\n ...\n ...\n\n After decompress ILSVRC12_img_train.tar, you can use the following\n command to build the above structure for `train/`:\n\n .. code-block:: none\n\n tar xvf ILSVRC12_img_train.tar -C train && cd train\n find -type f -name '*.tar' | parallel -P 10 'echo {} && mkdir -p {/.} && tar xf {} -C {/.}'\n Or:\n for i in *.tar; do dir=${i%.tar}; echo $dir; mkdir -p $dir; tar xf $i -C $dir; done\n\n " assert (name in ['train', 'test', 'val']) self.full_dir = os.path.join(dir, name) self.name = name assert os.path.isdir(self.full_dir), self.full_dir self.shuffle = shuffle meta = ILSVRCMeta(meta_dir) self.imglist = meta.get_image_list(name) self.dir_structure = dir_structure self.synset = meta.get_synset_1000() if include_bb: bbdir = (os.path.join(dir, 'bbox') if (not isinstance(include_bb, six.string_types)) else include_bb) assert (name == 'train'), 'Bounding box only available for training' self.bblist = ILSVRC12.get_training_bbox(bbdir, self.imglist) self.include_bb = include_bb def size(self): return len(self.imglist) def get_data(self): '\n Produce original images of shape [h, w, 3(BGR)], and label,\n and optionally a bbox of [xmin, ymin, xmax, ymax]\n ' idxs = np.arange(len(self.imglist)) add_label_to_fname = ((self.name != 'train') and (self.dir_structure != 'original')) if self.shuffle: self.rng.shuffle(idxs) for k in idxs: (fname, label) = self.imglist[k] if add_label_to_fname: fname = os.path.join(self.full_dir, self.synset[label], fname) else: fname = os.path.join(self.full_dir, fname) im = cv2.imread(fname.strip(), cv2.IMREAD_COLOR) assert (im is not None), fname if (im.ndim == 2): im = np.expand_dims(im, 2).repeat(3, 2) if self.include_bb: bb = self.bblist[k] if (bb is None): bb = [0, 0, (im.shape[1] - 1), (im.shape[0] - 1)] (yield [im, label, bb]) else: (yield [im, label]) @staticmethod def get_training_bbox(bbox_dir, imglist): ret = [] def parse_bbox(fname): root = ET.parse(fname).getroot() size = root.find('size').getchildren() size = map(int, [size[0].text, size[1].text]) box = root.find('object').find('bndbox').getchildren() box = map((lambda x: float(x.text)), box) return np.asarray(box, dtype='float32') with timed_operation('Loading Bounding Boxes ...'): cnt = 0 import tqdm for k in tqdm.trange(len(imglist)): fname = imglist[k][0] fname = (fname[:(- 4)] + 'xml') fname = os.path.join(bbox_dir, fname) try: ret.append(parse_bbox(fname)) cnt += 1 except KeyboardInterrupt: raise except: ret.append(None) logger.info('{}/{} images have bounding box.'.format(cnt, len(imglist))) return ret
def maybe_download(filename, work_directory): "Download the data from Yann's website, unless it's already here." filepath = os.path.join(work_directory, filename) if (not os.path.exists(filepath)): logger.info('Downloading mnist data to {}...'.format(filepath)) download((SOURCE_URL + filename), work_directory) return filepath
def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder('>') return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(filename): 'Extract the images into a 4D uint8 numpy array [index, y, x, depth].' with gzip.open(filename) as bytestream: magic = _read32(bytestream) if (magic != 2051): raise ValueError(('Invalid magic number %d in MNIST image file: %s' % (magic, filename))) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(((rows * cols) * num_images)) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) data = (data.astype('float32') / 255.0) return data
def extract_labels(filename): 'Extract the labels into a 1D uint8 numpy array [index].' with gzip.open(filename) as bytestream: magic = _read32(bytestream) if (magic != 2049): raise ValueError(('Invalid magic number %d in MNIST label file: %s' % (magic, filename))) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) return labels
class Mnist(RNGDataFlow): '\n Return [image, label],\n image is 28x28 in the range [0,1]\n ' def __init__(self, train_or_test, shuffle=True, dir=None): "\n Args:\n train_or_test: string either 'train' or 'test'\n " if (dir is None): dir = get_dataset_path('mnist_data') assert (train_or_test in ['train', 'test']) self.train_or_test = train_or_test self.shuffle = shuffle def get_images_and_labels(image_file, label_file): f = maybe_download(image_file, dir) images = extract_images(f) f = maybe_download(label_file, dir) labels = extract_labels(f) assert (images.shape[0] == labels.shape[0]) return (images, labels) if (self.train_or_test == 'train'): (self.images, self.labels) = get_images_and_labels('train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyte.gz') else: (self.images, self.labels) = get_images_and_labels('t10k-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz') def size(self): return self.images.shape[0] def get_data(self): idxs = list(range(self.size())) if self.shuffle: self.rng.shuffle(idxs) for k in idxs: img = self.images[k].reshape((28, 28)) label = self.labels[k] (yield [img, label])
@memoized_ignoreargs def get_PennTreeBank(data_dir=None): if (data_dir is None): data_dir = get_dataset_path('ptb_data') if (not os.path.isfile(os.path.join(data_dir, 'ptb.train.txt'))): download(TRAIN_URL, data_dir) download(VALID_URL, data_dir) download(TEST_URL, data_dir) word_to_id = tfreader._build_vocab(os.path.join(data_dir, 'ptb.train.txt')) data3 = [np.asarray(tfreader._file_to_word_ids(os.path.join(data_dir, fname), word_to_id)) for fname in ['ptb.train.txt', 'ptb.valid.txt', 'ptb.test.txt']] return (data3, word_to_id)
class SVHNDigit(RNGDataFlow): '\n SVHN Cropped Digit Dataset.\n return img of 32x32x3, label of 0-9\n ' _Cache = {} def __init__(self, name, data_dir=None, shuffle=True): "\n :param name: 'train', 'test', or 'extra'\n :param data_dir: a directory containing the original {train,test,extra}_32x32.mat\n " self.shuffle = shuffle if (name in SVHNDigit._Cache): (self.X, self.Y) = SVHNDigit._Cache[name] return if (data_dir is None): data_dir = get_dataset_path('svhn_data') assert (name in ['train', 'test', 'extra']), name filename = os.path.join(data_dir, (name + '_32x32.mat')) assert os.path.isfile(filename), 'File {} not found! Please download it from {}.'.format(filename, SVHN_URL) logger.info('Loading {} ...'.format(filename)) data = scipy.io.loadmat(filename) self.X = data['X'].transpose(3, 0, 1, 2) self.Y = data['y'].reshape((- 1)) self.Y[(self.Y == 10)] = 0 SVHNDigit._Cache[name] = (self.X, self.Y) def size(self): return self.X.shape[0] def get_data(self): n = self.X.shape[0] idxs = np.arange(n) if self.shuffle: self.rng.shuffle(idxs) for k in idxs: (yield [self.X[k], self.Y[k]]) @staticmethod def get_per_pixel_mean(): '\n return 32x32x3 image\n ' a = SVHNDigit('train') b = SVHNDigit('test') c = SVHNDigit('extra') return np.concatenate((a.X, b.X, c.X)).mean(axis=0)
def read_json(fname): f = open(fname) ret = json.load(f) f.close() return ret
class VisualQA(DataFlow): '\n Visual QA dataset. See http://visualqa.org/\n Simply read q/a json file and produce q/a pairs in their original format.\n ' def __init__(self, question_file, annotation_file): with timed_operation('Reading VQA JSON file'): (qobj, aobj) = list(map(read_json, [question_file, annotation_file])) self.task_type = qobj['task_type'] self.questions = qobj['questions'] self._size = len(self.questions) self.anno = aobj['annotations'] assert (len(self.anno) == len(self.questions)), '{}!={}'.format(len(self.anno), len(self.questions)) self._clean() def _clean(self): for a in self.anno: for aa in a['answers']: del aa['answer_id'] def size(self): return self._size def get_data(self): for (q, a) in zip(self.questions, self.anno): assert (q['question_id'] == a['question_id']) (yield [q, a]) def get_common_answer(self, n): ' Get the n most common answers (could be phrases)\n n=3000 ~= thresh 4\n ' cnt = Counter() for anno in self.anno: cnt[anno['multiple_choice_answer'].lower()] += 1 return [k[0] for k in cnt.most_common(n)] def get_common_question_words(self, n): ' Get the n most common words in questions\n n=4600 ~= thresh 6\n ' from nltk.tokenize import word_tokenize cnt = Counter() for q in self.questions: cnt.update(word_tokenize(q['question'].lower())) del cnt['?'] ret = cnt.most_common(n) return [k[0] for k in ret]
def dump_dataset_images(ds, dirname, max_count=None, index=0): ' Dump images from a `DataFlow` to a directory.\n\n :param ds: a `DataFlow` instance.\n :param dirname: name of the directory.\n :param max_count: max number of images to dump\n :param index: the index of the image component in a data point.\n ' mkdir_p(dirname) if (max_count is None): max_count = sys.maxint ds.reset_state() for (i, dp) in enumerate(ds.get_data()): if ((i % 100) == 0): print(i) if (i > max_count): return img = dp[index] cv2.imwrite(os.path.join(dirname, '{}.jpg'.format(i)), img)
def dump_dataflow_to_lmdb(ds, lmdb_path): ' Dump a `Dataflow` ds to a lmdb database, where the key is the index\n and the data is the serialized datapoint.\n The output database can be read directly by `LMDBDataPoint`\n ' assert isinstance(ds, DataFlow), type(ds) isdir = os.path.isdir(lmdb_path) if isdir: assert (not os.path.isfile(os.path.join(lmdb_path, 'data.mdb'))), 'LMDB file exists!' else: assert (not os.path.isfile(lmdb_path)), 'LMDB file exists!' ds.reset_state() db = lmdb.open(lmdb_path, subdir=isdir, map_size=(1099511627776 * 2), readonly=False, meminit=False, map_async=True) try: sz = ds.size() except NotImplementedError: sz = 0 with get_tqdm(total=sz) as pbar: with db.begin(write=True) as txn: for (idx, dp) in enumerate(ds.get_data()): txn.put(six.binary_type(idx), dumps(dp)) pbar.update() keys = list(map(six.binary_type, range((idx + 1)))) txn.put('__keys__', dumps(keys)) logger.info('Flushing database ...') db.sync()
def dataflow_to_process_queue(ds, size, nr_consumer): '\n Convert a `DataFlow` to a multiprocessing.Queue.\n The dataflow will only be reset in the spawned process.\n\n :param ds: a `DataFlow`\n :param size: size of the queue\n :param nr_consumer: number of consumer of the queue.\n will add this many of `DIE` sentinel to the end of the queue.\n :returns: (queue, process). The process will take data from `ds` to fill\n the queue once you start it. Each element is (task_id, dp).\n ' q = mp.Queue(size) class EnqueProc(mp.Process): def __init__(self, ds, q, nr_consumer): super(EnqueProc, self).__init__() self.ds = ds self.q = q def run(self): self.ds.reset_state() try: for (idx, dp) in enumerate(self.ds.get_data()): self.q.put((idx, dp)) finally: for _ in range(nr_consumer): self.q.put((DIE, None)) proc = EnqueProc(ds, q, nr_consumer) return (q, proc)
class ImageFromFile(RNGDataFlow): def __init__(self, files, channel=3, resize=None, shuffle=False): '\n Generate RGB images from list of files\n :param files: list of file paths\n :param channel: 1 or 3 channel\n :param resize: a (h, w) tuple. If given, will force a resize\n ' assert len(files), 'No Image Files!' self.files = files self.channel = int(channel) self.imread_mode = (cv2.IMREAD_GRAYSCALE if (self.channel == 1) else cv2.IMREAD_COLOR) self.resize = resize self.shuffle = shuffle def size(self): return len(self.files) def get_data(self): if self.shuffle: self.rng.shuffle(self.files) for f in self.files: im = cv2.imread(f, self.imread_mode) if (self.channel == 3): im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) if (self.resize is not None): im = cv2.resize(im, self.resize[::(- 1)]) (yield [im])
class AugmentImageComponent(MapDataComponent): def __init__(self, ds, augmentors, index=0): '\n Augment the image component of datapoints\n :param ds: a `DataFlow` instance.\n :param augmentors: a list of `ImageAugmentor` instance to be applied in order.\n :param index: the index (or list of indices) of the image component in the produced datapoints by `ds`. default to be 0\n ' if isinstance(augmentors, AugmentorList): self.augs = augmentors else: self.augs = AugmentorList(augmentors) super(AugmentImageComponent, self).__init__(ds, (lambda x: self.augs.augment(x)), index) def reset_state(self): self.ds.reset_state() self.augs.reset_state()
class AugmentImageComponents(MapData): def __init__(self, ds, augmentors, index=(0, 1)): ' Augment a list of images of the same shape, with the same parameters\n :param ds: a `DataFlow` instance.\n :param augmentors: a list of `ImageAugmentor` instance to be applied in order.\n :param index: tuple of indices of the image components\n ' self.augs = AugmentorList(augmentors) self.ds = ds def func(dp): im = dp[index[0]] (im, prms) = self.augs._augment_return_params(im) dp[index[0]] = im for idx in index[1:]: dp[idx] = self.augs._augment(dp[idx], prms) return dp super(AugmentImageComponents, self).__init__(ds, func) def reset_state(self): self.ds.reset_state() self.augs.reset_state()
def global_import(name): p = __import__(name, globals(), locals(), level=1) lst = (p.__all__ if ('__all__' in dir(p)) else dir(p)) del globals()[name] for k in lst: globals()[k] = p.__dict__[k]
@six.add_metaclass(ABCMeta) class Augmentor(object): ' Base class for an augmentor' def __init__(self): self.reset_state() def _init(self, params=None): if params: for (k, v) in params.items(): if (k != 'self'): setattr(self, k, v) def reset_state(self): self.rng = get_rng(self) def augment(self, d): '\n Perform augmentation on the data.\n ' (d, params) = self._augment_return_params(d) return d def _augment_return_params(self, d): '\n Augment the image and return both image and params\n ' prms = self._get_augment_params(d) return (self._augment(d, prms), prms) @abstractmethod def _augment(self, d, param): '\n augment with the given param and return the new image\n ' def _get_augment_params(self, d): '\n get the augmentor parameters\n ' return None def _rand_range(self, low=1.0, high=None, size=None): if (high is None): (low, high) = (0, low) if (size == None): size = [] return self.rng.uniform(low, high, size)
class ImageAugmentor(Augmentor): def augment(self, img): "\n Perform augmentation on the image in-place.\n :param img: an [h,w] or [h,w,c] image\n :returns: the augmented image, always of type 'float32'\n " (img, params) = self._augment_return_params(img) return img def _fprop_coord(self, coord, param): return coord
class AugmentorList(ImageAugmentor): '\n Augment by a list of augmentors\n ' def __init__(self, augmentors): '\n :param augmentors: list of `ImageAugmentor` instance to be applied\n ' self.augs = augmentors super(AugmentorList, self).__init__() def _get_augment_params(self, img): raise RuntimeError('Cannot simply get parameters of a AugmentorList!') def _augment_return_params(self, img): assert (img.ndim in [2, 3]), img.ndim img = img.astype('float32') prms = [] for a in self.augs: (img, prm) = a._augment_return_params(img) prms.append(prm) return (img, prms) def _augment(self, img, param): assert (img.ndim in [2, 3]), img.ndim img = img.astype('float32') for (aug, prm) in zip(self.augs, param): img = aug._augment(img, prm) return img def reset_state(self): ' Will reset state of each augmentor ' for a in self.augs: a.reset_state()
class Identity(ImageAugmentor): def _augment(self, img, _): return img
class RandomApplyAug(ImageAugmentor): ' Randomly apply the augmentor with a prob. Otherwise do nothing' def __init__(self, aug, prob): self._init(locals()) super(RandomApplyAug, self).__init__() def _get_augment_params(self, img): p = self.rng.rand() if (p < self.prob): prm = self.aug._get_augment_params(img) return (True, prm) else: return (False, None) def reset_state(self): super(RandomApplyAug, self).reset_state() self.aug.reset_state() def _augment(self, img, prm): if (not prm[0]): return img else: return self.aug._augment(img, prm[1])
class RandomChooseAug(ImageAugmentor): def __init__(self, aug_lists): '\n :param aug_lists: list of augmentor, or list of (augmentor, probability) tuple\n ' if isinstance(aug_lists[0], (tuple, list)): prob = [k[1] for k in aug_lists] aug_lists = [k[0] for k in aug_lists] self._init(locals()) else: prob = (1.0 / len(aug_lists)) self._init(locals()) super(RandomChooseAug, self).__init__() def reset_state(self): super(RandomChooseAug, self).reset_state() for a in self.aug_lists: a.reset_state() def _get_augment_params(self, img): aug_idx = self.rng.choice(len(self.aug_lists), p=self.prob) aug_prm = self.aug_lists[aug_idx]._get_augment_params(img) return (aug_idx, aug_prm) def _augment(self, img, prm): (idx, prm) = prm return self.aug_lists[idx]._augment(img, prm)
class RandomOrderAug(ImageAugmentor): def __init__(self, aug_lists): '\n Shuffle the augmentors into random order.\n :param aug_lists: list of augmentor, or list of (augmentor, probability) tuple\n ' self._init(locals()) super(RandomOrderAug, self).__init__() def reset_state(self): super(RandomOrderAug, self).reset_state() for a in self.aug_lists: a.reset_state() def _get_augment_params(self, img): idxs = self.rng.permutation(len(self.aug_lists)) prms = [self.aug_lists[k]._get_augment_params(img) for k in range(len(self.aug_lists))] return (idxs, prms) def _augment(self, img, prm): (idxs, prms) = prm for k in idxs: img = self.aug_lists[k]._augment(img, prms[k]) return img
class MapImage(ImageAugmentor): '\n Map the image array by a function.\n ' def __init__(self, func): '\n :param func: a function which takes a image array and return a augmented one\n ' self.func = func def _augment(self, img, _): return self.func(img)
class JpegNoise(ImageAugmentor): def __init__(self, quality_range=(40, 100)): super(JpegNoise, self).__init__() self._init(locals()) def _get_augment_params(self, img): return self.rng.randint(*self.quality_range) def _augment(self, img, q): enc = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, q])[1] return cv2.imdecode(enc, 1)
class GaussianNoise(ImageAugmentor): def __init__(self, sigma=1, clip=True): '\n Add a gaussian noise N(0, sigma^2) of the same shape to img.\n ' super(GaussianNoise, self).__init__() self._init(locals()) def _get_augment_params(self, img): return self.rng.randn(*img.shape) def _augment(self, img, noise): ret = (img + (noise * self.sigma)) if self.clip: ret = np.clip(ret, 0, 255) return ret
class SaltPepperNoise(ImageAugmentor): def __init__(self, white_prob=0.05, black_prob=0.05): ' Salt and pepper noise.\n Randomly set some elements in img to 0 or 255, regardless of its channels.\n ' assert ((white_prob + black_prob) <= 1), 'Sum of probabilities cannot be greater than 1' super(SaltPepperNoise, self).__init__() self._init(locals()) def _get_augment_params(self, img): return self.rng.uniform(low=0, high=1, size=img.shape) def _augment(self, img, param): img[(param > (1 - self.white_prob))] = 255 img[(param < self.black_prob)] = 0 return img
class Flip(ImageAugmentor): '\n Random flip.\n ' def __init__(self, horiz=False, vert=False, prob=0.5): '\n Only one of horiz, vert can be set.\n\n :param horiz: whether or not apply horizontal flip.\n :param vert: whether or not apply vertical flip.\n :param prob: probability of flip.\n ' super(Flip, self).__init__() if (horiz and vert): raise ValueError('Please use two Flip instead.') elif horiz: self.code = 1 elif vert: self.code = 0 else: raise ValueError('Are you kidding?') self.prob = prob self._init() def _get_augment_params(self, img): return (self._rand_range() < self.prob) def _augment(self, img, do): if do: img = cv2.flip(img, self.code) return img def _fprop_coord(self, coord, param): raise NotImplementedError()
class Resize(ImageAugmentor): ' Resize image to a target size' def __init__(self, shape, interp=cv2.INTER_CUBIC): '\n :param shape: shape in (h, w)\n ' shape = tuple(shape2d(shape)) self._init(locals()) def _augment(self, img, _): return cv2.resize(img, self.shape[::(- 1)], interpolation=self.interp)
class ResizeShortestEdge(ImageAugmentor): ' Resize the shortest edge to a certain number while\n keeping the aspect ratio\n ' def __init__(self, size): size = (size * 1.0) self._init(locals()) def _augment(self, img, _): (h, w) = img.shape[:2] scale = (self.size / min(h, w)) desSize = map(int, [(scale * w), (scale * h)]) img = cv2.resize(img, tuple(desSize), interpolation=cv2.INTER_CUBIC) return img
class RandomResize(ImageAugmentor): ' randomly rescale w and h of the image' def __init__(self, xrange, yrange, minimum=(0, 0), aspect_ratio_thres=0.15, interp=cv2.INTER_CUBIC): '\n :param xrange: (min, max) scaling ratio\n :param yrange: (min, max) scaling ratio\n :param minimum: (xmin, ymin). Avoid scaling down too much.\n :param aspect_ratio_thres: at most change k=20% aspect ratio\n ' super(RandomResize, self).__init__() self._init(locals()) def _get_augment_params(self, img): cnt = 0 while True: sx = self._rand_range(*self.xrange) sy = self._rand_range(*self.yrange) destX = int(max((sx * img.shape[1]), self.minimum[0])) destY = int(max((sy * img.shape[0]), self.minimum[1])) oldr = ((img.shape[1] * 1.0) / img.shape[0]) newr = ((destX * 1.0) / destY) diff = (abs((newr - oldr)) / oldr) if (diff <= self.aspect_ratio_thres): return (destX, destY) cnt += 1 if (cnt > 50): logger.warn('RandomResize failed to augment an image') return (img.shape[1], img.shape[0]) def _augment(self, img, dsize): return cv2.resize(img, dsize, interpolation=self.interp)
class PrefetchProcess(mp.Process): def __init__(self, ds, queue, reset_after_spawn=True): '\n :param ds: ds to take data from\n :param queue: output queue to put results in\n ' super(PrefetchProcess, self).__init__() self.ds = ds self.queue = queue self.reset_after_spawn = reset_after_spawn def run(self): if self.reset_after_spawn: self.ds.reset_state() while True: for dp in self.ds.get_data(): self.queue.put(dp)
class PrefetchData(ProxyDataFlow): '\n Prefetch data from a `DataFlow` using multiprocessing\n ' def __init__(self, ds, nr_prefetch, nr_proc=1): '\n :param ds: a `DataFlow` instance.\n :param nr_prefetch: size of the queue to hold prefetched datapoints.\n :param nr_proc: number of processes to use. When larger than 1, order\n of data points will be random.\n ' super(PrefetchData, self).__init__(ds) try: self._size = ds.size() except NotImplementedError: self._size = (- 1) self.nr_proc = nr_proc self.nr_prefetch = nr_prefetch self.queue = mp.Queue(self.nr_prefetch) self.procs = [PrefetchProcess(self.ds, self.queue) for _ in range(self.nr_proc)] ensure_proc_terminate(self.procs) for x in self.procs: x.start() def get_data(self): for k in itertools.count(): if ((self._size > 0) and (k >= self._size)): break dp = self.queue.get() (yield dp) def reset_state(self): pass
def BlockParallel(ds, queue_size): '\n Insert `BlockParallel` in dataflow pipeline to block parallelism on ds\n\n :param ds: a `DataFlow`\n :param queue_size: size of the queue used\n ' return PrefetchData(ds, queue_size, 1)
class PrefetchProcessZMQ(mp.Process): def __init__(self, ds, conn_name): '\n :param ds: a `DataFlow` instance.\n :param conn_name: the name of the IPC connection\n ' super(PrefetchProcessZMQ, self).__init__() self.ds = ds self.conn_name = conn_name def run(self): self.ds.reset_state() self.context = zmq.Context() self.socket = self.context.socket(zmq.PUSH) self.socket.set_hwm(5) self.socket.connect(self.conn_name) while True: for dp in self.ds.get_data(): self.socket.send(dumps(dp), copy=False)
class PrefetchDataZMQ(ProxyDataFlow): ' Work the same as `PrefetchData`, but faster. ' def __init__(self, ds, nr_proc=1, pipedir=None): "\n :param ds: a `DataFlow` instance.\n :param nr_proc: number of processes to use. When larger than 1, order\n of datapoints will be random.\n :param pipedir: a local directory where the pipes would be. Useful if you're running on non-local FS such as NFS.\n " super(PrefetchDataZMQ, self).__init__(ds) try: self._size = ds.size() except NotImplementedError: self._size = (- 1) self.nr_proc = nr_proc self.context = zmq.Context() self.socket = self.context.socket(zmq.PULL) if (pipedir is None): pipedir = os.environ.get('TENSORPACK_PIPEDIR', '.') assert os.path.isdir(pipedir), pipedir self.pipename = ('ipc://{}/dataflow-pipe-'.format(pipedir.rstrip('/')) + str(uuid.uuid1())[:6]) self.socket.set_hwm(5) self.socket.bind(self.pipename) self.procs = [PrefetchProcessZMQ(self.ds, self.pipename) for _ in range(self.nr_proc)] self.start_processes() import atexit atexit.register((lambda x: x.__del__()), self) def start_processes(self): start_proc_mask_signal(self.procs) def get_data(self): for k in itertools.count(): if ((self._size > 0) and (k >= self._size)): break dp = loads(self.socket.recv(copy=False).bytes) (yield dp) def reset_state(self): pass def __del__(self): if (not self.context.closed): self.context.destroy(0) for x in self.procs: x.terminate() try: print('Prefetch process exited.') except: pass
class PrefetchOnGPUs(PrefetchDataZMQ): ' Prefetch with each process having a specific CUDA_VISIBLE_DEVICES\n variable' def __init__(self, ds, gpus, pipedir=None): self.gpus = gpus super(PrefetchOnGPUs, self).__init__(ds, len(gpus), pipedir) def start_processes(self): with mask_sigint(): for (gpu, proc) in zip(self.gpus, self.procs): with change_gpu(gpu): proc.start()
class FakeData(RNGDataFlow): ' Generate fake fixed data of given shapes' def __init__(self, shapes, size, random=True, dtype='float32'): '\n :param shapes: a list of lists/tuples\n :param size: size of this DataFlow\n :param random: whether to randomly generate data every iteration. note\n that only generating the data could be time-consuming!\n ' super(FakeData, self).__init__() self.shapes = shapes self._size = int(size) self.random = random self.dtype = dtype def size(self): return self._size def get_data(self): if self.random: for _ in range(self._size): (yield [self.rng.rand(*k).astype(self.dtype) for k in self.shapes]) else: v = [self.rng.rand(*k).astype(self.dtype) for k in self.shapes] for _ in range(self._size): (yield copy.deepcopy(v))
class DataFromQueue(DataFlow): ' Produce data from a queue ' def __init__(self, queue): self.queue = queue def get_data(self): while True: (yield self.queue.get())
class DataFromList(RNGDataFlow): ' Produce data from a list' def __init__(self, lst, shuffle=True): super(DataFromList, self).__init__() self.lst = lst self.shuffle = shuffle def size(self): return len(self.lst) def get_data(self): if (not self.shuffle): for k in self.lst: (yield k) else: idxs = np.arange(len(self.lst)) self.rng.shuffle(idxs) for k in idxs: (yield self.lst[k])
class DataFromSocket(DataFlow): ' Produce data from a zmq socket' def __init__(self, socket_name): self._name = socket_name def get_data(self): try: ctx = zmq.Context() socket = ctx.socket(zmq.PULL) socket.bind(self._name) while True: dp = loads(socket.recv(copy=False)) (yield dp) finally: ctx.destroy(linger=0)
def serve_data(ds, addr): ctx = zmq.Context() socket = ctx.socket(zmq.PUSH) socket.set_hwm(10) socket.bind(addr) ds = RepeatedData(ds, (- 1)) try: ds.reset_state() logger.info('Serving data at {}'.format(addr)) while True: for dp in ds.get_data(): socket.send(dumps(dp), copy=False) finally: socket.setsockopt(zmq.LINGER, 0) socket.close() if (not ctx.closed): ctx.destroy(0)
class RemoteData(DataFlow): def __init__(self, addr): self.ctx = zmq.Context() self.socket = self.ctx.socket(zmq.PULL) self.socket.set_hwm(10) self.socket.connect(addr) def get_data(self): while True: dp = loads(self.socket.recv(copy=False)) (yield dp)
class TFFuncMapper(ProxyDataFlow): def __init__(self, ds, get_placeholders, symbf, apply_symbf_on_dp, device='/cpu:0'): '\n :param get_placeholders: a function returning the placeholders\n :param symbf: a symbolic function taking the placeholders\n :param apply_symbf_on_dp: apply the above function to datapoint\n ' super(TFFuncMapper, self).__init__(ds) self.get_placeholders = get_placeholders self.symbf = symbf self.apply_symbf_on_dp = apply_symbf_on_dp self.device = device def reset_state(self): super(TFFuncMapper, self).reset_state() self.graph = tf.Graph() with self.graph.as_default(), tf.device(self.device): self.placeholders = self.get_placeholders() self.output_vars = self.symbf(self.placeholders) self.sess = tf.Session() def run_func(vals): return self.sess.run(self.output_vars, feed_dict=dict(zip(self.placeholders, vals))) self.run_func = run_func def get_data(self): for dp in self.ds.get_data(): dp = self.apply_symbf_on_dp(dp, self.run_func) if dp: (yield dp)
@layer_register() def Depthwise(x, out_channel, kernel_shape, padding='SAME', stride=1, W_init=None, b_init=None, nl=tf.identity, channel_multiplier=1, use_bias=True, data_format='NHWC'): ' Function to build the depth-wise convolution layer.' in_shape = x.get_shape().as_list() channel_axis = (3 if (data_format == 'NHWC') else 1) in_channel = in_shape[channel_axis] assert (in_channel is not None), '[Depthwise] Input cannot have unknown channel!' kernel_shape = shape2d(kernel_shape) padding = padding.upper() filter_shape = (kernel_shape + [in_channel, channel_multiplier]) stride = [1, stride, stride, 1] if (W_init is None): W_init = tf.contrib.layers.variance_scaling_initializer() if (b_init is None): b_init = tf.constant_initializer() W = tf.get_variable('W', filter_shape, initializer=W_init) if use_bias: b = tf.get_variable('b', [out_channel], initializer=b_init) depth = tf.nn.depthwise_conv2d(x, W, stride, padding, name='depthwise_weights') return depth
@layer_register() def depthwise_separable_conv(x, num_pwc_filters, kernel_size, stride, depth_multiplier=1, padding='SAME', rate=1, scope=None): ' Function to build the depth-wise separable convolution layer.\n ' num_pwc_filters = round((num_pwc_filters * depth_multiplier)) batch_norm_params = {'center': True, 'scale': True, 'decay': 0.9997, 'epsilon': 0.001} with slim.arg_scope([slim.batch_norm], **batch_norm_params): depthwise_conv = slim.separable_convolution2d(x, num_outputs=None, stride=stride, depth_multiplier=1, padding='SAME', normalizer_fn=slim.batch_norm, activation_fn=tf.nn.relu, kernel_size=kernel_size, scope='dw') pointwise_conv = slim.convolution2d(depthwise_conv, num_pwc_filters, kernel_size=[1, 1], padding='SAME', stride=1, normalizer_fn=slim.batch_norm, activation_fn=tf.nn.relu, scope='sep') return pointwise_conv
def _global_import(name): p = __import__(name, globals(), locals(), level=1) lst = (p.__all__ if ('__all__' in dir(p)) else dir(p)) del globals()[name] for k in lst: globals()[k] = p.__dict__[k] __all__.append(k)
class LinearWrap(object): ' A simple wrapper to easily create linear graph,\n for layers with one input&output, or tf function with one input&output\n ' class TFModuleFunc(object): def __init__(self, mod, tensor): self._mod = mod self._t = tensor def __getattr__(self, name): ret = getattr(self._mod, name) if isinstance(ret, ModuleType): return LinearWrap.TFModuleFunc(ret, self._t) else: def f(*args, **kwargs): o = ret(self._t, *args, **kwargs) return LinearWrap(o) return f def __init__(self, tensor): self._t = tensor def __getattr__(self, layer_name): layer = eval(layer_name) if hasattr(layer, 'f'): if layer.use_scope: def f(name, *args, **kwargs): ret = layer(name, self._t, *args, **kwargs) return LinearWrap(ret) else: def f(*args, **kwargs): if (len(args) and isinstance(args[0], six.string_types)): (name, args) = (args[0], args[1:]) ret = layer(name, self._t, *args, **kwargs) else: ret = layer(self._t, *args, **kwargs) return LinearWrap(ret) return f else: if (layer_name != 'tf'): logger.warn("You're calling LinearWrap.__getattr__ with something neither a layer nor 'tf'!") assert isinstance(layer, ModuleType) return LinearWrap.TFModuleFunc(layer, self._t) def apply(self, func, *args, **kwargs): ' send tensor to the first argument of a simple func' ret = func(self._t, *args, **kwargs) return LinearWrap(ret) def __call__(self): return self._t def tensor(self): return self._t def print_tensor(self): print(self._t) return self
def disable_layer_logging(): class ContainEverything(): def __contains__(self, x): return True globals()['_layer_logged'] = ContainEverything()
def layer_register(summary_activation=False, log_shape=True, use_scope=True): '\n Register a layer.\n :param summary_activation: Define the default behavior of whether to\n summary the output(activation) of this layer.\n Can be overriden when creating the layer.\n :param log_shape: log input/output shape of this layer\n :param use_scope: whether to call this layer with an extra first argument as scope\n if set to False, will try to figure out whether the first argument is scope name\n ' def wrapper(func): @wraps(func) def wrapped_func(*args, **kwargs): if use_scope: (name, inputs) = (args[0], args[1]) args = args[1:] assert isinstance(name, six.string_types), name else: assert ((not log_shape) and (not summary_activation)) if isinstance(args[0], six.string_types): (name, inputs) = (args[0], args[1]) args = args[1:] else: inputs = args[0] name = None if (not (isinstance(inputs, (tf.Tensor, tf.Variable)) or (isinstance(inputs, (list, tuple)) and isinstance(inputs[0], (tf.Tensor, tf.Variable))))): raise ValueError(('Invalid inputs to layer: ' + str(inputs))) do_summary = kwargs.pop('summary_activation', summary_activation) actual_args = copy.copy(get_arg_scope()[func.__name__]) actual_args.update(kwargs) if (name is not None): with tf.variable_scope(name) as scope: do_log_shape = (log_shape and (scope.name not in _layer_logged)) do_summary = (do_summary and (scope.name not in _layer_logged)) if do_log_shape: logger.info('{} input: {}'.format(scope.name, get_shape_str(inputs))) outputs = func(*args, **actual_args) if do_log_shape: logger.info('{} output: {}'.format(scope.name, get_shape_str(outputs))) _layer_logged.add(scope.name) if do_summary: if isinstance(outputs, list): for x in outputs: add_activation_summary(x, scope.name) else: add_activation_summary(outputs, scope.name) else: outputs = func(*args, **actual_args) return outputs wrapped_func.f = func wrapped_func.use_scope = use_scope return wrapped_func on_doc = ((os.environ.get('READTHEDOCS') == 'True') or os.environ.get('TENSORPACK_DOC_BUILDING')) if on_doc: from decorator import decorator wrapper = decorator(wrapper) return wrapper
def shape4d(a): return (([1] + shape2d(a)) + [1])
class TestModel(unittest.TestCase): def run_variable(self, var): sess = tf.Session() sess.run(tf.initialize_all_variables()) if isinstance(var, list): return sess.run(var) else: return sess.run([var])[0] def make_variable(self, *args): if (len(args) > 1): return [tf.Variable(k) for k in args] else: return tf.Variable(args[0])
def run_test_case(case): suite = unittest.TestLoader().loadTestsFromTestCase(case) unittest.TextTestRunner(verbosity=2).run(suite)
@layer_register(log_shape=False) def BatchNormV1(x, use_local_stat=None, decay=0.9, epsilon=1e-05): '\n Batch normalization layer as described in:\n\n `Batch Normalization: Accelerating Deep Network Training by\n Reducing Internal Covariance Shift <http://arxiv.org/abs/1502.03167>`_.\n\n :param input: a NHWC or NC tensor\n :param use_local_stat: bool. whether to use mean/var of this batch or the moving average.\n Default to True in training and False in inference.\n :param decay: decay rate. default to 0.9.\n :param epsilon: default to 1e-5.\n\n Note that only the first training tower maintains a moving average.\n ' shape = x.get_shape().as_list() assert (len(shape) in [2, 4]) n_out = shape[(- 1)] assert (n_out is not None) beta = tf.get_variable('beta', [n_out], initializer=tf.constant_initializer()) gamma = tf.get_variable('gamma', [n_out], initializer=tf.constant_initializer(1.0)) if (len(shape) == 2): (batch_mean, batch_var) = tf.nn.moments(x, [0], keep_dims=False) else: (batch_mean, batch_var) = tf.nn.moments(x, [0, 1, 2], keep_dims=False) batch_mean = tf.identity(batch_mean, 'mean') batch_var = tf.identity(batch_var, 'variance') emaname = 'EMA' ctx = get_current_tower_context() if (use_local_stat is None): use_local_stat = ctx.is_training if (use_local_stat != ctx.is_training): logger.warn('[BatchNorm] use_local_stat != is_training') if use_local_stat: if ctx.is_training: with tf.variable_scope(tf.get_variable_scope(), reuse=False): with tf.name_scope(None): ema = tf.train.ExponentialMovingAverage(decay=decay, name=emaname) ema_apply_op = ema.apply([batch_mean, batch_var]) (ema_mean, ema_var) = (ema.average(batch_mean), ema.average(batch_var)) if ctx.is_main_training_tower: add_model_variable(ema_mean) add_model_variable(ema_var) else: assert (not ctx.is_training) with tf.name_scope(None): ema = tf.train.ExponentialMovingAverage(decay=decay, name=emaname) mean_var_name = ema.average_name(batch_mean) var_var_name = ema.average_name(batch_var) sc = tf.get_variable_scope() if ctx.is_main_tower: ema_mean = tf.get_variable(('mean/' + emaname), [n_out]) ema_var = tf.get_variable(('variance/' + emaname), [n_out]) else: G = tf.get_default_graph() ema_mean = ctx.find_tensor_in_main_tower(G, (mean_var_name + ':0')) ema_var = ctx.find_tensor_in_main_tower(G, (var_var_name + ':0')) if use_local_stat: batch = tf.cast(tf.shape(x)[0], tf.float32) mul = tf.where(tf.equal(batch, 1.0), 1.0, (batch / (batch - 1))) batch_var = (batch_var * mul) with tf.control_dependencies(([ema_apply_op] if ctx.is_training else [])): return tf.nn.batch_normalization(x, batch_mean, batch_var, beta, gamma, epsilon, 'output') else: return tf.nn.batch_normalization(x, ema_mean, ema_var, beta, gamma, epsilon, 'output')
@layer_register(log_shape=False) def BatchNormV2(x, use_local_stat=None, decay=0.9, epsilon=1e-05, post_scale=True): '\n Batch normalization layer as described in:\n\n `Batch Normalization: Accelerating Deep Network Training by\n Reducing Internal Covariance Shift <http://arxiv.org/abs/1502.03167>`_.\n\n :param input: a NHWC or NC tensor\n :param use_local_stat: bool. whether to use mean/var of this batch or the moving average.\n Default to True in training and False in inference.\n :param decay: decay rate. default to 0.9.\n :param epsilon: default to 1e-5.\n\n Note that only the first training tower maintains a moving average.\n ' shape = x.get_shape().as_list() assert (len(shape) in [2, 4]) n_out = shape[(- 1)] assert (n_out is not None), 'Input to BatchNorm cannot have unknown channels!' if (len(shape) == 2): x = tf.reshape(x, [(- 1), 1, 1, n_out]) beta = tf.get_variable('beta', [n_out], initializer=tf.constant_initializer()) gamma = tf.get_variable('gamma', [n_out], initializer=tf.constant_initializer(1.0)) if (not post_scale): beta = (0.0 * beta) gamma = ((0.0 * gamma) + tf.ones_like(gamma)) ctx = get_current_tower_context() if (use_local_stat is None): use_local_stat = ctx.is_training if (use_local_stat != ctx.is_training): logger.warn('[BatchNorm] use_local_stat != is_training') moving_mean = tf.get_variable('mean/EMA', [n_out], initializer=tf.constant_initializer(), trainable=False) moving_var = tf.get_variable('variance/EMA', [n_out], initializer=tf.constant_initializer(), trainable=False) if use_local_stat: (xn, batch_mean, batch_var) = tf.nn.fused_batch_norm(x, gamma, beta, epsilon=epsilon, is_training=True) if ctx.is_main_training_tower: update_op1 = moving_averages.assign_moving_average(moving_mean, batch_mean, decay, zero_debias=False, name='mean_ema_op') update_op2 = moving_averages.assign_moving_average(moving_var, batch_var, decay, zero_debias=False, name='var_ema_op') add_model_variable(moving_mean) add_model_variable(moving_var) else: assert (not ctx.is_training), 'In training, local statistics has to be used!' xn = tf.nn.batch_normalization(x, moving_mean, moving_var, beta, gamma, epsilon) if ctx.is_main_training_tower: with tf.control_dependencies([update_op1, update_op2]): return tf.identity(xn, name='output') else: return tf.identity(xn, name='output')
@layer_register() def FullyConnected(x, out_dim, W_init=None, b_init=None, nl=None, use_bias=True): '\n Fully-Connected layer.\n\n :param input: a tensor to be flattened except the first dimension.\n :param out_dim: output dimension\n :param W_init: initializer for W. default to `xavier_initializer_conv2d`.\n :param b_init: initializer for b. default to zero initializer.\n :param nl: nonlinearity\n :param use_bias: whether to use bias. a boolean default to True\n :returns: a 2D tensor\n ' x = symbf.batch_flatten(x) in_dim = x.get_shape().as_list()[1] if (W_init is None): W_init = tf.contrib.layers.variance_scaling_initializer() if (b_init is None): b_init = tf.constant_initializer() W = tf.get_variable('W', [in_dim, out_dim], initializer=W_init) if use_bias: b = tf.get_variable('b', [out_dim], initializer=b_init) prod = (tf.nn.xw_plus_b(x, W, b) if use_bias else tf.matmul(x, W)) if (nl is None): logger.warn('[DEPRECATED] Default ReLU nonlinearity for Conv2D and FullyConnected will be deprecated. Please use argscope instead.') nl = tf.nn.relu return nl(prod, name='output')
class InputVar(object): def __init__(self, type, shape, name, sparse=False): self.type = type self.shape = shape self.name = name self.sparse = sparse def dumps(self): return pickle.dumps(self) @staticmethod def loads(buf): return pickle.loads(buf)
@six.add_metaclass(ABCMeta) class ModelDesc(object): ' Base class for a model description ' def get_input_vars(self): '\n Create or return (if already created) raw input TF placeholder vars in the graph.\n\n :returns: the list of raw input vars in the graph\n ' if hasattr(self, 'reuse_input_vars'): return self.reuse_input_vars ret = self.build_placeholders() self.reuse_input_vars = ret return ret get_reuse_placehdrs = get_input_vars def build_placeholders(self, prefix=''): ' build placeholders with optional prefix, for each InputVar\n ' input_vars = self._get_input_vars() for v in input_vars: tf.add_to_collection(INPUT_VARS_KEY, v.dumps()) ret = [] for v in input_vars: placehdr_f = (tf.placeholder if (not v.sparse) else tf.sparse_placeholder) ret.append(placehdr_f(v.type, shape=v.shape, name=(prefix + v.name))) return ret def get_input_vars_desc(self): ' return a list of `InputVar` instance' return self._get_input_vars() @abstractmethod def _get_input_vars(self): ':returns: a list of InputVar ' def build_graph(self, model_inputs): '\n Setup the whole graph.\n\n :param model_inputs: a list of input variable in the graph.\n :param is_training: a boolean\n :returns: the cost to minimize. a scalar variable\n ' if (len(inspect.getargspec(self._build_graph).args) == 3): logger.warn('[DEPRECATED] _build_graph(self, input_vars, is_training) is deprecated! Use _build_graph(self, input_vars) and get_current_tower_context().is_training instead.') self._build_graph(model_inputs, get_current_tower_context().is_training) else: self._build_graph(model_inputs) @abstractmethod def _build_graph(self, inputs): pass def get_cost(self): return self._get_cost() def _get_cost(self, *args): return self.cost def get_gradient_processor(self): ' Return a list of GradientProcessor. They will be executed in order' return [CheckGradient()]
class ModelFromMetaGraph(ModelDesc): '\n Load the whole exact TF graph from a saved meta_graph.\n Only useful for inference.\n ' def __init__(self, filename): tf.train.import_meta_graph(filename) all_coll = tf.get_default_graph().get_all_collection_keys() for k in [INPUT_VARS_KEY, tf.GraphKeys.TRAINABLE_VARIABLES, tf.GraphKeys().VARIABLES]: assert (k in all_coll), 'Collection {} not found in metagraph!'.format(k) def _get_input_vars(self): col = tf.get_collection(INPUT_VARS_KEY) col = [InputVar.loads(v) for v in col] return col def _build_graph(self, _, __): ' Do nothing. Graph was imported already ' pass
@layer_register() def Maxout(x, num_unit): '\n Maxout as in `Maxout Networks <http://arxiv.org/abs/1302.4389>`_.\n\n :param input: a NHWC or NC tensor.\n :param num_unit: a int. must be divisible by C.\n :returns: a NHW(C/num_unit) tensor\n ' input_shape = x.get_shape().as_list() ndim = len(input_shape) assert ((ndim == 4) or (ndim == 2)) ch = input_shape[(- 1)] assert ((ch is not None) and ((ch % num_unit) == 0)) if (ndim == 4): x = tf.reshape(x, [(- 1), input_shape[1], input_shape[2], (ch / num_unit), num_unit]) else: x = tf.reshape(x, [(- 1), (ch / num_unit), num_unit]) return tf.reduce_max(x, ndim, name='output')
@layer_register(log_shape=False) def PReLU(x, init=tf.constant_initializer(0.001), name=None): '\n Parameterized relu as in `Delving Deep into Rectifiers: Surpassing\n Human-Level Performance on ImageNet Classification\n <http://arxiv.org/abs/1502.01852>`_.\n\n :param input: any tensor.\n :param init: initializer for the p. default to 0.001.\n ' alpha = tf.get_variable('alpha', [], initializer=init) x = (((1 + alpha) * x) + ((1 - alpha) * tf.abs(x))) if (name is None): name = 'output' return tf.mul(x, 0.5, name=name)
@layer_register(use_scope=False, log_shape=False) def LeakyReLU(x, alpha, name=None): '\n Leaky relu as in `Rectifier Nonlinearities Improve Neural Network Acoustic\n Models\n <http://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf>`_.\n\n :param input: any tensor.\n :param alpha: the negative slope.\n ' if (name is None): name = 'output' return tf.maximum(x, (alpha * x), name=name)
@layer_register(log_shape=False, use_scope=False) def BNReLU(x, name=None): x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
@memoized def _log_regularizer(name): logger.info('Apply regularizer for {}'.format(name))
def regularize_cost(regex, func, name=None): '\n Apply a regularizer on every trainable variable matching the regex.\n\n :param func: a function that takes a tensor and return a scalar.\n ' G = tf.get_default_graph() params = G.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) costs = [] for p in params: para_name = p.name if re.search(regex, para_name): costs.append(func(p)) _log_regularizer(para_name) if (not costs): return 0 return tf.add_n(costs, name=name)
@layer_register(log_shape=False, use_scope=False) def Dropout(x, keep_prob=0.5, is_training=None): '\n :param is_training: if None, will use the current context by default.\n ' if (is_training is None): is_training = get_current_tower_context().is_training keep_prob = tf.constant((keep_prob if is_training else 1.0)) return tf.nn.dropout(x, keep_prob)