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, 'sy... |
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... |
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 + filen... |
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)))
... |
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_item... |
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_... |
@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)
... |
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 {tr... |
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(rea... |
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 componen... |
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)
... |
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 ... |
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 ... |
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 in... |
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 :para... |
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... |
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)
retur... |
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_augmen... |
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):
... |
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 i... |
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... |
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', im... |
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... |
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... |
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: p... |
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... |
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... |
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... |
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
sel... |
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: nu... |
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 ru... |
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... |
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... |
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 iterati... |
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):
... |
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:
... |
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():
... |
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))
(y... |
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... |
@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_f... |
@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... |
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 __geta... |
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 inpu... |
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(... |
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:... |
@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... |
@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_co... |
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... |
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... |
@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... |
@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 in... |
@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 ... |
@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 = []
f... |
@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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.