code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def calculate_fid_given_paths(paths, batch_size, cuda, dims): """Calculates the FID of two paths""" for p in paths: if not os.path.exists(p): raise RuntimeError('Invalid path: %s' % p) block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims] model = InceptionV3([block_idx]) if cuda: ...
Calculates the FID of two paths
calculate_fid_given_paths
python
OFA-Sys/OFA
run_scripts/image_gen/fid_score.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/image_gen/fid_score.py
Apache-2.0
def inception_score(imgs, cuda=True, batch_size=32, resize=False, splits=1): """Computes the inception score of the generated images imgs imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1] cuda -- whether or not to run on GPU batch_size -- batch size for feeding into Inception...
Computes the inception score of the generated images imgs imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1] cuda -- whether or not to run on GPU batch_size -- batch size for feeding into Inception v3 splits -- number of splits
inception_score
python
OFA-Sys/OFA
run_scripts/image_gen/inception_score.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/image_gen/inception_score.py
Apache-2.0
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False): """Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indice...
Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are: - 0: corresponds to output of first max pooling - 1: corresponds to output of second max pooling ...
__init__
python
OFA-Sys/OFA
run_scripts/image_gen/eval_utils/inceptionV3.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/image_gen/eval_utils/inceptionV3.py
Apache-2.0
def forward(self, inp): """Get Inception feature maps Parameters ---------- inp : torch.autograd.Variable Input tensor of shape Bx3xHxW. Values are expected to be in range (0, 1) Returns ------- List of torch.autograd.Variable, correspond...
Get Inception feature maps Parameters ---------- inp : torch.autograd.Variable Input tensor of shape Bx3xHxW. Values are expected to be in range (0, 1) Returns ------- List of torch.autograd.Variable, corresponding to the selected output ...
forward
python
OFA-Sys/OFA
run_scripts/image_gen/eval_utils/inceptionV3.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/image_gen/eval_utils/inceptionV3.py
Apache-2.0
def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for chars in word: child = node.data.get(chars) if not child: node.data[chars] = TrieNode() node = node....
Inserts a word into the trie. :type word: str :rtype: void
insert
python
OFA-Sys/OFA
utils/text2phone.py
https://github.com/OFA-Sys/OFA/blob/master/utils/text2phone.py
Apache-2.0
def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.root for chars in word: node = node.data.get(chars) if not node: return False return node.is_word
Returns if the word is in the trie. :type word: str :rtype: bool
search
python
OFA-Sys/OFA
utils/text2phone.py
https://github.com/OFA-Sys/OFA/blob/master/utils/text2phone.py
Apache-2.0
def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ node = self.root for chars in prefix: node = node.data.get(chars) if not node: ...
Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool
startsWith
python
OFA-Sys/OFA
utils/text2phone.py
https://github.com/OFA-Sys/OFA/blob/master/utils/text2phone.py
Apache-2.0
def get_start(self, prefix): """ Returns words started with prefix :param prefix: :return: words (list) """ def get_key(pre, pre_node): word_list = [] if pre_node.is_word: word_list.append(pre) for x in pre_node.d...
Returns words started with prefix :param prefix: :return: words (list)
get_start
python
OFA-Sys/OFA
utils/text2phone.py
https://github.com/OFA-Sys/OFA/blob/master/utils/text2phone.py
Apache-2.0
def autocontrast_func(img, cutoff=0): ''' same output as PIL.ImageOps.autocontrast ''' n_bins = 256 def tune_channel(ch): n = ch.size cut = cutoff * n // 100 if cut == 0: high, low = ch.max(), ch.min() else: hist = cv2.calcHist([ch], [0], ...
same output as PIL.ImageOps.autocontrast
autocontrast_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def equalize_func(img): ''' same output as PIL.ImageOps.equalize PIL's implementation is different from cv2.equalize ''' n_bins = 256 def tune_channel(ch): hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins]) non_zero_hist = hist[hist != 0].reshape(-1) ste...
same output as PIL.ImageOps.equalize PIL's implementation is different from cv2.equalize
equalize_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def rotate_func(img, degree, fill=(0, 0, 0)): ''' like PIL, rotate by degree, not radians ''' H, W = img.shape[0], img.shape[1] center = W / 2, H / 2 M = cv2.getRotationMatrix2D(center, degree, 1) out = cv2.warpAffine(img, M, (W, H), borderValue=fill) return out
like PIL, rotate by degree, not radians
rotate_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def solarize_func(img, thresh=128): ''' same output as PIL.ImageOps.posterize ''' table = np.array([el if el < thresh else 255 - el for el in range(256)]) table = table.clip(0, 255).astype(np.uint8) out = table[img] return out
same output as PIL.ImageOps.posterize
solarize_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def color_func(img, factor): ''' same output as PIL.ImageEnhance.Color ''' ## implementation according to PIL definition, quite slow # degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis] # out = blend(degenerate, img, factor) # M = ( # np.eye(3) * factor ...
same output as PIL.ImageEnhance.Color
color_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def contrast_func(img, factor): """ same output as PIL.ImageEnhance.Contrast """ mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299])) table = np.array([( el - mean) * factor + mean for el in range(256) ]).clip(0, 255).astype(np.uint8) out = table[img...
same output as PIL.ImageEnhance.Contrast
contrast_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def sharpness_func(img, factor): ''' The differences the this result and PIL are all on the 4 boundaries, the center areas are same ''' kernel = np.ones((3, 3), dtype=np.float32) kernel[1][1] = 5 kernel /= 13 degenerate = cv2.filter2D(img, -1, kernel) if factor == 0.0: out = ...
The differences the this result and PIL are all on the 4 boundaries, the center areas are same
sharpness_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def translate_x_func(img, offset, fill=(0, 0, 0)): ''' same output as PIL.Image.transform ''' H, W = img.shape[0], img.shape[1] M = np.float32([[1, 0, -offset], [0, 1, 0]]) out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) return out
same output as PIL.Image.transform
translate_x_func
python
OFA-Sys/OFA
utils/vision_helper.py
https://github.com/OFA-Sys/OFA/blob/master/utils/vision_helper.py
Apache-2.0
def __init__(self, n=4, df="corpus"): """ Initialize the CIDEr scoring function : param n (int): n-gram size : param df (string): specifies where to get the IDF values from takes values 'corpus', 'coco-train' : return: None """ # set cider to s...
Initialize the CIDEr scoring function : param n (int): n-gram size : param df (string): specifies where to get the IDF values from takes values 'corpus', 'coco-train' : return: None
__init__
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider.py
Apache-2.0
def compute_score(self, gts, res): """ Main function to compute CIDEr score : param gts (dict) : {image:tokenized reference sentence} : param res (dict) : {image:tokenized candidate sentence} : return: cider (float) : computed CIDEr score for the corpus """ # c...
Main function to compute CIDEr score : param gts (dict) : {image:tokenized reference sentence} : param res (dict) : {image:tokenized candidate sentence} : return: cider (float) : computed CIDEr score for the corpus
compute_score
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider.py
Apache-2.0
def precook(s, n=4, out=False): """ Takes a string as input and returns an object that can be given to either cook_refs or cook_test. This is optional: cook_refs and cook_test can take string arguments as well. :param s: string : sentence to be converted into ngrams :param n: int : number of ...
Takes a string as input and returns an object that can be given to either cook_refs or cook_test. This is optional: cook_refs and cook_test can take string arguments as well. :param s: string : sentence to be converted into ngrams :param n: int : number of ngrams for which representation is calc...
precook
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider_scorer.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider_scorer.py
Apache-2.0
def cook_append(self, test, refs): '''called by constructor and __iadd__ to avoid creating new instances.''' if refs is not None: self.crefs.append(cook_refs(refs)) if test is not None: self.ctest.append(cook_test(test)) ## N.B.: -1 else: ...
called by constructor and __iadd__ to avoid creating new instances.
cook_append
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider_scorer.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider_scorer.py
Apache-2.0
def __iadd__(self, other): '''add an instance (e.g., from another sentence).''' if type(other) is tuple: ## avoid creating new CiderScorer instances self.cook_append(other[0], other[1]) else: self.ctest.extend(other.ctest) self.crefs.extend(other....
add an instance (e.g., from another sentence).
__iadd__
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider_scorer.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider_scorer.py
Apache-2.0
def compute_doc_freq(self): ''' Compute term frequency for reference data. This will be used to compute idf (inverse document frequency later) The term frequency is stored in the object :return: None ''' for refs in self.crefs: # refs, k ref captions o...
Compute term frequency for reference data. This will be used to compute idf (inverse document frequency later) The term frequency is stored in the object :return: None
compute_doc_freq
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider_scorer.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider_scorer.py
Apache-2.0
def counts2vec(cnts): """ Function maps counts of ngram to vector of tfidf weights. The function returns vec, an array of dictionary that store mapping of n-gram and tf-idf weights. The n-th entry of array denotes length of n-grams. :param cnts: :r...
Function maps counts of ngram to vector of tfidf weights. The function returns vec, an array of dictionary that store mapping of n-gram and tf-idf weights. The n-th entry of array denotes length of n-grams. :param cnts: :return: vec (array of dict), norm (arr...
counts2vec
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider_scorer.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider_scorer.py
Apache-2.0
def sim(vec_hyp, vec_ref, norm_hyp, norm_ref, length_hyp, length_ref): ''' Compute the cosine similarity of two vectors. :param vec_hyp: array of dictionary for vector corresponding to hypothesis :param vec_ref: array of dictionary for vector corresponding to reference ...
Compute the cosine similarity of two vectors. :param vec_hyp: array of dictionary for vector corresponding to hypothesis :param vec_ref: array of dictionary for vector corresponding to reference :param norm_hyp: array of float for vector corresponding to hypothesis ...
sim
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/cider/cider_scorer.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/cider/cider_scorer.py
Apache-2.0
def compute_score(self, gts, res): """ Main function to compute CIDEr score :param hypo_for_image (dict) : dictionary with key <image> and value <tokenized hypothesis / candidate sentence> ref_for_image (dict) : dictionary with key <image> and value <tokenized reference sentenc...
Main function to compute CIDEr score :param hypo_for_image (dict) : dictionary with key <image> and value <tokenized hypothesis / candidate sentence> ref_for_image (dict) : dictionary with key <image> and value <tokenized reference sentence> :return: cider (float) : computed C...
compute_score
python
OFA-Sys/OFA
utils/cider/pyciderevalcap/ciderD/ciderD.py
https://github.com/OFA-Sys/OFA/blob/master/utils/cider/pyciderevalcap/ciderD/ciderD.py
Apache-2.0
def datagen(filter_files, time_len=1, batch_size=256, ignore_goods=False): """ Parameters: ----------- leads : bool, should we use all x, y and speed radar leads? default is false, uses only x """ global first assert time_len > 0 filter_names = sorted(filter_files) logger.info("Loading {} hdf5 bucket...
Parameters: ----------- leads : bool, should we use all x, y and speed radar leads? default is false, uses only x
datagen
python
commaai/research
dask_generator.py
https://github.com/commaai/research/blob/master/dask_generator.py
BSD-3-Clause
def send_arrays(socket, arrays, stop=False): """Send NumPy arrays using the buffer interface and some metadata. Parameters ---------- socket : :class:`zmq.Socket` The socket to send data over. arrays : list A list of :class:`numpy.ndarray` to transfer. stop : bool, optional Instead of sending a serie...
Send NumPy arrays using the buffer interface and some metadata. Parameters ---------- socket : :class:`zmq.Socket` The socket to send data over. arrays : list A list of :class:`numpy.ndarray` to transfer. stop : bool, optional Instead of sending a series of NumPy arrays, send a JSON object with a sin...
send_arrays
python
commaai/research
server.py
https://github.com/commaai/research/blob/master/server.py
BSD-3-Clause
def recv_arrays(socket): """Receive a list of NumPy arrays. Parameters ---------- socket : :class:`zmq.Socket` The socket to receive the arrays on. Returns ------- list A list of :class:`numpy.ndarray` objects. Raises ------ StopIteration If the first JSON object received contains the key `...
Receive a list of NumPy arrays. Parameters ---------- socket : :class:`zmq.Socket` The socket to receive the arrays on. Returns ------- list A list of :class:`numpy.ndarray` objects. Raises ------ StopIteration If the first JSON object received contains the key `stop`, signifying that the s...
recv_arrays
python
commaai/research
server.py
https://github.com/commaai/research/blob/master/server.py
BSD-3-Clause
def client_generator(port=5557, host="localhost", hwm=20): """Generator in client side should extend this generator Parameters ---------- port : int hwm : int, optional The `ZeroMQ high-water mark (HWM) <http://zguide.zeromq.org/page:all#High-Water-Marks>`_ on the sending socket. Increasing this incre...
Generator in client side should extend this generator Parameters ---------- port : int hwm : int, optional The `ZeroMQ high-water mark (HWM) <http://zguide.zeromq.org/page:all#High-Water-Marks>`_ on the sending socket. Increasing this increases the buffer, which can be useful if your data preprocessin...
client_generator
python
commaai/research
server.py
https://github.com/commaai/research/blob/master/server.py
BSD-3-Clause
def start_server(data_stream, port=5557, hwm=20): """Start a data processing server. This command starts a server in the current process that performs the actual data processing (by retrieving data from the given data stream). It also starts a second process, the broker, which mediates between the server and...
Start a data processing server. This command starts a server in the current process that performs the actual data processing (by retrieving data from the given data stream). It also starts a second process, the broker, which mediates between the server and the client. The broker also keeps a buffer of batches ...
start_server
python
commaai/research
server.py
https://github.com/commaai/research/blob/master/server.py
BSD-3-Clause
def train_model(name, g_train, d_train, sampler, generator, samples_per_epoch, nb_epoch, z_dim=100, verbose=1, callbacks=[], validation_data=None, nb_val_samples=None, saver=None): """ Main training loop. modified from Keras fit_generator """ self = {}...
Main training loop. modified from Keras fit_generator
train_model
python
commaai/research
train_generative_model.py
https://github.com/commaai/research/blob/master/train_generative_model.py
BSD-3-Clause
def dec_conv2d_block(x, name, f, k, bias=True, bn=False, stddev=0.02, data_format="NCHW", activation_fn=tf.nn.elu): """Decoding 2D conv block: chain 2 convolutions with""" with tf.variable_scope(name): if data_format == "NHWC": n_in = x.get_shape()[-1] elif data_format == "NCHW": ...
Decoding 2D conv block: chain 2 convolutions with
dec_conv2d_block
python
tdeboissiere/DeepLearningImplementations
BEGAN/src/utils/layers.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/BEGAN/src/utils/layers.py
MIT
def upsampleNN(x, name, s, data_format="NCHW"): """ Upsample image data by a factor s with NN interpolation""" with tf.variable_scope(name): # Transpose before resize if data_format == "NCHW": x = tf.transpose(x, [0, 2, 3, 1]) # Resize x_shape = x.get_shape().as_lis...
Upsample image data by a factor s with NN interpolation
upsampleNN
python
tdeboissiere/DeepLearningImplementations
BEGAN/src/utils/layers.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/BEGAN/src/utils/layers.py
MIT
def enc_conv2d_block(x, name, f, k, bias=True, bn=False, stddev=0.02, data_format="NCHW", activation_fn=tf.nn.elu, downsampling=True): """Encoding 2D conv block: chain 2 convolutions with x2 downsampling by default""" with tf.variable_scope(name): if data_format == "NHWC": n_in = x.get_shap...
Encoding 2D conv block: chain 2 convolutions with x2 downsampling by default
enc_conv2d_block
python
tdeboissiere/DeepLearningImplementations
BEGAN/src/utils/layers.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/BEGAN/src/utils/layers.py
MIT
def format_image(img_path, size): """ Load img with opencv and reshape """ img_color = cv2.imread(img_path) img_color = img_color[:, :, ::-1] img_black = cv2.imread(img_path, 0) img_color = cv2.resize(img_color, (size, size), interpolation=cv2.INTER_AREA) img_black = cv2.resize(img_bla...
Load img with opencv and reshape
format_image
python
tdeboissiere/DeepLearningImplementations
Colorful/src/data/make_dataset.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/data/make_dataset.py
MIT
def build_HDF5(size=64): """ Gather the data in a single HDF5 file. """ # Read evaluation file, build it if it does not exist # In evaluation status, "0" represents training image, "1" represents # validation image, "2" represents testing image; d_partition = {} with open(os.path.join(r...
Gather the data in a single HDF5 file.
build_HDF5
python
tdeboissiere/DeepLearningImplementations
Colorful/src/data/make_dataset.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/data/make_dataset.py
MIT
def check_HDF5(size=64): """ Plot images with landmarks to check the processing """ # Get hdf5 file hdf5_file = os.path.join(data_dir, "CelebA_%s_data.h5" % size) with h5py.File(hdf5_file, "r") as hf: data_color = hf["training_color_data"] data_lab = hf["training_lab_data"] ...
Plot images with landmarks to check the processing
check_HDF5
python
tdeboissiere/DeepLearningImplementations
Colorful/src/data/make_dataset.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/data/make_dataset.py
MIT
def train(**kwargs): """ Train model args: **kwargs (dict) keyword arguments that specify the model hyperparameters """ # Roll out the parameters batch_size = kwargs["batch_size"] n_batch_per_epoch = kwargs["n_batch_per_epoch"] nb_epoch = kwargs["nb_epoch"] data_file = kwargs["data...
Train model args: **kwargs (dict) keyword arguments that specify the model hyperparameters
train
python
tdeboissiere/DeepLearningImplementations
Colorful/src/model/train_colorful.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/model/train_colorful.py
MIT
def gen_batch(self, nn_finder, nb_q, prior_factor): """ Use multiprocessing to generate batches in parallel. """ try: queue = multiprocessing.Queue(maxsize=self.num_cached) # define producer (putting items into queue) def producer(): try: ...
Use multiprocessing to generate batches in parallel.
gen_batch
python
tdeboissiere/DeepLearningImplementations
Colorful/src/utils/batch_utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/utils/batch_utils.py
MIT
def gen_batch_in_memory(self, X, nn_finder, nb_q, prior_factor): """Generate batch, assuming X is loaded in memory in the main program""" while True: # Select idx at random for the batch idx = np.random.choice(X.shape[0], self.batch_size, replace=False) X_batch_colo...
Generate batch, assuming X is loaded in memory in the main program
gen_batch_in_memory
python
tdeboissiere/DeepLearningImplementations
Colorful/src/utils/batch_utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/utils/batch_utils.py
MIT
def remove_files(files): """ Remove files from disk args: files (str or list) remove all files in 'files' """ if isinstance(files, (list, tuple)): for f in files: if os.path.isfile(os.path.expanduser(f)): os.remove(f) elif isinstance(files, str): if ...
Remove files from disk args: files (str or list) remove all files in 'files'
remove_files
python
tdeboissiere/DeepLearningImplementations
Colorful/src/utils/general_utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/utils/general_utils.py
MIT
def create_dir(dirs): """ Create directory args: dirs (str or list) create all dirs in 'dirs' """ if isinstance(dirs, (list, tuple)): for d in dirs: if not os.path.exists(os.path.expanduser(d)): os.makedirs(d) elif isinstance(dirs, str): if not os.pa...
Create directory args: dirs (str or list) create all dirs in 'dirs'
create_dir
python
tdeboissiere/DeepLearningImplementations
Colorful/src/utils/general_utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Colorful/src/utils/general_utils.py
MIT
def __init__(self, model): """Creates a DeconvNet instance :param model: Keras model :returns: deconvnet class :rtype: deconvnet """ self.model = model list_layers = self.model.layers self.lnames = [l.name for l in list_layers] assert len(self.ln...
Creates a DeconvNet instance :param model: Keras model :returns: deconvnet class :rtype: deconvnet
__init__
python
tdeboissiere/DeepLearningImplementations
DeconvNet/KerasDeconv.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/KerasDeconv.py
MIT
def get_layers(self): """Returns the layers of the network :returns: returns the layers of the network :rtype: list """ list_layers = self.model.layers list_layers_name = [l.name for l in list_layers] return list_layers_name
Returns the layers of the network :returns: returns the layers of the network :rtype: list
get_layers
python
tdeboissiere/DeepLearningImplementations
DeconvNet/KerasDeconv.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/KerasDeconv.py
MIT
def get_deconv(self, X, target_layer, feat_map=None): """ Starts the deconvolution process :param X: input image: the data to be deconv-ed :param target_layer: layer in the model up to which we want to be deconvolved :param feat_map: # @TODO: update :returns: deconvolved...
Starts the deconvolution process :param X: input image: the data to be deconv-ed :param target_layer: layer in the model up to which we want to be deconvolved :param feat_map: # @TODO: update :returns: deconvolved image :rtype: numpy array
get_deconv
python
tdeboissiere/DeepLearningImplementations
DeconvNet/KerasDeconv.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/KerasDeconv.py
MIT
def find_top9_mean_act(data, Dec, target_layer, feat_map, batch_size=32): """ Find images with highest mean activation args: data (numpy array) the image data shape : (n_samples, n_channels, img_dim1, img_dim2) Dec (DeconvNet) instance of the DeconvNet class target_layer...
Find images with highest mean activation args: data (numpy array) the image data shape : (n_samples, n_channels, img_dim1, img_dim2) Dec (DeconvNet) instance of the DeconvNet class target_layer (str) Layer name we want to visualise feat_map (int) index of the fi...
find_top9_mean_act
python
tdeboissiere/DeepLearningImplementations
DeconvNet/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/utils.py
MIT
def get_deconv_images(d_act_path, d_deconv_path, data, Dec): """ Deconvolve images specified in d_act. Then pickle these images for future use args: d_act_path (str) path to the dict that for each target layer and for a selection of feature maps, holds the index ...
Deconvolve images specified in d_act. Then pickle these images for future use args: d_act_path (str) path to the dict that for each target layer and for a selection of feature maps, holds the index of the top9 images activating said feature maps ...
get_deconv_images
python
tdeboissiere/DeepLearningImplementations
DeconvNet/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/utils.py
MIT
def format_array(arr): """ Utility to format array for tiled plot args: arr (numpy array) shape : (n_samples, n_channels, img_dim1, img_dim2) """ n_channels = arr.shape[1] len_arr = arr.shape[0] assert (n_channels == 1 or n_channels == 3), "n_channels should be 1 (Greyscale) or ...
Utility to format array for tiled plot args: arr (numpy array) shape : (n_samples, n_channels, img_dim1, img_dim2)
format_array
python
tdeboissiere/DeepLearningImplementations
DeconvNet/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/utils.py
MIT
def scale_to_unit_interval(ndar, eps=1e-8): """ Scales all values in the ndarray ndar to be between 0 and 1 """ ndar = ndar.copy() ndar -= ndar.min() ndar *= 1.0 / (ndar.max() + eps) return ndar
Scales all values in the ndarray ndar to be between 0 and 1
scale_to_unit_interval
python
tdeboissiere/DeepLearningImplementations
DeconvNet/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/utils.py
MIT
def tile_raster_images(X, img_shape, tile_shape, tile_spacing=(0, 0), scale_rows_to_unit_interval=True, output_pixel_vals=True): """ Transform an array with one flattened image per row, into an array in which images are reshaped and layed out like tiles on a flo...
Transform an array with one flattened image per row, into an array in which images are reshaped and layed out like tiles on a floor. This function is useful for visualizing datasets whose rows are images, and also columns of matrices for transforming those rows (such as the first layer of a neural...
tile_raster_images
python
tdeboissiere/DeepLearningImplementations
DeconvNet/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/utils.py
MIT
def plot_max_activation(d_act_path, d_deconv_path, data, target_layer, save=False): """ Plot original images (or cropped versions) and the deconvolution result for images specified in d_act_path / d_dedeconv_path args: d_act_path (str) path to the dict that for each target layer ...
Plot original images (or cropped versions) and the deconvolution result for images specified in d_act_path / d_dedeconv_path args: d_act_path (str) path to the dict that for each target layer and for a selection of feature maps, holds the index of the top9 im...
plot_max_activation
python
tdeboissiere/DeepLearningImplementations
DeconvNet/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/utils.py
MIT
def plot_deconv(img_index, data, Dec, target_layer, feat_map, save=False): """ Plot original images (or cropped versions) and the deconvolution result for images specified in img_index, for the target layer and feat_map specified in the arguments args: img_index (list/arr) array or list of index. ...
Plot original images (or cropped versions) and the deconvolution result for images specified in img_index, for the target layer and feat_map specified in the arguments args: img_index (list/arr) array or list of index. These are the indices of the images we want to plo...
plot_deconv
python
tdeboissiere/DeepLearningImplementations
DeconvNet/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/utils.py
MIT
def VGG_16(weights_path=None): """ VGG Model Keras specification args: weights_path (str) trained weights file path returns model (Keras model) """ model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=(3, 224, 224))) model.add(Conv2D(64, (3, 3), activation='relu')) mod...
VGG Model Keras specification args: weights_path (str) trained weights file path returns model (Keras model)
VGG_16
python
tdeboissiere/DeepLearningImplementations
DeconvNet/VGG_deconv.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/VGG_deconv.py
MIT
def load_model(weights_path): """ Load and compile VGG model args: weights_path (str) trained weights file path returns model (Keras model) """ model = VGG_16(weights_path) model.compile(optimizer="sgd", loss='categorical_crossentropy') return model
Load and compile VGG model args: weights_path (str) trained weights file path returns model (Keras model)
load_model
python
tdeboissiere/DeepLearningImplementations
DeconvNet/VGG_deconv.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DeconvNet/VGG_deconv.py
MIT
def conv_factory(x, concat_axis, nb_filter, dropout_rate=None, weight_decay=1E-4): """Apply BatchNorm, Relu 3x3Conv2D, optional dropout :param x: Input keras network :param concat_axis: int -- index of contatenate axis :param nb_filter: int -- number of filters :param dropout_rate:...
Apply BatchNorm, Relu 3x3Conv2D, optional dropout :param x: Input keras network :param concat_axis: int -- index of contatenate axis :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: keras network with ...
conv_factory
python
tdeboissiere/DeepLearningImplementations
DenseNet/densenet.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DenseNet/densenet.py
MIT
def transition(x, concat_axis, nb_filter, dropout_rate=None, weight_decay=1E-4): """Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_filter: int -- number of filters :param dropout_...
Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: model ...
transition
python
tdeboissiere/DeepLearningImplementations
DenseNet/densenet.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DenseNet/densenet.py
MIT
def denseblock(x, concat_axis, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1E-4): """Build a denseblock where the output of each conv_factory is fed to subsequent ones :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_layer...
Build a denseblock where the output of each conv_factory is fed to subsequent ones :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_layers: int -- the number of layers of conv_ factory to append to the model. :param nb_filter: int -- numb...
denseblock
python
tdeboissiere/DeepLearningImplementations
DenseNet/densenet.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DenseNet/densenet.py
MIT
def denseblock_altern(x, concat_axis, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1E-4): """Build a denseblock where the output of each conv_factory is fed to subsequent ones. (Alternative of a above) :param x: keras model :param concat_axis: int -- index...
Build a denseblock where the output of each conv_factory is fed to subsequent ones. (Alternative of a above) :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_layers: int -- the number of layers of conv_ factory to append to the model. :pa...
denseblock_altern
python
tdeboissiere/DeepLearningImplementations
DenseNet/densenet.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DenseNet/densenet.py
MIT
def DenseNet(nb_classes, img_dim, depth, nb_dense_block, growth_rate, nb_filter, dropout_rate=None, weight_decay=1E-4): """ Build the DenseNet model :param nb_classes: int -- number of classes :param img_dim: tuple -- (channels, rows, columns) :param depth: int -- how many layers :para...
Build the DenseNet model :param nb_classes: int -- number of classes :param img_dim: tuple -- (channels, rows, columns) :param depth: int -- how many layers :param nb_dense_block: int -- number of dense blocks to add to end :param growth_rate: int -- number of filters to add :param nb_filter: ...
DenseNet
python
tdeboissiere/DeepLearningImplementations
DenseNet/densenet.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DenseNet/densenet.py
MIT
def run_cifar10(batch_size, nb_epoch, depth, nb_dense_block, nb_filter, growth_rate, dropout_rate, learning_rate, weight_decay, plot_architecture): """ Run CIFAR10 experime...
Run CIFAR10 experiments :param batch_size: int -- batch size :param nb_epoch: int -- number of training epochs :param depth: int -- network depth :param nb_dense_block: int -- number of dense blocks :param nb_filter: int -- initial number of conv filter :param growth_rate: int -- number of new...
run_cifar10
python
tdeboissiere/DeepLearningImplementations
DenseNet/run_cifar10.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/DenseNet/run_cifar10.py
MIT
def train(model_name, **kwargs): """ Train model args: model_name (str, keras model name) **kwargs (dict) keyword arguments that specify the model hyperparameters """ # Roll out the parameters batch_size = kwargs["batch_size"] nb_epoch = kwargs["nb_epoch"] dataset = kwargs["d...
Train model args: model_name (str, keras model name) **kwargs (dict) keyword arguments that specify the model hyperparameters
train
python
tdeboissiere/DeepLearningImplementations
Eve/train.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Eve/train.py
MIT
def generator_upsampling(noise_dim, img_dim, bn_mode, model_name="generator_upsampling", dset="mnist"): """ Generator model of the DCGAN args : img_dim (tuple of int) num_chan, height, width pretr_weights_file (str) file holding pre trained weights returns : model (keras NN) the Neural Net ...
Generator model of the DCGAN args : img_dim (tuple of int) num_chan, height, width pretr_weights_file (str) file holding pre trained weights returns : model (keras NN) the Neural Net model
generator_upsampling
python
tdeboissiere/DeepLearningImplementations
GAN/src/model/models_GAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/GAN/src/model/models_GAN.py
MIT
def generator_deconv(noise_dim, img_dim, bn_mode, batch_size, model_name="generator_deconv", dset="mnist"): """ Generator model of the DCGAN args : nb_classes (int) number of classes img_dim (tuple of int) num_chan, height, width pretr_weights_file (str) file holding pre trained weigh...
Generator model of the DCGAN args : nb_classes (int) number of classes img_dim (tuple of int) num_chan, height, width pretr_weights_file (str) file holding pre trained weights returns : model (keras NN) the Neural Net model
generator_deconv
python
tdeboissiere/DeepLearningImplementations
GAN/src/model/models_GAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/GAN/src/model/models_GAN.py
MIT
def DCGAN_discriminator(noise_dim, img_dim, bn_mode, model_name="DCGAN_discriminator", dset="mnist", use_mbd=False): """ Discriminator model of the DCGAN args : img_dim (tuple of int) num_chan, height, width pretr_weights_file (str) file holding pre trained weights returns : model (keras NN...
Discriminator model of the DCGAN args : img_dim (tuple of int) num_chan, height, width pretr_weights_file (str) file holding pre trained weights returns : model (keras NN) the Neural Net model
DCGAN_discriminator
python
tdeboissiere/DeepLearningImplementations
GAN/src/model/models_GAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/GAN/src/model/models_GAN.py
MIT
def train(**kwargs): """ Train model Load the whole train data in memory for faster operations args: **kwargs (dict) keyword arguments that specify the model hyperparameters """ # Roll out the parameters batch_size = kwargs["batch_size"] n_batch_per_epoch = kwargs["n_batch_per_epoch"]...
Train model Load the whole train data in memory for faster operations args: **kwargs (dict) keyword arguments that specify the model hyperparameters
train
python
tdeboissiere/DeepLearningImplementations
GAN/src/model/train_GAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/GAN/src/model/train_GAN.py
MIT
def save_image(data, data_format, e): """Saves a picture showing the current progress of the model""" X_G, X_real = data Xg = X_G[:8] Xr = X_real[:8] if data_format == "NHWC": X = np.concatenate((Xg, Xr), axis=0) list_rows = [] for i in range(int(X.shape[0] / 4)): ...
Saves a picture showing the current progress of the model
save_image
python
tdeboissiere/DeepLearningImplementations
GAN_tf/src/utils/visualization_utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/GAN_tf/src/utils/visualization_utils.py
MIT
def cdgmm(A, B, jit=True, inplace=False): """This function uses the C-wrapper to use cuBLAS. """ A, B = A.contiguous(), B.contiguous() if A.size()[-3:] != B.size(): raise RuntimeError('The filters are not compatible for multiplication!') if not iscomplex(A) or not iscomplex(B): ...
This function uses the C-wrapper to use cuBLAS.
cdgmm
python
tdeboissiere/DeepLearningImplementations
ScatteringTransform/test/utils_pytorch.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/ScatteringTransform/test/utils_pytorch.py
MIT
def alpha_dropout(input, p=0.5, training=False): """Applies alpha dropout to the input. See :class:`~torch.nn.AlphaDropout` for details. Args: p (float, optional): the drop probability training (bool, optional): switch between training and evaluation mode """ if p < 0 or p > 1: ...
Applies alpha dropout to the input. See :class:`~torch.nn.AlphaDropout` for details. Args: p (float, optional): the drop probability training (bool, optional): switch between training and evaluation mode
alpha_dropout
python
tdeboissiere/DeepLearningImplementations
SELU/models.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/SELU/models.py
MIT
def train(args): """Train NN for eye tracking regression Args: args: CLI arguments """ # Setup experiment ID exp_ID = "%s_depth_%s_opt_%s_drop_%s_bn_%s" % (args.model, args.n_inner_layers + 2, ...
Train NN for eye tracking regression Args: args: CLI arguments
train
python
tdeboissiere/DeepLearningImplementations
SELU/train.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/SELU/train.py
MIT
def standard_train(args, input_var, network, tang_output): """Train a network normally, output the network, a function to make predictions and training losses""" # Create data X = utils.create_dataset(args.npts) # Create a list of batches (a list of batch idxs splitting X in batches of size batch_size...
Train a network normally, output the network, a function to make predictions and training losses
standard_train
python
tdeboissiere/DeepLearningImplementations
Sobolev/sobolev_training.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Sobolev/sobolev_training.py
MIT
def sobolev_train(args, input_var, network, tang_output): """Train a network with Sobolev, output the network, a function to make predictions and training losses""" # Create data X = utils.create_dataset(args.npts) # Create a list of batches (a list of batch idxs splitting X in batches of size batch_s...
Train a network with Sobolev, output the network, a function to make predictions and training losses
sobolev_train
python
tdeboissiere/DeepLearningImplementations
Sobolev/sobolev_training.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Sobolev/sobolev_training.py
MIT
def get_list_batches(npts, batch_size): """Create batches (i.e a list of index) such that an array of size npts is split in batches of size batch_size""" num_elem = npts num_batches = num_elem / batch_size # list_batches is a list of array. Each array contains the indeces of the batch elements. ...
Create batches (i.e a list of index) such that an array of size npts is split in batches of size batch_size
get_list_batches
python
tdeboissiere/DeepLearningImplementations
Sobolev/utils.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/Sobolev/utils.py
MIT
def generator_toy(noise_dim, model_name="generator_toy"): """ Simple MLP generator for the MoG unrolled GAN toy experiment """ gen_input = Input(shape=noise_dim, name="generator_input") x = Dense(128)(gen_input) x = Activation("tanh")(x) x = Dense(128)(x) x = Activation("tanh")(x) ...
Simple MLP generator for the MoG unrolled GAN toy experiment
generator_toy
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/models_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/models_WGAN.py
MIT
def discriminator_toy(model_name="discriminator_toy"): """ Simple MLP discriminator for the MoG unrolled GAN toy experiment """ disc_input = Input(shape=(2,), name="discriminator_input") x = Dense(128)(disc_input) x = Activation("tanh")(x) x = Dense(128)(x) x = Activation("tanh")(x) ...
Simple MLP discriminator for the MoG unrolled GAN toy experiment
discriminator_toy
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/models_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/models_WGAN.py
MIT
def GAN_toy(generator, discriminator, noise_dim): """ Simple GAN genrator + discriminator for the MoG unrolled GAN toy experiment """ gen_input = Input(shape=noise_dim, name="noise_input") generated_sample = generator(gen_input) GAN_output = discriminator(generated_sample) GAN_toy = Model(...
Simple GAN genrator + discriminator for the MoG unrolled GAN toy experiment
GAN_toy
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/models_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/models_WGAN.py
MIT
def generator_upsampling(noise_dim, img_dim, bn_mode, model_name="generator_upsampling", dset="mnist"): """DCGAN generator based on Upsampling and Conv2D Args: noise_dim: Dimension of the noise input img_dim: dimension of the image output bn_mode: keras batchnorm mode model_name...
DCGAN generator based on Upsampling and Conv2D Args: noise_dim: Dimension of the noise input img_dim: dimension of the image output bn_mode: keras batchnorm mode model_name: model name (default: {"generator_upsampling"}) dset: dataset (default: {"mnist"}) Returns: ...
generator_upsampling
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/models_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/models_WGAN.py
MIT
def generator_deconv(noise_dim, img_dim, bn_mode, batch_size, model_name="generator_deconv", dset="mnist"): """DCGAN generator based on Deconv2D Args: noise_dim: Dimension of the noise input img_dim: dimension of the image output bn_mode: keras batchnorm mode batch_size: needed ...
DCGAN generator based on Deconv2D Args: noise_dim: Dimension of the noise input img_dim: dimension of the image output bn_mode: keras batchnorm mode batch_size: needed to reshape after the deconv2D model_name: model name (default: {"generator_deconv"}) dset: dataset ...
generator_deconv
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/models_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/models_WGAN.py
MIT
def discriminator(img_dim, bn_mode, model_name="discriminator"): """DCGAN discriminator Args: img_dim: dimension of the image output bn_mode: keras batchnorm mode model_name: model name (default: {"generator_deconv"}) Returns: keras model """ if K.image_dim_orderin...
DCGAN discriminator Args: img_dim: dimension of the image output bn_mode: keras batchnorm mode model_name: model name (default: {"generator_deconv"}) Returns: keras model
discriminator
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/models_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/models_WGAN.py
MIT
def DCGAN(generator, discriminator, noise_dim, img_dim): """DCGAN generator + discriminator model Args: generator: keras generator model discriminator: keras discriminator model noise_dim: generator input noise dimension img_dim: real image data dimension Returns: k...
DCGAN generator + discriminator model Args: generator: keras generator model discriminator: keras discriminator model noise_dim: generator input noise dimension img_dim: real image data dimension Returns: keras model
DCGAN
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/models_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/models_WGAN.py
MIT
def train(**kwargs): """ Train standard DCGAN model args: **kwargs (dict) keyword arguments that specify the model hyperparameters """ # Roll out the parameters generator = kwargs["generator"] dset = kwargs["dset"] img_dim = kwargs["img_dim"] nb_epoch = kwargs["nb_epoch"] batch...
Train standard DCGAN model args: **kwargs (dict) keyword arguments that specify the model hyperparameters
train
python
tdeboissiere/DeepLearningImplementations
WassersteinGAN/src/model/train_WGAN.py
https://github.com/tdeboissiere/DeepLearningImplementations/blob/master/WassersteinGAN/src/model/train_WGAN.py
MIT
def infer(self, model_input, frame=None): """Schedule current model input to infer, return last result""" next_req_id = next(self._req_ids) self.model.async_infer(model_input, next_req_id) last_frame = self._frames[0] if self._frames else frame self._frames.append(frame) ...
Schedule current model input to infer, return last result
infer
python
openvinotoolkit/open_model_zoo
demos/action_recognition_demo/python/action_recognition_demo/models.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/action_recognition_demo/python/action_recognition_demo/models.py
Apache-2.0
def fill_area(image, bottom_left, top_right, color=(0, 0, 0), alpha=1.): """Fills area with the specified color""" xmin, ymax = bottom_left xmax, ymin = top_right image[ymin:ymax, xmin:xmax, :] = image[ymin:ymax, xmin:xmax, :] * (1 - alpha) + np.asarray(color) * alpha return image
Fills area with the specified color
fill_area
python
openvinotoolkit/open_model_zoo
demos/action_recognition_demo/python/action_recognition_demo/result_renderer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/action_recognition_demo/python/action_recognition_demo/result_renderer.py
Apache-2.0
def decode_output(probs, labels, top_k=None, label_postprocessing=None): """Decodes top probabilities into corresponding label names""" top_ind = np.argsort(probs)[::-1][:top_k] if label_postprocessing: for k in range(top_k): label_postprocessing[k].update(top_ind[k]) top_ind =...
Decodes top probabilities into corresponding label names
decode_output
python
openvinotoolkit/open_model_zoo
demos/action_recognition_demo/python/action_recognition_demo/result_renderer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/action_recognition_demo/python/action_recognition_demo/result_renderer.py
Apache-2.0
def softmax(x, axis=None): """Normalizes logits to get confidence values along specified axis""" exp = np.exp(x) return exp / np.sum(exp, axis=axis)
Normalizes logits to get confidence values along specified axis
softmax
python
openvinotoolkit/open_model_zoo
demos/action_recognition_demo/python/action_recognition_demo/steps.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/action_recognition_demo/python/action_recognition_demo/steps.py
Apache-2.0
def __init__(self): ''' An abstract Model Adapter constructor. Reads the model from disk or other place. '''
An abstract Model Adapter constructor. Reads the model from disk or other place.
__init__
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/model_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/model_adapter.py
Apache-2.0
def load_model(self): ''' Loads the model on the device. '''
Loads the model on the device.
load_model
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/model_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/model_adapter.py
Apache-2.0
def get_input_layers(self): ''' Gets the names of model inputs and for each one creates the Metadata structure, which contains the information about the input shape, layout, precision in OpenVINO format, meta (optional) Returns: - the dict containing Metadata f...
Gets the names of model inputs and for each one creates the Metadata structure, which contains the information about the input shape, layout, precision in OpenVINO format, meta (optional) Returns: - the dict containing Metadata for all inputs
get_input_layers
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/model_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/model_adapter.py
Apache-2.0
def get_output_layers(self): ''' Gets the names of model outputs and for each one creates the Metadata structure, which contains the information about the output shape, layout, precision in OpenVINO format, meta (optional) Returns: - the dict containing Metadat...
Gets the names of model outputs and for each one creates the Metadata structure, which contains the information about the output shape, layout, precision in OpenVINO format, meta (optional) Returns: - the dict containing Metadata for all outputs
get_output_layers
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/model_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/model_adapter.py
Apache-2.0
def reshape_model(self, new_shape): ''' Reshapes the model inputs to fit the new input shape. Args: - new_shape (dict): the dictionary with inputs names as keys and list of new shape as values in the following format: { 'input_laye...
Reshapes the model inputs to fit the new input shape. Args: - new_shape (dict): the dictionary with inputs names as keys and list of new shape as values in the following format: { 'input_layer_name_1': [1, 128, 128, 3], ...
reshape_model
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/model_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/model_adapter.py
Apache-2.0
def await_all(self): ''' In case of asynchronous execution waits the completion of all busy infer requests. '''
In case of asynchronous execution waits the completion of all busy infer requests.
await_all
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/model_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/model_adapter.py
Apache-2.0
def await_any(self): ''' In case of asynchronous execution waits the completion of any busy infer request until it becomes available for the data submission. '''
In case of asynchronous execution waits the completion of any busy infer request until it becomes available for the data submission.
await_any
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/model_adapter.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/model_adapter.py
Apache-2.0
def from_user_layouts(input_names: set, user_layouts: dict): ''' Create Layout for input based on user info ''' for input_name in input_names: if input_name in user_layouts: return user_layouts[input_name] return user_layouts.get('', '')
Create Layout for input based on user info
from_user_layouts
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/utils.py
Apache-2.0
def parse_layouts(layout_string: str) -> Optional[dict]: ''' Parse layout parameter in format "input0:NCHW,input1:NC" or "NCHW" (applied to all inputs) ''' if not layout_string: return None search_string = layout_string if layout_string.rfind(':') != -1 else ":" + lay...
Parse layout parameter in format "input0:NCHW,input1:NC" or "NCHW" (applied to all inputs)
parse_layouts
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/adapters/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/adapters/utils.py
Apache-2.0
def get_proposals(self, rpn_cls_prob_reshape, bbox_deltas, image_size, _feat_stride=16): """ Parameters rpn_cls_prob_reshape: (H , W , Ax2), probabilities for predicted regions bbox_deltas: (H , W , Ax4), predicted regions image_size: a list of [image_height, image_width] ...
Parameters rpn_cls_prob_reshape: (H , W , Ax2), probabilities for predicted regions bbox_deltas: (H , W , Ax4), predicted regions image_size: a list of [image_height, image_width] _feat_stride: the downsampling ratio of feature map to the original input image Algorithm: ...
get_proposals
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/ctpn.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/ctpn.py
Apache-2.0
def __init__(self, model_adapter, configuration=None, preload=False): '''Detection Model constructor It extends the `ImageModel` construtor. Args: model_adapter (ModelAdapter): allows working with the specified executor configuration (dict, optional): it contains values...
Detection Model constructor It extends the `ImageModel` construtor. Args: model_adapter (ModelAdapter): allows working with the specified executor configuration (dict, optional): it contains values for parameters accepted by specific wrapper (`confidence_threshold...
__init__
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/detection_model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/detection_model.py
Apache-2.0
def _resize_detections(self, detections, meta): '''Resizes detection bounding boxes according to initial image shape. It implements image resizing depending on the set `resize_type`(see `ImageModel` for details). Next, it applies bounding boxes clipping. Args: detections (L...
Resizes detection bounding boxes according to initial image shape. It implements image resizing depending on the set `resize_type`(see `ImageModel` for details). Next, it applies bounding boxes clipping. Args: detections (List[Detection]): list of detections with coordinates in nor...
_resize_detections
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/detection_model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/detection_model.py
Apache-2.0
def __init__(self, model_adapter, configuration=None, preload=False): '''Image model constructor It extends the `Model` constructor. Args: model_adapter (ModelAdapter): allows working with the specified executor configuration (dict, optional): it contains values for par...
Image model constructor It extends the `Model` constructor. Args: model_adapter (ModelAdapter): allows working with the specified executor configuration (dict, optional): it contains values for parameters accepted by specific wrapper (`confidence_threshold`, `labe...
__init__
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/image_model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/image_model.py
Apache-2.0
def _get_inputs(self): '''Defines the model inputs for images and additional info. Raises: WrapperError: if the wrapper failed to define appropriate inputs for images Returns: - list of inputs names for images - list of inputs names for additional info ...
Defines the model inputs for images and additional info. Raises: WrapperError: if the wrapper failed to define appropriate inputs for images Returns: - list of inputs names for images - list of inputs names for additional info
_get_inputs
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/image_model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/image_model.py
Apache-2.0
def preprocess(self, inputs): '''Data preprocess method It performs basic preprocessing of a single image: - Resizes the image to fit the model input size via the defined resize type - Normalizes the image: subtracts means, divides by scales, switch channels BGR-RGB ...
Data preprocess method It performs basic preprocessing of a single image: - Resizes the image to fit the model input size via the defined resize type - Normalizes the image: subtracts means, divides by scales, switch channels BGR-RGB - Changes the image layout according to t...
preprocess
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/image_model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/image_model.py
Apache-2.0
def _change_layout(self, image): '''Changes the input image layout to fit the layout of the model input layer. Args: inputs (ndarray): a single image as 3D array in HWC layout Returns: - the image with layout aligned with the model layout ''' if self.nch...
Changes the input image layout to fit the layout of the model input layer. Args: inputs (ndarray): a single image as 3D array in HWC layout Returns: - the image with layout aligned with the model layout
_change_layout
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/image_model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/image_model.py
Apache-2.0