id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,400 | apache/incubator-mxnet | python/mxnet/image/image.py | color_normalize | def color_normalize(src, mean, std=None):
"""Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
NDArray
An `NDArray` containing the normalized image.
"""
if mean is not None:
src -= mean
if std is not None:
src /= std
return src | python | def color_normalize(src, mean, std=None):
"""Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
NDArray
An `NDArray` containing the normalized image.
"""
if mean is not None:
src -= mean
if std is not None:
src /= std
return src | [
"def",
"color_normalize",
"(",
"src",
",",
"mean",
",",
"std",
"=",
"None",
")",
":",
"if",
"mean",
"is",
"not",
"None",
":",
"src",
"-=",
"mean",
"if",
"std",
"is",
"not",
"None",
":",
"src",
"/=",
"std",
"return",
"src"
] | Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
NDArray
An `NDArray` containing the normalized image. | [
"Normalize",
"src",
"with",
"mean",
"and",
"std",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L526-L547 |
23,401 | apache/incubator-mxnet | python/mxnet/image/image.py | random_size_crop | def random_size_crop(src, size, area, ratio, interp=2, **kwargs):
"""Randomly crop src with size. Randomize area and aspect ratio.
Parameters
----------
src : NDArray
Input image
size : tuple of (int, int)
Size of the crop formatted as (width, height).
area : float in (0, 1] or tuple of (float, float)
If tuple, minimum area and maximum area to be maintained after cropping
If float, minimum area to be maintained after cropping, maximum area is set to 1.0
ratio : tuple of (float, float)
Aspect ratio range as (min_aspect_ratio, max_aspect_ratio)
interp: int, optional, default=2
Interpolation method. See resize_short for details.
Returns
-------
NDArray
An `NDArray` containing the cropped image.
Tuple
A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the
original image and (width, height) are the dimensions of the cropped image.
"""
h, w, _ = src.shape
src_area = h * w
if 'min_area' in kwargs:
warnings.warn('`min_area` is deprecated. Please use `area` instead.',
DeprecationWarning)
area = kwargs.pop('min_area')
assert not kwargs, "unexpected keyword arguments for `random_size_crop`."
if isinstance(area, numeric_types):
area = (area, 1.0)
for _ in range(10):
target_area = random.uniform(area[0], area[1]) * src_area
log_ratio = (np.log(ratio[0]), np.log(ratio[1]))
new_ratio = np.exp(random.uniform(*log_ratio))
new_w = int(round(np.sqrt(target_area * new_ratio)))
new_h = int(round(np.sqrt(target_area / new_ratio)))
if new_w <= w and new_h <= h:
x0 = random.randint(0, w - new_w)
y0 = random.randint(0, h - new_h)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
# fall back to center_crop
return center_crop(src, size, interp) | python | def random_size_crop(src, size, area, ratio, interp=2, **kwargs):
"""Randomly crop src with size. Randomize area and aspect ratio.
Parameters
----------
src : NDArray
Input image
size : tuple of (int, int)
Size of the crop formatted as (width, height).
area : float in (0, 1] or tuple of (float, float)
If tuple, minimum area and maximum area to be maintained after cropping
If float, minimum area to be maintained after cropping, maximum area is set to 1.0
ratio : tuple of (float, float)
Aspect ratio range as (min_aspect_ratio, max_aspect_ratio)
interp: int, optional, default=2
Interpolation method. See resize_short for details.
Returns
-------
NDArray
An `NDArray` containing the cropped image.
Tuple
A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the
original image and (width, height) are the dimensions of the cropped image.
"""
h, w, _ = src.shape
src_area = h * w
if 'min_area' in kwargs:
warnings.warn('`min_area` is deprecated. Please use `area` instead.',
DeprecationWarning)
area = kwargs.pop('min_area')
assert not kwargs, "unexpected keyword arguments for `random_size_crop`."
if isinstance(area, numeric_types):
area = (area, 1.0)
for _ in range(10):
target_area = random.uniform(area[0], area[1]) * src_area
log_ratio = (np.log(ratio[0]), np.log(ratio[1]))
new_ratio = np.exp(random.uniform(*log_ratio))
new_w = int(round(np.sqrt(target_area * new_ratio)))
new_h = int(round(np.sqrt(target_area / new_ratio)))
if new_w <= w and new_h <= h:
x0 = random.randint(0, w - new_w)
y0 = random.randint(0, h - new_h)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
# fall back to center_crop
return center_crop(src, size, interp) | [
"def",
"random_size_crop",
"(",
"src",
",",
"size",
",",
"area",
",",
"ratio",
",",
"interp",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"h",
",",
"w",
",",
"_",
"=",
"src",
".",
"shape",
"src_area",
"=",
"h",
"*",
"w",
"if",
"'min_area'",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"'`min_area` is deprecated. Please use `area` instead.'",
",",
"DeprecationWarning",
")",
"area",
"=",
"kwargs",
".",
"pop",
"(",
"'min_area'",
")",
"assert",
"not",
"kwargs",
",",
"\"unexpected keyword arguments for `random_size_crop`.\"",
"if",
"isinstance",
"(",
"area",
",",
"numeric_types",
")",
":",
"area",
"=",
"(",
"area",
",",
"1.0",
")",
"for",
"_",
"in",
"range",
"(",
"10",
")",
":",
"target_area",
"=",
"random",
".",
"uniform",
"(",
"area",
"[",
"0",
"]",
",",
"area",
"[",
"1",
"]",
")",
"*",
"src_area",
"log_ratio",
"=",
"(",
"np",
".",
"log",
"(",
"ratio",
"[",
"0",
"]",
")",
",",
"np",
".",
"log",
"(",
"ratio",
"[",
"1",
"]",
")",
")",
"new_ratio",
"=",
"np",
".",
"exp",
"(",
"random",
".",
"uniform",
"(",
"*",
"log_ratio",
")",
")",
"new_w",
"=",
"int",
"(",
"round",
"(",
"np",
".",
"sqrt",
"(",
"target_area",
"*",
"new_ratio",
")",
")",
")",
"new_h",
"=",
"int",
"(",
"round",
"(",
"np",
".",
"sqrt",
"(",
"target_area",
"/",
"new_ratio",
")",
")",
")",
"if",
"new_w",
"<=",
"w",
"and",
"new_h",
"<=",
"h",
":",
"x0",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"w",
"-",
"new_w",
")",
"y0",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"h",
"-",
"new_h",
")",
"out",
"=",
"fixed_crop",
"(",
"src",
",",
"x0",
",",
"y0",
",",
"new_w",
",",
"new_h",
",",
"size",
",",
"interp",
")",
"return",
"out",
",",
"(",
"x0",
",",
"y0",
",",
"new_w",
",",
"new_h",
")",
"# fall back to center_crop",
"return",
"center_crop",
"(",
"src",
",",
"size",
",",
"interp",
")"
] | Randomly crop src with size. Randomize area and aspect ratio.
Parameters
----------
src : NDArray
Input image
size : tuple of (int, int)
Size of the crop formatted as (width, height).
area : float in (0, 1] or tuple of (float, float)
If tuple, minimum area and maximum area to be maintained after cropping
If float, minimum area to be maintained after cropping, maximum area is set to 1.0
ratio : tuple of (float, float)
Aspect ratio range as (min_aspect_ratio, max_aspect_ratio)
interp: int, optional, default=2
Interpolation method. See resize_short for details.
Returns
-------
NDArray
An `NDArray` containing the cropped image.
Tuple
A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the
original image and (width, height) are the dimensions of the cropped image. | [
"Randomly",
"crop",
"src",
"with",
"size",
".",
"Randomize",
"area",
"and",
"aspect",
"ratio",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L550-L602 |
23,402 | apache/incubator-mxnet | python/mxnet/image/image.py | CreateAugmenter | def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False,
mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0,
pca_noise=0, rand_gray=0, inter_method=2):
"""Creates an augmenter list.
Parameters
----------
data_shape : tuple of int
Shape for output data
resize : int
Resize shorter edge if larger than 0 at the begining
rand_crop : bool
Whether to enable random cropping other than center crop
rand_resize : bool
Whether to enable random sized cropping, require rand_crop to be enabled
rand_gray : float
[0, 1], probability to convert to grayscale for all channels, the number
of channels will not be reduced to 1
rand_mirror : bool
Whether to apply horizontal flip to image with probability 0.5
mean : np.ndarray or None
Mean pixel values for [r, g, b]
std : np.ndarray or None
Standard deviations for [r, g, b]
brightness : float
Brightness jittering range (percent)
contrast : float
Contrast jittering range (percent)
saturation : float
Saturation jittering range (percent)
hue : float
Hue jittering range (percent)
pca_noise : float
Pca noise level (percent)
inter_method : int, default=2(Area-based)
Interpolation method for all resizing operations
Possible values:
0: Nearest Neighbors Interpolation.
1: Bilinear interpolation.
2: Area-based (resampling using pixel area relation). It may be a
preferred method for image decimation, as it gives moire-free
results. But when the image is zoomed, it is similar to the Nearest
Neighbors method. (used by default).
3: Bicubic interpolation over 4x4 pixel neighborhood.
4: Lanczos interpolation over 8x8 pixel neighborhood.
9: Cubic for enlarge, area for shrink, bilinear for others
10: Random select from interpolation method metioned above.
Note:
When shrinking an image, it will generally look best with AREA-based
interpolation, whereas, when enlarging an image, it will generally look best
with Bicubic (slow) or Bilinear (faster but still looks OK).
Examples
--------
>>> # An example of creating multiple augmenters
>>> augs = mx.image.CreateAugmenter(data_shape=(3, 300, 300), rand_mirror=True,
... mean=True, brightness=0.125, contrast=0.125, rand_gray=0.05,
... saturation=0.125, pca_noise=0.05, inter_method=10)
>>> # dump the details
>>> for aug in augs:
... aug.dumps()
"""
auglist = []
if resize > 0:
auglist.append(ResizeAug(resize, inter_method))
crop_size = (data_shape[2], data_shape[1])
if rand_resize:
assert rand_crop
auglist.append(RandomSizedCropAug(crop_size, 0.08, (3.0 / 4.0, 4.0 / 3.0), inter_method))
elif rand_crop:
auglist.append(RandomCropAug(crop_size, inter_method))
else:
auglist.append(CenterCropAug(crop_size, inter_method))
if rand_mirror:
auglist.append(HorizontalFlipAug(0.5))
auglist.append(CastAug())
if brightness or contrast or saturation:
auglist.append(ColorJitterAug(brightness, contrast, saturation))
if hue:
auglist.append(HueJitterAug(hue))
if pca_noise > 0:
eigval = np.array([55.46, 4.794, 1.148])
eigvec = np.array([[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]])
auglist.append(LightingAug(pca_noise, eigval, eigvec))
if rand_gray > 0:
auglist.append(RandomGrayAug(rand_gray))
if mean is True:
mean = nd.array([123.68, 116.28, 103.53])
elif mean is not None:
assert isinstance(mean, (np.ndarray, nd.NDArray)) and mean.shape[0] in [1, 3]
if std is True:
std = nd.array([58.395, 57.12, 57.375])
elif std is not None:
assert isinstance(std, (np.ndarray, nd.NDArray)) and std.shape[0] in [1, 3]
if mean is not None or std is not None:
auglist.append(ColorNormalizeAug(mean, std))
return auglist | python | def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False,
mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0,
pca_noise=0, rand_gray=0, inter_method=2):
"""Creates an augmenter list.
Parameters
----------
data_shape : tuple of int
Shape for output data
resize : int
Resize shorter edge if larger than 0 at the begining
rand_crop : bool
Whether to enable random cropping other than center crop
rand_resize : bool
Whether to enable random sized cropping, require rand_crop to be enabled
rand_gray : float
[0, 1], probability to convert to grayscale for all channels, the number
of channels will not be reduced to 1
rand_mirror : bool
Whether to apply horizontal flip to image with probability 0.5
mean : np.ndarray or None
Mean pixel values for [r, g, b]
std : np.ndarray or None
Standard deviations for [r, g, b]
brightness : float
Brightness jittering range (percent)
contrast : float
Contrast jittering range (percent)
saturation : float
Saturation jittering range (percent)
hue : float
Hue jittering range (percent)
pca_noise : float
Pca noise level (percent)
inter_method : int, default=2(Area-based)
Interpolation method for all resizing operations
Possible values:
0: Nearest Neighbors Interpolation.
1: Bilinear interpolation.
2: Area-based (resampling using pixel area relation). It may be a
preferred method for image decimation, as it gives moire-free
results. But when the image is zoomed, it is similar to the Nearest
Neighbors method. (used by default).
3: Bicubic interpolation over 4x4 pixel neighborhood.
4: Lanczos interpolation over 8x8 pixel neighborhood.
9: Cubic for enlarge, area for shrink, bilinear for others
10: Random select from interpolation method metioned above.
Note:
When shrinking an image, it will generally look best with AREA-based
interpolation, whereas, when enlarging an image, it will generally look best
with Bicubic (slow) or Bilinear (faster but still looks OK).
Examples
--------
>>> # An example of creating multiple augmenters
>>> augs = mx.image.CreateAugmenter(data_shape=(3, 300, 300), rand_mirror=True,
... mean=True, brightness=0.125, contrast=0.125, rand_gray=0.05,
... saturation=0.125, pca_noise=0.05, inter_method=10)
>>> # dump the details
>>> for aug in augs:
... aug.dumps()
"""
auglist = []
if resize > 0:
auglist.append(ResizeAug(resize, inter_method))
crop_size = (data_shape[2], data_shape[1])
if rand_resize:
assert rand_crop
auglist.append(RandomSizedCropAug(crop_size, 0.08, (3.0 / 4.0, 4.0 / 3.0), inter_method))
elif rand_crop:
auglist.append(RandomCropAug(crop_size, inter_method))
else:
auglist.append(CenterCropAug(crop_size, inter_method))
if rand_mirror:
auglist.append(HorizontalFlipAug(0.5))
auglist.append(CastAug())
if brightness or contrast or saturation:
auglist.append(ColorJitterAug(brightness, contrast, saturation))
if hue:
auglist.append(HueJitterAug(hue))
if pca_noise > 0:
eigval = np.array([55.46, 4.794, 1.148])
eigvec = np.array([[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]])
auglist.append(LightingAug(pca_noise, eigval, eigvec))
if rand_gray > 0:
auglist.append(RandomGrayAug(rand_gray))
if mean is True:
mean = nd.array([123.68, 116.28, 103.53])
elif mean is not None:
assert isinstance(mean, (np.ndarray, nd.NDArray)) and mean.shape[0] in [1, 3]
if std is True:
std = nd.array([58.395, 57.12, 57.375])
elif std is not None:
assert isinstance(std, (np.ndarray, nd.NDArray)) and std.shape[0] in [1, 3]
if mean is not None or std is not None:
auglist.append(ColorNormalizeAug(mean, std))
return auglist | [
"def",
"CreateAugmenter",
"(",
"data_shape",
",",
"resize",
"=",
"0",
",",
"rand_crop",
"=",
"False",
",",
"rand_resize",
"=",
"False",
",",
"rand_mirror",
"=",
"False",
",",
"mean",
"=",
"None",
",",
"std",
"=",
"None",
",",
"brightness",
"=",
"0",
",",
"contrast",
"=",
"0",
",",
"saturation",
"=",
"0",
",",
"hue",
"=",
"0",
",",
"pca_noise",
"=",
"0",
",",
"rand_gray",
"=",
"0",
",",
"inter_method",
"=",
"2",
")",
":",
"auglist",
"=",
"[",
"]",
"if",
"resize",
">",
"0",
":",
"auglist",
".",
"append",
"(",
"ResizeAug",
"(",
"resize",
",",
"inter_method",
")",
")",
"crop_size",
"=",
"(",
"data_shape",
"[",
"2",
"]",
",",
"data_shape",
"[",
"1",
"]",
")",
"if",
"rand_resize",
":",
"assert",
"rand_crop",
"auglist",
".",
"append",
"(",
"RandomSizedCropAug",
"(",
"crop_size",
",",
"0.08",
",",
"(",
"3.0",
"/",
"4.0",
",",
"4.0",
"/",
"3.0",
")",
",",
"inter_method",
")",
")",
"elif",
"rand_crop",
":",
"auglist",
".",
"append",
"(",
"RandomCropAug",
"(",
"crop_size",
",",
"inter_method",
")",
")",
"else",
":",
"auglist",
".",
"append",
"(",
"CenterCropAug",
"(",
"crop_size",
",",
"inter_method",
")",
")",
"if",
"rand_mirror",
":",
"auglist",
".",
"append",
"(",
"HorizontalFlipAug",
"(",
"0.5",
")",
")",
"auglist",
".",
"append",
"(",
"CastAug",
"(",
")",
")",
"if",
"brightness",
"or",
"contrast",
"or",
"saturation",
":",
"auglist",
".",
"append",
"(",
"ColorJitterAug",
"(",
"brightness",
",",
"contrast",
",",
"saturation",
")",
")",
"if",
"hue",
":",
"auglist",
".",
"append",
"(",
"HueJitterAug",
"(",
"hue",
")",
")",
"if",
"pca_noise",
">",
"0",
":",
"eigval",
"=",
"np",
".",
"array",
"(",
"[",
"55.46",
",",
"4.794",
",",
"1.148",
"]",
")",
"eigvec",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"-",
"0.5675",
",",
"0.7192",
",",
"0.4009",
"]",
",",
"[",
"-",
"0.5808",
",",
"-",
"0.0045",
",",
"-",
"0.8140",
"]",
",",
"[",
"-",
"0.5836",
",",
"-",
"0.6948",
",",
"0.4203",
"]",
"]",
")",
"auglist",
".",
"append",
"(",
"LightingAug",
"(",
"pca_noise",
",",
"eigval",
",",
"eigvec",
")",
")",
"if",
"rand_gray",
">",
"0",
":",
"auglist",
".",
"append",
"(",
"RandomGrayAug",
"(",
"rand_gray",
")",
")",
"if",
"mean",
"is",
"True",
":",
"mean",
"=",
"nd",
".",
"array",
"(",
"[",
"123.68",
",",
"116.28",
",",
"103.53",
"]",
")",
"elif",
"mean",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"mean",
",",
"(",
"np",
".",
"ndarray",
",",
"nd",
".",
"NDArray",
")",
")",
"and",
"mean",
".",
"shape",
"[",
"0",
"]",
"in",
"[",
"1",
",",
"3",
"]",
"if",
"std",
"is",
"True",
":",
"std",
"=",
"nd",
".",
"array",
"(",
"[",
"58.395",
",",
"57.12",
",",
"57.375",
"]",
")",
"elif",
"std",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"std",
",",
"(",
"np",
".",
"ndarray",
",",
"nd",
".",
"NDArray",
")",
")",
"and",
"std",
".",
"shape",
"[",
"0",
"]",
"in",
"[",
"1",
",",
"3",
"]",
"if",
"mean",
"is",
"not",
"None",
"or",
"std",
"is",
"not",
"None",
":",
"auglist",
".",
"append",
"(",
"ColorNormalizeAug",
"(",
"mean",
",",
"std",
")",
")",
"return",
"auglist"
] | Creates an augmenter list.
Parameters
----------
data_shape : tuple of int
Shape for output data
resize : int
Resize shorter edge if larger than 0 at the begining
rand_crop : bool
Whether to enable random cropping other than center crop
rand_resize : bool
Whether to enable random sized cropping, require rand_crop to be enabled
rand_gray : float
[0, 1], probability to convert to grayscale for all channels, the number
of channels will not be reduced to 1
rand_mirror : bool
Whether to apply horizontal flip to image with probability 0.5
mean : np.ndarray or None
Mean pixel values for [r, g, b]
std : np.ndarray or None
Standard deviations for [r, g, b]
brightness : float
Brightness jittering range (percent)
contrast : float
Contrast jittering range (percent)
saturation : float
Saturation jittering range (percent)
hue : float
Hue jittering range (percent)
pca_noise : float
Pca noise level (percent)
inter_method : int, default=2(Area-based)
Interpolation method for all resizing operations
Possible values:
0: Nearest Neighbors Interpolation.
1: Bilinear interpolation.
2: Area-based (resampling using pixel area relation). It may be a
preferred method for image decimation, as it gives moire-free
results. But when the image is zoomed, it is similar to the Nearest
Neighbors method. (used by default).
3: Bicubic interpolation over 4x4 pixel neighborhood.
4: Lanczos interpolation over 8x8 pixel neighborhood.
9: Cubic for enlarge, area for shrink, bilinear for others
10: Random select from interpolation method metioned above.
Note:
When shrinking an image, it will generally look best with AREA-based
interpolation, whereas, when enlarging an image, it will generally look best
with Bicubic (slow) or Bilinear (faster but still looks OK).
Examples
--------
>>> # An example of creating multiple augmenters
>>> augs = mx.image.CreateAugmenter(data_shape=(3, 300, 300), rand_mirror=True,
... mean=True, brightness=0.125, contrast=0.125, rand_gray=0.05,
... saturation=0.125, pca_noise=0.05, inter_method=10)
>>> # dump the details
>>> for aug in augs:
... aug.dumps() | [
"Creates",
"an",
"augmenter",
"list",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1015-L1126 |
23,403 | apache/incubator-mxnet | python/mxnet/image/image.py | Augmenter.dumps | def dumps(self):
"""Saves the Augmenter to string
Returns
-------
str
JSON formatted string that describes the Augmenter.
"""
return json.dumps([self.__class__.__name__.lower(), self._kwargs]) | python | def dumps(self):
"""Saves the Augmenter to string
Returns
-------
str
JSON formatted string that describes the Augmenter.
"""
return json.dumps([self.__class__.__name__.lower(), self._kwargs]) | [
"def",
"dumps",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"[",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"self",
".",
"_kwargs",
"]",
")"
] | Saves the Augmenter to string
Returns
-------
str
JSON formatted string that describes the Augmenter. | [
"Saves",
"the",
"Augmenter",
"to",
"string"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L616-L624 |
23,404 | apache/incubator-mxnet | python/mxnet/image/image.py | SequentialAug.dumps | def dumps(self):
"""Override the default to avoid duplicate dump."""
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] | python | def dumps(self):
"""Override the default to avoid duplicate dump."""
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] | [
"def",
"dumps",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"[",
"x",
".",
"dumps",
"(",
")",
"for",
"x",
"in",
"self",
".",
"ts",
"]",
"]"
] | Override the default to avoid duplicate dump. | [
"Override",
"the",
"default",
"to",
"avoid",
"duplicate",
"dump",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L643-L645 |
23,405 | apache/incubator-mxnet | python/mxnet/image/image.py | ImageIter.hard_reset | def hard_reset(self):
"""Resets the iterator and ignore roll over data"""
if self.seq is not None and self.shuffle:
random.shuffle(self.seq)
if self.imgrec is not None:
self.imgrec.reset()
self.cur = 0
self._allow_read = True
self._cache_data = None
self._cache_label = None
self._cache_idx = None | python | def hard_reset(self):
"""Resets the iterator and ignore roll over data"""
if self.seq is not None and self.shuffle:
random.shuffle(self.seq)
if self.imgrec is not None:
self.imgrec.reset()
self.cur = 0
self._allow_read = True
self._cache_data = None
self._cache_label = None
self._cache_idx = None | [
"def",
"hard_reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"seq",
"is",
"not",
"None",
"and",
"self",
".",
"shuffle",
":",
"random",
".",
"shuffle",
"(",
"self",
".",
"seq",
")",
"if",
"self",
".",
"imgrec",
"is",
"not",
"None",
":",
"self",
".",
"imgrec",
".",
"reset",
"(",
")",
"self",
".",
"cur",
"=",
"0",
"self",
".",
"_allow_read",
"=",
"True",
"self",
".",
"_cache_data",
"=",
"None",
"self",
".",
"_cache_label",
"=",
"None",
"self",
".",
"_cache_idx",
"=",
"None"
] | Resets the iterator and ignore roll over data | [
"Resets",
"the",
"iterator",
"and",
"ignore",
"roll",
"over",
"data"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1290-L1300 |
23,406 | apache/incubator-mxnet | python/mxnet/image/image.py | ImageIter.next_sample | def next_sample(self):
"""Helper function for reading in next sample."""
if self._allow_read is False:
raise StopIteration
if self.seq is not None:
if self.cur < self.num_image:
idx = self.seq[self.cur]
else:
if self.last_batch_handle != 'discard':
self.cur = 0
raise StopIteration
self.cur += 1
if self.imgrec is not None:
s = self.imgrec.read_idx(idx)
header, img = recordio.unpack(s)
if self.imglist is None:
return header.label, img
else:
return self.imglist[idx][0], img
else:
label, fname = self.imglist[idx]
return label, self.read_image(fname)
else:
s = self.imgrec.read()
if s is None:
if self.last_batch_handle != 'discard':
self.imgrec.reset()
raise StopIteration
header, img = recordio.unpack(s)
return header.label, img | python | def next_sample(self):
"""Helper function for reading in next sample."""
if self._allow_read is False:
raise StopIteration
if self.seq is not None:
if self.cur < self.num_image:
idx = self.seq[self.cur]
else:
if self.last_batch_handle != 'discard':
self.cur = 0
raise StopIteration
self.cur += 1
if self.imgrec is not None:
s = self.imgrec.read_idx(idx)
header, img = recordio.unpack(s)
if self.imglist is None:
return header.label, img
else:
return self.imglist[idx][0], img
else:
label, fname = self.imglist[idx]
return label, self.read_image(fname)
else:
s = self.imgrec.read()
if s is None:
if self.last_batch_handle != 'discard':
self.imgrec.reset()
raise StopIteration
header, img = recordio.unpack(s)
return header.label, img | [
"def",
"next_sample",
"(",
"self",
")",
":",
"if",
"self",
".",
"_allow_read",
"is",
"False",
":",
"raise",
"StopIteration",
"if",
"self",
".",
"seq",
"is",
"not",
"None",
":",
"if",
"self",
".",
"cur",
"<",
"self",
".",
"num_image",
":",
"idx",
"=",
"self",
".",
"seq",
"[",
"self",
".",
"cur",
"]",
"else",
":",
"if",
"self",
".",
"last_batch_handle",
"!=",
"'discard'",
":",
"self",
".",
"cur",
"=",
"0",
"raise",
"StopIteration",
"self",
".",
"cur",
"+=",
"1",
"if",
"self",
".",
"imgrec",
"is",
"not",
"None",
":",
"s",
"=",
"self",
".",
"imgrec",
".",
"read_idx",
"(",
"idx",
")",
"header",
",",
"img",
"=",
"recordio",
".",
"unpack",
"(",
"s",
")",
"if",
"self",
".",
"imglist",
"is",
"None",
":",
"return",
"header",
".",
"label",
",",
"img",
"else",
":",
"return",
"self",
".",
"imglist",
"[",
"idx",
"]",
"[",
"0",
"]",
",",
"img",
"else",
":",
"label",
",",
"fname",
"=",
"self",
".",
"imglist",
"[",
"idx",
"]",
"return",
"label",
",",
"self",
".",
"read_image",
"(",
"fname",
")",
"else",
":",
"s",
"=",
"self",
".",
"imgrec",
".",
"read",
"(",
")",
"if",
"s",
"is",
"None",
":",
"if",
"self",
".",
"last_batch_handle",
"!=",
"'discard'",
":",
"self",
".",
"imgrec",
".",
"reset",
"(",
")",
"raise",
"StopIteration",
"header",
",",
"img",
"=",
"recordio",
".",
"unpack",
"(",
"s",
")",
"return",
"header",
".",
"label",
",",
"img"
] | Helper function for reading in next sample. | [
"Helper",
"function",
"for",
"reading",
"in",
"next",
"sample",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1302-L1331 |
23,407 | apache/incubator-mxnet | python/mxnet/image/image.py | ImageIter._batchify | def _batchify(self, batch_data, batch_label, start=0):
"""Helper function for batchifying data"""
i = start
batch_size = self.batch_size
try:
while i < batch_size:
label, s = self.next_sample()
data = self.imdecode(s)
try:
self.check_valid_image(data)
except RuntimeError as e:
logging.debug('Invalid image, skipping: %s', str(e))
continue
data = self.augmentation_transform(data)
assert i < batch_size, 'Batch size must be multiples of augmenter output length'
batch_data[i] = self.postprocess_data(data)
batch_label[i] = label
i += 1
except StopIteration:
if not i:
raise StopIteration
return i | python | def _batchify(self, batch_data, batch_label, start=0):
"""Helper function for batchifying data"""
i = start
batch_size = self.batch_size
try:
while i < batch_size:
label, s = self.next_sample()
data = self.imdecode(s)
try:
self.check_valid_image(data)
except RuntimeError as e:
logging.debug('Invalid image, skipping: %s', str(e))
continue
data = self.augmentation_transform(data)
assert i < batch_size, 'Batch size must be multiples of augmenter output length'
batch_data[i] = self.postprocess_data(data)
batch_label[i] = label
i += 1
except StopIteration:
if not i:
raise StopIteration
return i | [
"def",
"_batchify",
"(",
"self",
",",
"batch_data",
",",
"batch_label",
",",
"start",
"=",
"0",
")",
":",
"i",
"=",
"start",
"batch_size",
"=",
"self",
".",
"batch_size",
"try",
":",
"while",
"i",
"<",
"batch_size",
":",
"label",
",",
"s",
"=",
"self",
".",
"next_sample",
"(",
")",
"data",
"=",
"self",
".",
"imdecode",
"(",
"s",
")",
"try",
":",
"self",
".",
"check_valid_image",
"(",
"data",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"logging",
".",
"debug",
"(",
"'Invalid image, skipping: %s'",
",",
"str",
"(",
"e",
")",
")",
"continue",
"data",
"=",
"self",
".",
"augmentation_transform",
"(",
"data",
")",
"assert",
"i",
"<",
"batch_size",
",",
"'Batch size must be multiples of augmenter output length'",
"batch_data",
"[",
"i",
"]",
"=",
"self",
".",
"postprocess_data",
"(",
"data",
")",
"batch_label",
"[",
"i",
"]",
"=",
"label",
"i",
"+=",
"1",
"except",
"StopIteration",
":",
"if",
"not",
"i",
":",
"raise",
"StopIteration",
"return",
"i"
] | Helper function for batchifying data | [
"Helper",
"function",
"for",
"batchifying",
"data"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1333-L1354 |
23,408 | apache/incubator-mxnet | python/mxnet/image/image.py | ImageIter.imdecode | def imdecode(self, s):
"""Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details."""
def locate():
"""Locate the image file/index if decode fails."""
if self.seq is not None:
idx = self.seq[(self.cur % self.num_image) - 1]
else:
idx = (self.cur % self.num_image) - 1
if self.imglist is not None:
_, fname = self.imglist[idx]
msg = "filename: {}".format(fname)
else:
msg = "index: {}".format(idx)
return "Broken image " + msg
try:
img = imdecode(s)
except Exception as e:
raise RuntimeError("{}, {}".format(locate(), e))
return img | python | def imdecode(self, s):
"""Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details."""
def locate():
"""Locate the image file/index if decode fails."""
if self.seq is not None:
idx = self.seq[(self.cur % self.num_image) - 1]
else:
idx = (self.cur % self.num_image) - 1
if self.imglist is not None:
_, fname = self.imglist[idx]
msg = "filename: {}".format(fname)
else:
msg = "index: {}".format(idx)
return "Broken image " + msg
try:
img = imdecode(s)
except Exception as e:
raise RuntimeError("{}, {}".format(locate(), e))
return img | [
"def",
"imdecode",
"(",
"self",
",",
"s",
")",
":",
"def",
"locate",
"(",
")",
":",
"\"\"\"Locate the image file/index if decode fails.\"\"\"",
"if",
"self",
".",
"seq",
"is",
"not",
"None",
":",
"idx",
"=",
"self",
".",
"seq",
"[",
"(",
"self",
".",
"cur",
"%",
"self",
".",
"num_image",
")",
"-",
"1",
"]",
"else",
":",
"idx",
"=",
"(",
"self",
".",
"cur",
"%",
"self",
".",
"num_image",
")",
"-",
"1",
"if",
"self",
".",
"imglist",
"is",
"not",
"None",
":",
"_",
",",
"fname",
"=",
"self",
".",
"imglist",
"[",
"idx",
"]",
"msg",
"=",
"\"filename: {}\"",
".",
"format",
"(",
"fname",
")",
"else",
":",
"msg",
"=",
"\"index: {}\"",
".",
"format",
"(",
"idx",
")",
"return",
"\"Broken image \"",
"+",
"msg",
"try",
":",
"img",
"=",
"imdecode",
"(",
"s",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"RuntimeError",
"(",
"\"{}, {}\"",
".",
"format",
"(",
"locate",
"(",
")",
",",
"e",
")",
")",
"return",
"img"
] | Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details. | [
"Decodes",
"a",
"string",
"or",
"byte",
"string",
"to",
"an",
"NDArray",
".",
"See",
"mx",
".",
"img",
".",
"imdecode",
"for",
"more",
"details",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1409-L1428 |
23,409 | apache/incubator-mxnet | example/gluon/lipnet/utils/common.py | word_to_vector | def word_to_vector(word):
"""
Convert character vectors to integer vectors.
"""
vector = []
for char in list(word):
vector.append(char2int(char))
return vector | python | def word_to_vector(word):
"""
Convert character vectors to integer vectors.
"""
vector = []
for char in list(word):
vector.append(char2int(char))
return vector | [
"def",
"word_to_vector",
"(",
"word",
")",
":",
"vector",
"=",
"[",
"]",
"for",
"char",
"in",
"list",
"(",
"word",
")",
":",
"vector",
".",
"append",
"(",
"char2int",
"(",
"char",
")",
")",
"return",
"vector"
] | Convert character vectors to integer vectors. | [
"Convert",
"character",
"vectors",
"to",
"integer",
"vectors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/common.py#L46-L53 |
23,410 | apache/incubator-mxnet | example/gluon/lipnet/utils/common.py | vector_to_word | def vector_to_word(vector):
"""
Convert integer vectors to character vectors.
"""
word = ""
for vec in vector:
word = word + int2char(vec)
return word | python | def vector_to_word(vector):
"""
Convert integer vectors to character vectors.
"""
word = ""
for vec in vector:
word = word + int2char(vec)
return word | [
"def",
"vector_to_word",
"(",
"vector",
")",
":",
"word",
"=",
"\"\"",
"for",
"vec",
"in",
"vector",
":",
"word",
"=",
"word",
"+",
"int2char",
"(",
"vec",
")",
"return",
"word"
] | Convert integer vectors to character vectors. | [
"Convert",
"integer",
"vectors",
"to",
"character",
"vectors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/common.py#L56-L63 |
23,411 | apache/incubator-mxnet | example/gluon/lipnet/utils/common.py | char_conv | def char_conv(out):
"""
Convert integer vectors to character vectors for batch.
"""
out_conv = list()
for i in range(out.shape[0]):
tmp_str = ''
for j in range(out.shape[1]):
if int(out[i][j]) >= 0:
tmp_char = int2char(int(out[i][j]))
if int(out[i][j]) == 27:
tmp_char = ''
tmp_str = tmp_str + tmp_char
out_conv.append(tmp_str)
return out_conv | python | def char_conv(out):
"""
Convert integer vectors to character vectors for batch.
"""
out_conv = list()
for i in range(out.shape[0]):
tmp_str = ''
for j in range(out.shape[1]):
if int(out[i][j]) >= 0:
tmp_char = int2char(int(out[i][j]))
if int(out[i][j]) == 27:
tmp_char = ''
tmp_str = tmp_str + tmp_char
out_conv.append(tmp_str)
return out_conv | [
"def",
"char_conv",
"(",
"out",
")",
":",
"out_conv",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"out",
".",
"shape",
"[",
"0",
"]",
")",
":",
"tmp_str",
"=",
"''",
"for",
"j",
"in",
"range",
"(",
"out",
".",
"shape",
"[",
"1",
"]",
")",
":",
"if",
"int",
"(",
"out",
"[",
"i",
"]",
"[",
"j",
"]",
")",
">=",
"0",
":",
"tmp_char",
"=",
"int2char",
"(",
"int",
"(",
"out",
"[",
"i",
"]",
"[",
"j",
"]",
")",
")",
"if",
"int",
"(",
"out",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"==",
"27",
":",
"tmp_char",
"=",
"''",
"tmp_str",
"=",
"tmp_str",
"+",
"tmp_char",
"out_conv",
".",
"append",
"(",
"tmp_str",
")",
"return",
"out_conv"
] | Convert integer vectors to character vectors for batch. | [
"Convert",
"integer",
"vectors",
"to",
"character",
"vectors",
"for",
"batch",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/common.py#L66-L80 |
23,412 | apache/incubator-mxnet | example/kaggle-ndsb2/Preprocessing.py | get_frames | def get_frames(root_path):
"""Get path to all the frame in view SAX and contain complete frames"""
ret = []
for root, _, files in os.walk(root_path):
root=root.replace('\\','/')
files=[s for s in files if ".dcm" in s]
if len(files) == 0 or not files[0].endswith(".dcm") or root.find("sax") == -1:
continue
prefix = files[0].rsplit('-', 1)[0]
fileset = set(files)
expected = ["%s-%04d.dcm" % (prefix, i + 1) for i in range(30)]
if all(x in fileset for x in expected):
ret.append([root + "/" + x for x in expected])
# sort for reproduciblity
return sorted(ret, key = lambda x: x[0]) | python | def get_frames(root_path):
"""Get path to all the frame in view SAX and contain complete frames"""
ret = []
for root, _, files in os.walk(root_path):
root=root.replace('\\','/')
files=[s for s in files if ".dcm" in s]
if len(files) == 0 or not files[0].endswith(".dcm") or root.find("sax") == -1:
continue
prefix = files[0].rsplit('-', 1)[0]
fileset = set(files)
expected = ["%s-%04d.dcm" % (prefix, i + 1) for i in range(30)]
if all(x in fileset for x in expected):
ret.append([root + "/" + x for x in expected])
# sort for reproduciblity
return sorted(ret, key = lambda x: x[0]) | [
"def",
"get_frames",
"(",
"root_path",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root_path",
")",
":",
"root",
"=",
"root",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"files",
"=",
"[",
"s",
"for",
"s",
"in",
"files",
"if",
"\".dcm\"",
"in",
"s",
"]",
"if",
"len",
"(",
"files",
")",
"==",
"0",
"or",
"not",
"files",
"[",
"0",
"]",
".",
"endswith",
"(",
"\".dcm\"",
")",
"or",
"root",
".",
"find",
"(",
"\"sax\"",
")",
"==",
"-",
"1",
":",
"continue",
"prefix",
"=",
"files",
"[",
"0",
"]",
".",
"rsplit",
"(",
"'-'",
",",
"1",
")",
"[",
"0",
"]",
"fileset",
"=",
"set",
"(",
"files",
")",
"expected",
"=",
"[",
"\"%s-%04d.dcm\"",
"%",
"(",
"prefix",
",",
"i",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"30",
")",
"]",
"if",
"all",
"(",
"x",
"in",
"fileset",
"for",
"x",
"in",
"expected",
")",
":",
"ret",
".",
"append",
"(",
"[",
"root",
"+",
"\"/\"",
"+",
"x",
"for",
"x",
"in",
"expected",
"]",
")",
"# sort for reproduciblity",
"return",
"sorted",
"(",
"ret",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")"
] | Get path to all the frame in view SAX and contain complete frames | [
"Get",
"path",
"to",
"all",
"the",
"frame",
"in",
"view",
"SAX",
"and",
"contain",
"complete",
"frames"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Preprocessing.py#L39-L53 |
23,413 | apache/incubator-mxnet | example/kaggle-ndsb2/Preprocessing.py | write_data_csv | def write_data_csv(fname, frames, preproc):
"""Write data to csv file"""
fdata = open(fname, "w")
dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames)
data,result = zip(*dr)
for entry in data:
fdata.write(','.join(entry)+'\r\n')
print("All finished, %d slices in total" % len(data))
fdata.close()
result = np.ravel(result)
return result | python | def write_data_csv(fname, frames, preproc):
"""Write data to csv file"""
fdata = open(fname, "w")
dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames)
data,result = zip(*dr)
for entry in data:
fdata.write(','.join(entry)+'\r\n')
print("All finished, %d slices in total" % len(data))
fdata.close()
result = np.ravel(result)
return result | [
"def",
"write_data_csv",
"(",
"fname",
",",
"frames",
",",
"preproc",
")",
":",
"fdata",
"=",
"open",
"(",
"fname",
",",
"\"w\"",
")",
"dr",
"=",
"Parallel",
"(",
")",
"(",
"delayed",
"(",
"get_data",
")",
"(",
"lst",
",",
"preproc",
")",
"for",
"lst",
"in",
"frames",
")",
"data",
",",
"result",
"=",
"zip",
"(",
"*",
"dr",
")",
"for",
"entry",
"in",
"data",
":",
"fdata",
".",
"write",
"(",
"','",
".",
"join",
"(",
"entry",
")",
"+",
"'\\r\\n'",
")",
"print",
"(",
"\"All finished, %d slices in total\"",
"%",
"len",
"(",
"data",
")",
")",
"fdata",
".",
"close",
"(",
")",
"result",
"=",
"np",
".",
"ravel",
"(",
"result",
")",
"return",
"result"
] | Write data to csv file | [
"Write",
"data",
"to",
"csv",
"file"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Preprocessing.py#L94-L104 |
23,414 | apache/incubator-mxnet | example/kaggle-ndsb2/Preprocessing.py | crop_resize | def crop_resize(img, size):
"""crop center and resize"""
if img.shape[0] < img.shape[1]:
img = img.T
# we crop image from center
short_egde = min(img.shape[:2])
yy = int((img.shape[0] - short_egde) / 2)
xx = int((img.shape[1] - short_egde) / 2)
crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
# resize to 64, 64
resized_img = transform.resize(crop_img, (size, size))
resized_img *= 255
return resized_img.astype("uint8") | python | def crop_resize(img, size):
"""crop center and resize"""
if img.shape[0] < img.shape[1]:
img = img.T
# we crop image from center
short_egde = min(img.shape[:2])
yy = int((img.shape[0] - short_egde) / 2)
xx = int((img.shape[1] - short_egde) / 2)
crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
# resize to 64, 64
resized_img = transform.resize(crop_img, (size, size))
resized_img *= 255
return resized_img.astype("uint8") | [
"def",
"crop_resize",
"(",
"img",
",",
"size",
")",
":",
"if",
"img",
".",
"shape",
"[",
"0",
"]",
"<",
"img",
".",
"shape",
"[",
"1",
"]",
":",
"img",
"=",
"img",
".",
"T",
"# we crop image from center",
"short_egde",
"=",
"min",
"(",
"img",
".",
"shape",
"[",
":",
"2",
"]",
")",
"yy",
"=",
"int",
"(",
"(",
"img",
".",
"shape",
"[",
"0",
"]",
"-",
"short_egde",
")",
"/",
"2",
")",
"xx",
"=",
"int",
"(",
"(",
"img",
".",
"shape",
"[",
"1",
"]",
"-",
"short_egde",
")",
"/",
"2",
")",
"crop_img",
"=",
"img",
"[",
"yy",
":",
"yy",
"+",
"short_egde",
",",
"xx",
":",
"xx",
"+",
"short_egde",
"]",
"# resize to 64, 64",
"resized_img",
"=",
"transform",
".",
"resize",
"(",
"crop_img",
",",
"(",
"size",
",",
"size",
")",
")",
"resized_img",
"*=",
"255",
"return",
"resized_img",
".",
"astype",
"(",
"\"uint8\"",
")"
] | crop center and resize | [
"crop",
"center",
"and",
"resize"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Preprocessing.py#L107-L119 |
23,415 | apache/incubator-mxnet | example/gluon/sn_gan/model.py | get_generator | def get_generator():
""" construct and return generator """
g_net = gluon.nn.Sequential()
with g_net.name_scope():
g_net.add(gluon.nn.Conv2DTranspose(
channels=512, kernel_size=4, strides=1, padding=0, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(
channels=256, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(
channels=128, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(
channels=64, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(channels=3, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.Activation('tanh'))
return g_net | python | def get_generator():
""" construct and return generator """
g_net = gluon.nn.Sequential()
with g_net.name_scope():
g_net.add(gluon.nn.Conv2DTranspose(
channels=512, kernel_size=4, strides=1, padding=0, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(
channels=256, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(
channels=128, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(
channels=64, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.LeakyReLU(0.2))
g_net.add(gluon.nn.Conv2DTranspose(channels=3, kernel_size=4, strides=2, padding=1, use_bias=False))
g_net.add(gluon.nn.Activation('tanh'))
return g_net | [
"def",
"get_generator",
"(",
")",
":",
"g_net",
"=",
"gluon",
".",
"nn",
".",
"Sequential",
"(",
")",
"with",
"g_net",
".",
"name_scope",
"(",
")",
":",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"Conv2DTranspose",
"(",
"channels",
"=",
"512",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"use_bias",
"=",
"False",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"BatchNorm",
"(",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"Conv2DTranspose",
"(",
"channels",
"=",
"256",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"use_bias",
"=",
"False",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"BatchNorm",
"(",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"Conv2DTranspose",
"(",
"channels",
"=",
"128",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"use_bias",
"=",
"False",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"BatchNorm",
"(",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"Conv2DTranspose",
"(",
"channels",
"=",
"64",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"use_bias",
"=",
"False",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"BatchNorm",
"(",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"Conv2DTranspose",
"(",
"channels",
"=",
"3",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"use_bias",
"=",
"False",
")",
")",
"g_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"Activation",
"(",
"'tanh'",
")",
")",
"return",
"g_net"
] | construct and return generator | [
"construct",
"and",
"return",
"generator"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/model.py#L89-L117 |
23,416 | apache/incubator-mxnet | example/gluon/sn_gan/model.py | get_descriptor | def get_descriptor(ctx):
""" construct and return descriptor """
d_net = gluon.nn.Sequential()
with d_net.name_scope():
d_net.add(SNConv2D(num_filter=64, kernel_size=4, strides=2, padding=1, in_channels=3, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=128, kernel_size=4, strides=2, padding=1, in_channels=64, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=256, kernel_size=4, strides=2, padding=1, in_channels=128, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=512, kernel_size=4, strides=2, padding=1, in_channels=256, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=1, kernel_size=4, strides=1, padding=0, in_channels=512, ctx=ctx))
return d_net | python | def get_descriptor(ctx):
""" construct and return descriptor """
d_net = gluon.nn.Sequential()
with d_net.name_scope():
d_net.add(SNConv2D(num_filter=64, kernel_size=4, strides=2, padding=1, in_channels=3, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=128, kernel_size=4, strides=2, padding=1, in_channels=64, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=256, kernel_size=4, strides=2, padding=1, in_channels=128, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=512, kernel_size=4, strides=2, padding=1, in_channels=256, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_filter=1, kernel_size=4, strides=1, padding=0, in_channels=512, ctx=ctx))
return d_net | [
"def",
"get_descriptor",
"(",
"ctx",
")",
":",
"d_net",
"=",
"gluon",
".",
"nn",
".",
"Sequential",
"(",
")",
"with",
"d_net",
".",
"name_scope",
"(",
")",
":",
"d_net",
".",
"add",
"(",
"SNConv2D",
"(",
"num_filter",
"=",
"64",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"in_channels",
"=",
"3",
",",
"ctx",
"=",
"ctx",
")",
")",
"d_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"d_net",
".",
"add",
"(",
"SNConv2D",
"(",
"num_filter",
"=",
"128",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"in_channels",
"=",
"64",
",",
"ctx",
"=",
"ctx",
")",
")",
"d_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"d_net",
".",
"add",
"(",
"SNConv2D",
"(",
"num_filter",
"=",
"256",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"in_channels",
"=",
"128",
",",
"ctx",
"=",
"ctx",
")",
")",
"d_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"d_net",
".",
"add",
"(",
"SNConv2D",
"(",
"num_filter",
"=",
"512",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"1",
",",
"in_channels",
"=",
"256",
",",
"ctx",
"=",
"ctx",
")",
")",
"d_net",
".",
"add",
"(",
"gluon",
".",
"nn",
".",
"LeakyReLU",
"(",
"0.2",
")",
")",
"d_net",
".",
"add",
"(",
"SNConv2D",
"(",
"num_filter",
"=",
"1",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"in_channels",
"=",
"512",
",",
"ctx",
"=",
"ctx",
")",
")",
"return",
"d_net"
] | construct and return descriptor | [
"construct",
"and",
"return",
"descriptor"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/model.py#L120-L139 |
23,417 | apache/incubator-mxnet | example/ssd/tools/rand_sampler.py | RandCropper.sample | def sample(self, label):
"""
generate random cropping boxes according to parameters
if satifactory crops generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
list of (crop_box, label) tuples, if failed, return empty list []
"""
samples = []
count = 0
for trial in range(self.max_trials):
if count >= self.max_sample:
return samples
scale = np.random.uniform(self.min_scale, self.max_scale)
min_ratio = max(self.min_aspect_ratio, scale * scale)
max_ratio = min(self.max_aspect_ratio, 1. / scale / scale)
ratio = math.sqrt(np.random.uniform(min_ratio, max_ratio))
width = scale * ratio
height = scale / ratio
left = np.random.uniform(0., 1 - width)
top = np.random.uniform(0., 1 - height)
rand_box = (left, top, left + width, top + height)
valid_mask = np.where(label[:, 0] > -1)[0]
gt = label[valid_mask, :]
ious = self._check_satisfy(rand_box, gt)
if ious is not None:
# transform gt labels after crop, discard bad ones
l, t, r, b = rand_box
new_gt_boxes = []
new_width = r - l
new_height = b - t
for i in range(valid_mask.size):
if ious[i] > 0:
xmin = max(0., (gt[i, 1] - l) / new_width)
ymin = max(0., (gt[i, 2] - t) / new_height)
xmax = min(1., (gt[i, 3] - l) / new_width)
ymax = min(1., (gt[i, 4] - t) / new_height)
new_gt_boxes.append([gt[i, 0], xmin, ymin, xmax, ymax])
if not new_gt_boxes:
continue
new_gt_boxes = np.array(new_gt_boxes)
label = np.lib.pad(new_gt_boxes,
((0, label.shape[0]-new_gt_boxes.shape[0]), (0,0)), \
'constant', constant_values=(-1, -1))
samples.append((rand_box, label))
count += 1
return samples | python | def sample(self, label):
"""
generate random cropping boxes according to parameters
if satifactory crops generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
list of (crop_box, label) tuples, if failed, return empty list []
"""
samples = []
count = 0
for trial in range(self.max_trials):
if count >= self.max_sample:
return samples
scale = np.random.uniform(self.min_scale, self.max_scale)
min_ratio = max(self.min_aspect_ratio, scale * scale)
max_ratio = min(self.max_aspect_ratio, 1. / scale / scale)
ratio = math.sqrt(np.random.uniform(min_ratio, max_ratio))
width = scale * ratio
height = scale / ratio
left = np.random.uniform(0., 1 - width)
top = np.random.uniform(0., 1 - height)
rand_box = (left, top, left + width, top + height)
valid_mask = np.where(label[:, 0] > -1)[0]
gt = label[valid_mask, :]
ious = self._check_satisfy(rand_box, gt)
if ious is not None:
# transform gt labels after crop, discard bad ones
l, t, r, b = rand_box
new_gt_boxes = []
new_width = r - l
new_height = b - t
for i in range(valid_mask.size):
if ious[i] > 0:
xmin = max(0., (gt[i, 1] - l) / new_width)
ymin = max(0., (gt[i, 2] - t) / new_height)
xmax = min(1., (gt[i, 3] - l) / new_width)
ymax = min(1., (gt[i, 4] - t) / new_height)
new_gt_boxes.append([gt[i, 0], xmin, ymin, xmax, ymax])
if not new_gt_boxes:
continue
new_gt_boxes = np.array(new_gt_boxes)
label = np.lib.pad(new_gt_boxes,
((0, label.shape[0]-new_gt_boxes.shape[0]), (0,0)), \
'constant', constant_values=(-1, -1))
samples.append((rand_box, label))
count += 1
return samples | [
"def",
"sample",
"(",
"self",
",",
"label",
")",
":",
"samples",
"=",
"[",
"]",
"count",
"=",
"0",
"for",
"trial",
"in",
"range",
"(",
"self",
".",
"max_trials",
")",
":",
"if",
"count",
">=",
"self",
".",
"max_sample",
":",
"return",
"samples",
"scale",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"self",
".",
"min_scale",
",",
"self",
".",
"max_scale",
")",
"min_ratio",
"=",
"max",
"(",
"self",
".",
"min_aspect_ratio",
",",
"scale",
"*",
"scale",
")",
"max_ratio",
"=",
"min",
"(",
"self",
".",
"max_aspect_ratio",
",",
"1.",
"/",
"scale",
"/",
"scale",
")",
"ratio",
"=",
"math",
".",
"sqrt",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"min_ratio",
",",
"max_ratio",
")",
")",
"width",
"=",
"scale",
"*",
"ratio",
"height",
"=",
"scale",
"/",
"ratio",
"left",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0.",
",",
"1",
"-",
"width",
")",
"top",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0.",
",",
"1",
"-",
"height",
")",
"rand_box",
"=",
"(",
"left",
",",
"top",
",",
"left",
"+",
"width",
",",
"top",
"+",
"height",
")",
"valid_mask",
"=",
"np",
".",
"where",
"(",
"label",
"[",
":",
",",
"0",
"]",
">",
"-",
"1",
")",
"[",
"0",
"]",
"gt",
"=",
"label",
"[",
"valid_mask",
",",
":",
"]",
"ious",
"=",
"self",
".",
"_check_satisfy",
"(",
"rand_box",
",",
"gt",
")",
"if",
"ious",
"is",
"not",
"None",
":",
"# transform gt labels after crop, discard bad ones",
"l",
",",
"t",
",",
"r",
",",
"b",
"=",
"rand_box",
"new_gt_boxes",
"=",
"[",
"]",
"new_width",
"=",
"r",
"-",
"l",
"new_height",
"=",
"b",
"-",
"t",
"for",
"i",
"in",
"range",
"(",
"valid_mask",
".",
"size",
")",
":",
"if",
"ious",
"[",
"i",
"]",
">",
"0",
":",
"xmin",
"=",
"max",
"(",
"0.",
",",
"(",
"gt",
"[",
"i",
",",
"1",
"]",
"-",
"l",
")",
"/",
"new_width",
")",
"ymin",
"=",
"max",
"(",
"0.",
",",
"(",
"gt",
"[",
"i",
",",
"2",
"]",
"-",
"t",
")",
"/",
"new_height",
")",
"xmax",
"=",
"min",
"(",
"1.",
",",
"(",
"gt",
"[",
"i",
",",
"3",
"]",
"-",
"l",
")",
"/",
"new_width",
")",
"ymax",
"=",
"min",
"(",
"1.",
",",
"(",
"gt",
"[",
"i",
",",
"4",
"]",
"-",
"t",
")",
"/",
"new_height",
")",
"new_gt_boxes",
".",
"append",
"(",
"[",
"gt",
"[",
"i",
",",
"0",
"]",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
"]",
")",
"if",
"not",
"new_gt_boxes",
":",
"continue",
"new_gt_boxes",
"=",
"np",
".",
"array",
"(",
"new_gt_boxes",
")",
"label",
"=",
"np",
".",
"lib",
".",
"pad",
"(",
"new_gt_boxes",
",",
"(",
"(",
"0",
",",
"label",
".",
"shape",
"[",
"0",
"]",
"-",
"new_gt_boxes",
".",
"shape",
"[",
"0",
"]",
")",
",",
"(",
"0",
",",
"0",
")",
")",
",",
"'constant'",
",",
"constant_values",
"=",
"(",
"-",
"1",
",",
"-",
"1",
")",
")",
"samples",
".",
"append",
"(",
"(",
"rand_box",
",",
"label",
")",
")",
"count",
"+=",
"1",
"return",
"samples"
] | generate random cropping boxes according to parameters
if satifactory crops generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
list of (crop_box, label) tuples, if failed, return empty list [] | [
"generate",
"random",
"cropping",
"boxes",
"according",
"to",
"parameters",
"if",
"satifactory",
"crops",
"generated",
"apply",
"to",
"ground",
"-",
"truth",
"as",
"well"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/rand_sampler.py#L93-L145 |
23,418 | apache/incubator-mxnet | example/ssd/tools/rand_sampler.py | RandCropper._check_satisfy | def _check_satisfy(self, rand_box, gt_boxes):
"""
check if overlap with any gt box is larger than threshold
"""
l, t, r, b = rand_box
num_gt = gt_boxes.shape[0]
ls = np.ones(num_gt) * l
ts = np.ones(num_gt) * t
rs = np.ones(num_gt) * r
bs = np.ones(num_gt) * b
mask = np.where(ls < gt_boxes[:, 1])[0]
ls[mask] = gt_boxes[mask, 1]
mask = np.where(ts < gt_boxes[:, 2])[0]
ts[mask] = gt_boxes[mask, 2]
mask = np.where(rs > gt_boxes[:, 3])[0]
rs[mask] = gt_boxes[mask, 3]
mask = np.where(bs > gt_boxes[:, 4])[0]
bs[mask] = gt_boxes[mask, 4]
w = rs - ls
w[w < 0] = 0
h = bs - ts
h[h < 0] = 0
inter_area = h * w
union_area = np.ones(num_gt) * max(0, r - l) * max(0, b - t)
union_area += (gt_boxes[:, 3] - gt_boxes[:, 1]) * (gt_boxes[:, 4] - gt_boxes[:, 2])
union_area -= inter_area
ious = inter_area / union_area
ious[union_area <= 0] = 0
max_iou = np.amax(ious)
if max_iou < self.min_overlap:
return None
# check ground-truth constraint
if self.config['gt_constraint'] == 'center':
for i in range(ious.shape[0]):
if ious[i] > 0:
gt_x = (gt_boxes[i, 1] + gt_boxes[i, 3]) / 2.0
gt_y = (gt_boxes[i, 2] + gt_boxes[i, 4]) / 2.0
if gt_x < l or gt_x > r or gt_y < t or gt_y > b:
return None
elif self.config['gt_constraint'] == 'corner':
for i in range(ious.shape[0]):
if ious[i] > 0:
if gt_boxes[i, 1] < l or gt_boxes[i, 3] > r \
or gt_boxes[i, 2] < t or gt_boxes[i, 4] > b:
return None
return ious | python | def _check_satisfy(self, rand_box, gt_boxes):
"""
check if overlap with any gt box is larger than threshold
"""
l, t, r, b = rand_box
num_gt = gt_boxes.shape[0]
ls = np.ones(num_gt) * l
ts = np.ones(num_gt) * t
rs = np.ones(num_gt) * r
bs = np.ones(num_gt) * b
mask = np.where(ls < gt_boxes[:, 1])[0]
ls[mask] = gt_boxes[mask, 1]
mask = np.where(ts < gt_boxes[:, 2])[0]
ts[mask] = gt_boxes[mask, 2]
mask = np.where(rs > gt_boxes[:, 3])[0]
rs[mask] = gt_boxes[mask, 3]
mask = np.where(bs > gt_boxes[:, 4])[0]
bs[mask] = gt_boxes[mask, 4]
w = rs - ls
w[w < 0] = 0
h = bs - ts
h[h < 0] = 0
inter_area = h * w
union_area = np.ones(num_gt) * max(0, r - l) * max(0, b - t)
union_area += (gt_boxes[:, 3] - gt_boxes[:, 1]) * (gt_boxes[:, 4] - gt_boxes[:, 2])
union_area -= inter_area
ious = inter_area / union_area
ious[union_area <= 0] = 0
max_iou = np.amax(ious)
if max_iou < self.min_overlap:
return None
# check ground-truth constraint
if self.config['gt_constraint'] == 'center':
for i in range(ious.shape[0]):
if ious[i] > 0:
gt_x = (gt_boxes[i, 1] + gt_boxes[i, 3]) / 2.0
gt_y = (gt_boxes[i, 2] + gt_boxes[i, 4]) / 2.0
if gt_x < l or gt_x > r or gt_y < t or gt_y > b:
return None
elif self.config['gt_constraint'] == 'corner':
for i in range(ious.shape[0]):
if ious[i] > 0:
if gt_boxes[i, 1] < l or gt_boxes[i, 3] > r \
or gt_boxes[i, 2] < t or gt_boxes[i, 4] > b:
return None
return ious | [
"def",
"_check_satisfy",
"(",
"self",
",",
"rand_box",
",",
"gt_boxes",
")",
":",
"l",
",",
"t",
",",
"r",
",",
"b",
"=",
"rand_box",
"num_gt",
"=",
"gt_boxes",
".",
"shape",
"[",
"0",
"]",
"ls",
"=",
"np",
".",
"ones",
"(",
"num_gt",
")",
"*",
"l",
"ts",
"=",
"np",
".",
"ones",
"(",
"num_gt",
")",
"*",
"t",
"rs",
"=",
"np",
".",
"ones",
"(",
"num_gt",
")",
"*",
"r",
"bs",
"=",
"np",
".",
"ones",
"(",
"num_gt",
")",
"*",
"b",
"mask",
"=",
"np",
".",
"where",
"(",
"ls",
"<",
"gt_boxes",
"[",
":",
",",
"1",
"]",
")",
"[",
"0",
"]",
"ls",
"[",
"mask",
"]",
"=",
"gt_boxes",
"[",
"mask",
",",
"1",
"]",
"mask",
"=",
"np",
".",
"where",
"(",
"ts",
"<",
"gt_boxes",
"[",
":",
",",
"2",
"]",
")",
"[",
"0",
"]",
"ts",
"[",
"mask",
"]",
"=",
"gt_boxes",
"[",
"mask",
",",
"2",
"]",
"mask",
"=",
"np",
".",
"where",
"(",
"rs",
">",
"gt_boxes",
"[",
":",
",",
"3",
"]",
")",
"[",
"0",
"]",
"rs",
"[",
"mask",
"]",
"=",
"gt_boxes",
"[",
"mask",
",",
"3",
"]",
"mask",
"=",
"np",
".",
"where",
"(",
"bs",
">",
"gt_boxes",
"[",
":",
",",
"4",
"]",
")",
"[",
"0",
"]",
"bs",
"[",
"mask",
"]",
"=",
"gt_boxes",
"[",
"mask",
",",
"4",
"]",
"w",
"=",
"rs",
"-",
"ls",
"w",
"[",
"w",
"<",
"0",
"]",
"=",
"0",
"h",
"=",
"bs",
"-",
"ts",
"h",
"[",
"h",
"<",
"0",
"]",
"=",
"0",
"inter_area",
"=",
"h",
"*",
"w",
"union_area",
"=",
"np",
".",
"ones",
"(",
"num_gt",
")",
"*",
"max",
"(",
"0",
",",
"r",
"-",
"l",
")",
"*",
"max",
"(",
"0",
",",
"b",
"-",
"t",
")",
"union_area",
"+=",
"(",
"gt_boxes",
"[",
":",
",",
"3",
"]",
"-",
"gt_boxes",
"[",
":",
",",
"1",
"]",
")",
"*",
"(",
"gt_boxes",
"[",
":",
",",
"4",
"]",
"-",
"gt_boxes",
"[",
":",
",",
"2",
"]",
")",
"union_area",
"-=",
"inter_area",
"ious",
"=",
"inter_area",
"/",
"union_area",
"ious",
"[",
"union_area",
"<=",
"0",
"]",
"=",
"0",
"max_iou",
"=",
"np",
".",
"amax",
"(",
"ious",
")",
"if",
"max_iou",
"<",
"self",
".",
"min_overlap",
":",
"return",
"None",
"# check ground-truth constraint",
"if",
"self",
".",
"config",
"[",
"'gt_constraint'",
"]",
"==",
"'center'",
":",
"for",
"i",
"in",
"range",
"(",
"ious",
".",
"shape",
"[",
"0",
"]",
")",
":",
"if",
"ious",
"[",
"i",
"]",
">",
"0",
":",
"gt_x",
"=",
"(",
"gt_boxes",
"[",
"i",
",",
"1",
"]",
"+",
"gt_boxes",
"[",
"i",
",",
"3",
"]",
")",
"/",
"2.0",
"gt_y",
"=",
"(",
"gt_boxes",
"[",
"i",
",",
"2",
"]",
"+",
"gt_boxes",
"[",
"i",
",",
"4",
"]",
")",
"/",
"2.0",
"if",
"gt_x",
"<",
"l",
"or",
"gt_x",
">",
"r",
"or",
"gt_y",
"<",
"t",
"or",
"gt_y",
">",
"b",
":",
"return",
"None",
"elif",
"self",
".",
"config",
"[",
"'gt_constraint'",
"]",
"==",
"'corner'",
":",
"for",
"i",
"in",
"range",
"(",
"ious",
".",
"shape",
"[",
"0",
"]",
")",
":",
"if",
"ious",
"[",
"i",
"]",
">",
"0",
":",
"if",
"gt_boxes",
"[",
"i",
",",
"1",
"]",
"<",
"l",
"or",
"gt_boxes",
"[",
"i",
",",
"3",
"]",
">",
"r",
"or",
"gt_boxes",
"[",
"i",
",",
"2",
"]",
"<",
"t",
"or",
"gt_boxes",
"[",
"i",
",",
"4",
"]",
">",
"b",
":",
"return",
"None",
"return",
"ious"
] | check if overlap with any gt box is larger than threshold | [
"check",
"if",
"overlap",
"with",
"any",
"gt",
"box",
"is",
"larger",
"than",
"threshold"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/rand_sampler.py#L147-L192 |
23,419 | apache/incubator-mxnet | example/ssd/tools/rand_sampler.py | RandPadder.sample | def sample(self, label):
"""
generate random padding boxes according to parameters
if satifactory padding generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
list of (crop_box, label) tuples, if failed, return empty list []
"""
samples = []
count = 0
for trial in range(self.max_trials):
if count >= self.max_sample:
return samples
scale = np.random.uniform(self.min_scale, self.max_scale)
min_ratio = max(self.min_aspect_ratio, scale * scale)
max_ratio = min(self.max_aspect_ratio, 1. / scale / scale)
ratio = math.sqrt(np.random.uniform(min_ratio, max_ratio))
width = scale * ratio
if width < 1:
continue
height = scale / ratio
if height < 1:
continue
left = np.random.uniform(0., 1 - width)
top = np.random.uniform(0., 1 - height)
right = left + width
bot = top + height
rand_box = (left, top, right, bot)
valid_mask = np.where(label[:, 0] > -1)[0]
gt = label[valid_mask, :]
new_gt_boxes = []
for i in range(gt.shape[0]):
xmin = (gt[i, 1] - left) / width
ymin = (gt[i, 2] - top) / height
xmax = (gt[i, 3] - left) / width
ymax = (gt[i, 4] - top) / height
new_size = min(xmax - xmin, ymax - ymin)
if new_size < self.min_gt_scale:
new_gt_boxes = []
break
new_gt_boxes.append([gt[i, 0], xmin, ymin, xmax, ymax])
if not new_gt_boxes:
continue
new_gt_boxes = np.array(new_gt_boxes)
label = np.lib.pad(new_gt_boxes,
((0, label.shape[0]-new_gt_boxes.shape[0]), (0,0)), \
'constant', constant_values=(-1, -1))
samples.append((rand_box, label))
count += 1
return samples | python | def sample(self, label):
"""
generate random padding boxes according to parameters
if satifactory padding generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
list of (crop_box, label) tuples, if failed, return empty list []
"""
samples = []
count = 0
for trial in range(self.max_trials):
if count >= self.max_sample:
return samples
scale = np.random.uniform(self.min_scale, self.max_scale)
min_ratio = max(self.min_aspect_ratio, scale * scale)
max_ratio = min(self.max_aspect_ratio, 1. / scale / scale)
ratio = math.sqrt(np.random.uniform(min_ratio, max_ratio))
width = scale * ratio
if width < 1:
continue
height = scale / ratio
if height < 1:
continue
left = np.random.uniform(0., 1 - width)
top = np.random.uniform(0., 1 - height)
right = left + width
bot = top + height
rand_box = (left, top, right, bot)
valid_mask = np.where(label[:, 0] > -1)[0]
gt = label[valid_mask, :]
new_gt_boxes = []
for i in range(gt.shape[0]):
xmin = (gt[i, 1] - left) / width
ymin = (gt[i, 2] - top) / height
xmax = (gt[i, 3] - left) / width
ymax = (gt[i, 4] - top) / height
new_size = min(xmax - xmin, ymax - ymin)
if new_size < self.min_gt_scale:
new_gt_boxes = []
break
new_gt_boxes.append([gt[i, 0], xmin, ymin, xmax, ymax])
if not new_gt_boxes:
continue
new_gt_boxes = np.array(new_gt_boxes)
label = np.lib.pad(new_gt_boxes,
((0, label.shape[0]-new_gt_boxes.shape[0]), (0,0)), \
'constant', constant_values=(-1, -1))
samples.append((rand_box, label))
count += 1
return samples | [
"def",
"sample",
"(",
"self",
",",
"label",
")",
":",
"samples",
"=",
"[",
"]",
"count",
"=",
"0",
"for",
"trial",
"in",
"range",
"(",
"self",
".",
"max_trials",
")",
":",
"if",
"count",
">=",
"self",
".",
"max_sample",
":",
"return",
"samples",
"scale",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"self",
".",
"min_scale",
",",
"self",
".",
"max_scale",
")",
"min_ratio",
"=",
"max",
"(",
"self",
".",
"min_aspect_ratio",
",",
"scale",
"*",
"scale",
")",
"max_ratio",
"=",
"min",
"(",
"self",
".",
"max_aspect_ratio",
",",
"1.",
"/",
"scale",
"/",
"scale",
")",
"ratio",
"=",
"math",
".",
"sqrt",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"min_ratio",
",",
"max_ratio",
")",
")",
"width",
"=",
"scale",
"*",
"ratio",
"if",
"width",
"<",
"1",
":",
"continue",
"height",
"=",
"scale",
"/",
"ratio",
"if",
"height",
"<",
"1",
":",
"continue",
"left",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0.",
",",
"1",
"-",
"width",
")",
"top",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0.",
",",
"1",
"-",
"height",
")",
"right",
"=",
"left",
"+",
"width",
"bot",
"=",
"top",
"+",
"height",
"rand_box",
"=",
"(",
"left",
",",
"top",
",",
"right",
",",
"bot",
")",
"valid_mask",
"=",
"np",
".",
"where",
"(",
"label",
"[",
":",
",",
"0",
"]",
">",
"-",
"1",
")",
"[",
"0",
"]",
"gt",
"=",
"label",
"[",
"valid_mask",
",",
":",
"]",
"new_gt_boxes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"gt",
".",
"shape",
"[",
"0",
"]",
")",
":",
"xmin",
"=",
"(",
"gt",
"[",
"i",
",",
"1",
"]",
"-",
"left",
")",
"/",
"width",
"ymin",
"=",
"(",
"gt",
"[",
"i",
",",
"2",
"]",
"-",
"top",
")",
"/",
"height",
"xmax",
"=",
"(",
"gt",
"[",
"i",
",",
"3",
"]",
"-",
"left",
")",
"/",
"width",
"ymax",
"=",
"(",
"gt",
"[",
"i",
",",
"4",
"]",
"-",
"top",
")",
"/",
"height",
"new_size",
"=",
"min",
"(",
"xmax",
"-",
"xmin",
",",
"ymax",
"-",
"ymin",
")",
"if",
"new_size",
"<",
"self",
".",
"min_gt_scale",
":",
"new_gt_boxes",
"=",
"[",
"]",
"break",
"new_gt_boxes",
".",
"append",
"(",
"[",
"gt",
"[",
"i",
",",
"0",
"]",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
"]",
")",
"if",
"not",
"new_gt_boxes",
":",
"continue",
"new_gt_boxes",
"=",
"np",
".",
"array",
"(",
"new_gt_boxes",
")",
"label",
"=",
"np",
".",
"lib",
".",
"pad",
"(",
"new_gt_boxes",
",",
"(",
"(",
"0",
",",
"label",
".",
"shape",
"[",
"0",
"]",
"-",
"new_gt_boxes",
".",
"shape",
"[",
"0",
"]",
")",
",",
"(",
"0",
",",
"0",
")",
")",
",",
"'constant'",
",",
"constant_values",
"=",
"(",
"-",
"1",
",",
"-",
"1",
")",
")",
"samples",
".",
"append",
"(",
"(",
"rand_box",
",",
"label",
")",
")",
"count",
"+=",
"1",
"return",
"samples"
] | generate random padding boxes according to parameters
if satifactory padding generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
list of (crop_box, label) tuples, if failed, return empty list [] | [
"generate",
"random",
"padding",
"boxes",
"according",
"to",
"parameters",
"if",
"satifactory",
"padding",
"generated",
"apply",
"to",
"ground",
"-",
"truth",
"as",
"well"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/rand_sampler.py#L232-L287 |
23,420 | apache/incubator-mxnet | benchmark/python/sparse/dot.py | measure_cost | def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs):
"""Measure time cost of running a function
"""
mx.nd.waitall()
args_list = []
for arg in args:
args_list.append(arg)
start = time.time()
if scipy_trans_lhs:
args_list[0] = np.transpose(args_list[0]) if scipy_dns_lhs else sp.spmatrix.transpose(args_list[0])
for _ in range(repeat):
func_name(*args_list, **kwargs)
mx.nd.waitall()
end = time.time()
diff = end - start
return diff / repeat | python | def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs):
"""Measure time cost of running a function
"""
mx.nd.waitall()
args_list = []
for arg in args:
args_list.append(arg)
start = time.time()
if scipy_trans_lhs:
args_list[0] = np.transpose(args_list[0]) if scipy_dns_lhs else sp.spmatrix.transpose(args_list[0])
for _ in range(repeat):
func_name(*args_list, **kwargs)
mx.nd.waitall()
end = time.time()
diff = end - start
return diff / repeat | [
"def",
"measure_cost",
"(",
"repeat",
",",
"scipy_trans_lhs",
",",
"scipy_dns_lhs",
",",
"func_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mx",
".",
"nd",
".",
"waitall",
"(",
")",
"args_list",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"args_list",
".",
"append",
"(",
"arg",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"if",
"scipy_trans_lhs",
":",
"args_list",
"[",
"0",
"]",
"=",
"np",
".",
"transpose",
"(",
"args_list",
"[",
"0",
"]",
")",
"if",
"scipy_dns_lhs",
"else",
"sp",
".",
"spmatrix",
".",
"transpose",
"(",
"args_list",
"[",
"0",
"]",
")",
"for",
"_",
"in",
"range",
"(",
"repeat",
")",
":",
"func_name",
"(",
"*",
"args_list",
",",
"*",
"*",
"kwargs",
")",
"mx",
".",
"nd",
".",
"waitall",
"(",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"diff",
"=",
"end",
"-",
"start",
"return",
"diff",
"/",
"repeat"
] | Measure time cost of running a function | [
"Measure",
"time",
"cost",
"of",
"running",
"a",
"function"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/benchmark/python/sparse/dot.py#L110-L125 |
23,421 | apache/incubator-mxnet | python/mxnet/gluon/data/dataloader.py | default_batchify_fn | def default_batchify_fn(data):
"""Collate data into batch."""
if isinstance(data[0], nd.NDArray):
return nd.stack(*data)
elif isinstance(data[0], tuple):
data = zip(*data)
return [default_batchify_fn(i) for i in data]
else:
data = np.asarray(data)
return nd.array(data, dtype=data.dtype) | python | def default_batchify_fn(data):
"""Collate data into batch."""
if isinstance(data[0], nd.NDArray):
return nd.stack(*data)
elif isinstance(data[0], tuple):
data = zip(*data)
return [default_batchify_fn(i) for i in data]
else:
data = np.asarray(data)
return nd.array(data, dtype=data.dtype) | [
"def",
"default_batchify_fn",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
"[",
"0",
"]",
",",
"nd",
".",
"NDArray",
")",
":",
"return",
"nd",
".",
"stack",
"(",
"*",
"data",
")",
"elif",
"isinstance",
"(",
"data",
"[",
"0",
"]",
",",
"tuple",
")",
":",
"data",
"=",
"zip",
"(",
"*",
"data",
")",
"return",
"[",
"default_batchify_fn",
"(",
"i",
")",
"for",
"i",
"in",
"data",
"]",
"else",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"return",
"nd",
".",
"array",
"(",
"data",
",",
"dtype",
"=",
"data",
".",
"dtype",
")"
] | Collate data into batch. | [
"Collate",
"data",
"into",
"batch",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L127-L136 |
23,422 | apache/incubator-mxnet | python/mxnet/gluon/data/dataloader.py | default_mp_batchify_fn | def default_mp_batchify_fn(data):
"""Collate data into batch. Use shared memory for stacking."""
if isinstance(data[0], nd.NDArray):
out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype,
ctx=context.Context('cpu_shared', 0))
return nd.stack(*data, out=out)
elif isinstance(data[0], tuple):
data = zip(*data)
return [default_mp_batchify_fn(i) for i in data]
else:
data = np.asarray(data)
return nd.array(data, dtype=data.dtype,
ctx=context.Context('cpu_shared', 0)) | python | def default_mp_batchify_fn(data):
"""Collate data into batch. Use shared memory for stacking."""
if isinstance(data[0], nd.NDArray):
out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype,
ctx=context.Context('cpu_shared', 0))
return nd.stack(*data, out=out)
elif isinstance(data[0], tuple):
data = zip(*data)
return [default_mp_batchify_fn(i) for i in data]
else:
data = np.asarray(data)
return nd.array(data, dtype=data.dtype,
ctx=context.Context('cpu_shared', 0)) | [
"def",
"default_mp_batchify_fn",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
"[",
"0",
"]",
",",
"nd",
".",
"NDArray",
")",
":",
"out",
"=",
"nd",
".",
"empty",
"(",
"(",
"len",
"(",
"data",
")",
",",
")",
"+",
"data",
"[",
"0",
"]",
".",
"shape",
",",
"dtype",
"=",
"data",
"[",
"0",
"]",
".",
"dtype",
",",
"ctx",
"=",
"context",
".",
"Context",
"(",
"'cpu_shared'",
",",
"0",
")",
")",
"return",
"nd",
".",
"stack",
"(",
"*",
"data",
",",
"out",
"=",
"out",
")",
"elif",
"isinstance",
"(",
"data",
"[",
"0",
"]",
",",
"tuple",
")",
":",
"data",
"=",
"zip",
"(",
"*",
"data",
")",
"return",
"[",
"default_mp_batchify_fn",
"(",
"i",
")",
"for",
"i",
"in",
"data",
"]",
"else",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"return",
"nd",
".",
"array",
"(",
"data",
",",
"dtype",
"=",
"data",
".",
"dtype",
",",
"ctx",
"=",
"context",
".",
"Context",
"(",
"'cpu_shared'",
",",
"0",
")",
")"
] | Collate data into batch. Use shared memory for stacking. | [
"Collate",
"data",
"into",
"batch",
".",
"Use",
"shared",
"memory",
"for",
"stacking",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L139-L151 |
23,423 | apache/incubator-mxnet | python/mxnet/gluon/data/dataloader.py | _as_in_context | def _as_in_context(data, ctx):
"""Move data into new context."""
if isinstance(data, nd.NDArray):
return data.as_in_context(ctx)
elif isinstance(data, (list, tuple)):
return [_as_in_context(d, ctx) for d in data]
return data | python | def _as_in_context(data, ctx):
"""Move data into new context."""
if isinstance(data, nd.NDArray):
return data.as_in_context(ctx)
elif isinstance(data, (list, tuple)):
return [_as_in_context(d, ctx) for d in data]
return data | [
"def",
"_as_in_context",
"(",
"data",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"nd",
".",
"NDArray",
")",
":",
"return",
"data",
".",
"as_in_context",
"(",
"ctx",
")",
"elif",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"_as_in_context",
"(",
"d",
",",
"ctx",
")",
"for",
"d",
"in",
"data",
"]",
"return",
"data"
] | Move data into new context. | [
"Move",
"data",
"into",
"new",
"context",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L154-L160 |
23,424 | apache/incubator-mxnet | python/mxnet/gluon/data/dataloader.py | worker_loop_v1 | def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn):
"""Worker loop for multiprocessing DataLoader."""
while True:
idx, samples = key_queue.get()
if idx is None:
break
batch = batchify_fn([dataset[i] for i in samples])
data_queue.put((idx, batch)) | python | def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn):
"""Worker loop for multiprocessing DataLoader."""
while True:
idx, samples = key_queue.get()
if idx is None:
break
batch = batchify_fn([dataset[i] for i in samples])
data_queue.put((idx, batch)) | [
"def",
"worker_loop_v1",
"(",
"dataset",
",",
"key_queue",
",",
"data_queue",
",",
"batchify_fn",
")",
":",
"while",
"True",
":",
"idx",
",",
"samples",
"=",
"key_queue",
".",
"get",
"(",
")",
"if",
"idx",
"is",
"None",
":",
"break",
"batch",
"=",
"batchify_fn",
"(",
"[",
"dataset",
"[",
"i",
"]",
"for",
"i",
"in",
"samples",
"]",
")",
"data_queue",
".",
"put",
"(",
"(",
"idx",
",",
"batch",
")",
")"
] | Worker loop for multiprocessing DataLoader. | [
"Worker",
"loop",
"for",
"multiprocessing",
"DataLoader",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L163-L170 |
23,425 | apache/incubator-mxnet | python/mxnet/gluon/data/dataloader.py | fetcher_loop_v1 | def fetcher_loop_v1(data_queue, data_buffer, pin_memory=False,
pin_device_id=0, data_buffer_lock=None):
"""Fetcher loop for fetching data from queue and put in reorder dict."""
while True:
idx, batch = data_queue.get()
if idx is None:
break
if pin_memory:
batch = _as_in_context(batch, context.cpu_pinned(pin_device_id))
else:
batch = _as_in_context(batch, context.cpu())
if data_buffer_lock is not None:
with data_buffer_lock:
data_buffer[idx] = batch
else:
data_buffer[idx] = batch | python | def fetcher_loop_v1(data_queue, data_buffer, pin_memory=False,
pin_device_id=0, data_buffer_lock=None):
"""Fetcher loop for fetching data from queue and put in reorder dict."""
while True:
idx, batch = data_queue.get()
if idx is None:
break
if pin_memory:
batch = _as_in_context(batch, context.cpu_pinned(pin_device_id))
else:
batch = _as_in_context(batch, context.cpu())
if data_buffer_lock is not None:
with data_buffer_lock:
data_buffer[idx] = batch
else:
data_buffer[idx] = batch | [
"def",
"fetcher_loop_v1",
"(",
"data_queue",
",",
"data_buffer",
",",
"pin_memory",
"=",
"False",
",",
"pin_device_id",
"=",
"0",
",",
"data_buffer_lock",
"=",
"None",
")",
":",
"while",
"True",
":",
"idx",
",",
"batch",
"=",
"data_queue",
".",
"get",
"(",
")",
"if",
"idx",
"is",
"None",
":",
"break",
"if",
"pin_memory",
":",
"batch",
"=",
"_as_in_context",
"(",
"batch",
",",
"context",
".",
"cpu_pinned",
"(",
"pin_device_id",
")",
")",
"else",
":",
"batch",
"=",
"_as_in_context",
"(",
"batch",
",",
"context",
".",
"cpu",
"(",
")",
")",
"if",
"data_buffer_lock",
"is",
"not",
"None",
":",
"with",
"data_buffer_lock",
":",
"data_buffer",
"[",
"idx",
"]",
"=",
"batch",
"else",
":",
"data_buffer",
"[",
"idx",
"]",
"=",
"batch"
] | Fetcher loop for fetching data from queue and put in reorder dict. | [
"Fetcher",
"loop",
"for",
"fetching",
"data",
"from",
"queue",
"and",
"put",
"in",
"reorder",
"dict",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L172-L187 |
23,426 | apache/incubator-mxnet | python/mxnet/gluon/data/dataloader.py | _MultiWorkerIterV1.shutdown | def shutdown(self):
"""Shutdown internal workers by pushing terminate signals."""
if not self._shutdown:
# send shutdown signal to the fetcher and join data queue first
# Remark: loop_fetcher need to be joined prior to the workers.
# otherwise, the the fetcher may fail at getting data
self._data_queue.put((None, None))
self._fetcher.join()
# send shutdown signal to all worker processes
for _ in range(self._num_workers):
self._key_queue.put((None, None))
# force shut down any alive worker processes
for w in self._workers:
if w.is_alive():
w.terminate()
self._shutdown = True | python | def shutdown(self):
"""Shutdown internal workers by pushing terminate signals."""
if not self._shutdown:
# send shutdown signal to the fetcher and join data queue first
# Remark: loop_fetcher need to be joined prior to the workers.
# otherwise, the the fetcher may fail at getting data
self._data_queue.put((None, None))
self._fetcher.join()
# send shutdown signal to all worker processes
for _ in range(self._num_workers):
self._key_queue.put((None, None))
# force shut down any alive worker processes
for w in self._workers:
if w.is_alive():
w.terminate()
self._shutdown = True | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_shutdown",
":",
"# send shutdown signal to the fetcher and join data queue first",
"# Remark: loop_fetcher need to be joined prior to the workers.",
"# otherwise, the the fetcher may fail at getting data",
"self",
".",
"_data_queue",
".",
"put",
"(",
"(",
"None",
",",
"None",
")",
")",
"self",
".",
"_fetcher",
".",
"join",
"(",
")",
"# send shutdown signal to all worker processes",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_num_workers",
")",
":",
"self",
".",
"_key_queue",
".",
"put",
"(",
"(",
"None",
",",
"None",
")",
")",
"# force shut down any alive worker processes",
"for",
"w",
"in",
"self",
".",
"_workers",
":",
"if",
"w",
".",
"is_alive",
"(",
")",
":",
"w",
".",
"terminate",
"(",
")",
"self",
".",
"_shutdown",
"=",
"True"
] | Shutdown internal workers by pushing terminate signals. | [
"Shutdown",
"internal",
"workers",
"by",
"pushing",
"terminate",
"signals",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataloader.py#L266-L281 |
23,427 | apache/incubator-mxnet | python/mxnet/kvstore.py | _ctype_key_value | def _ctype_key_value(keys, vals):
"""
Returns ctype arrays for the key-value args, and the whether string keys are used.
For internal use only.
"""
if isinstance(keys, (tuple, list)):
assert(len(keys) == len(vals))
c_keys = []
c_vals = []
use_str_keys = None
for key, val in zip(keys, vals):
c_key_i, c_val_i, str_keys_i = _ctype_key_value(key, val)
c_keys += c_key_i
c_vals += c_val_i
use_str_keys = str_keys_i if use_str_keys is None else use_str_keys
assert(use_str_keys == str_keys_i), "inconsistent types of keys detected."
c_keys_arr = c_array(ctypes.c_char_p, c_keys) if use_str_keys \
else c_array(ctypes.c_int, c_keys)
c_vals_arr = c_array(ctypes.c_void_p, c_vals)
return (c_keys_arr, c_vals_arr, use_str_keys)
assert(isinstance(keys, (int,) + string_types)), \
"unexpected type for keys: " + str(type(keys))
use_str_keys = isinstance(keys, string_types)
if isinstance(vals, NDArray):
c_keys = c_str_array([keys]) if use_str_keys \
else c_array_buf(ctypes.c_int, array('i', [keys]))
return (c_keys, c_handle_array([vals]), use_str_keys)
else:
for value in vals:
assert(isinstance(value, NDArray))
c_keys = c_str_array([keys] * len(vals)) if use_str_keys \
else c_array_buf(ctypes.c_int, array('i', [keys] * len(vals)))
return (c_keys, c_handle_array(vals), use_str_keys) | python | def _ctype_key_value(keys, vals):
"""
Returns ctype arrays for the key-value args, and the whether string keys are used.
For internal use only.
"""
if isinstance(keys, (tuple, list)):
assert(len(keys) == len(vals))
c_keys = []
c_vals = []
use_str_keys = None
for key, val in zip(keys, vals):
c_key_i, c_val_i, str_keys_i = _ctype_key_value(key, val)
c_keys += c_key_i
c_vals += c_val_i
use_str_keys = str_keys_i if use_str_keys is None else use_str_keys
assert(use_str_keys == str_keys_i), "inconsistent types of keys detected."
c_keys_arr = c_array(ctypes.c_char_p, c_keys) if use_str_keys \
else c_array(ctypes.c_int, c_keys)
c_vals_arr = c_array(ctypes.c_void_p, c_vals)
return (c_keys_arr, c_vals_arr, use_str_keys)
assert(isinstance(keys, (int,) + string_types)), \
"unexpected type for keys: " + str(type(keys))
use_str_keys = isinstance(keys, string_types)
if isinstance(vals, NDArray):
c_keys = c_str_array([keys]) if use_str_keys \
else c_array_buf(ctypes.c_int, array('i', [keys]))
return (c_keys, c_handle_array([vals]), use_str_keys)
else:
for value in vals:
assert(isinstance(value, NDArray))
c_keys = c_str_array([keys] * len(vals)) if use_str_keys \
else c_array_buf(ctypes.c_int, array('i', [keys] * len(vals)))
return (c_keys, c_handle_array(vals), use_str_keys) | [
"def",
"_ctype_key_value",
"(",
"keys",
",",
"vals",
")",
":",
"if",
"isinstance",
"(",
"keys",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"assert",
"(",
"len",
"(",
"keys",
")",
"==",
"len",
"(",
"vals",
")",
")",
"c_keys",
"=",
"[",
"]",
"c_vals",
"=",
"[",
"]",
"use_str_keys",
"=",
"None",
"for",
"key",
",",
"val",
"in",
"zip",
"(",
"keys",
",",
"vals",
")",
":",
"c_key_i",
",",
"c_val_i",
",",
"str_keys_i",
"=",
"_ctype_key_value",
"(",
"key",
",",
"val",
")",
"c_keys",
"+=",
"c_key_i",
"c_vals",
"+=",
"c_val_i",
"use_str_keys",
"=",
"str_keys_i",
"if",
"use_str_keys",
"is",
"None",
"else",
"use_str_keys",
"assert",
"(",
"use_str_keys",
"==",
"str_keys_i",
")",
",",
"\"inconsistent types of keys detected.\"",
"c_keys_arr",
"=",
"c_array",
"(",
"ctypes",
".",
"c_char_p",
",",
"c_keys",
")",
"if",
"use_str_keys",
"else",
"c_array",
"(",
"ctypes",
".",
"c_int",
",",
"c_keys",
")",
"c_vals_arr",
"=",
"c_array",
"(",
"ctypes",
".",
"c_void_p",
",",
"c_vals",
")",
"return",
"(",
"c_keys_arr",
",",
"c_vals_arr",
",",
"use_str_keys",
")",
"assert",
"(",
"isinstance",
"(",
"keys",
",",
"(",
"int",
",",
")",
"+",
"string_types",
")",
")",
",",
"\"unexpected type for keys: \"",
"+",
"str",
"(",
"type",
"(",
"keys",
")",
")",
"use_str_keys",
"=",
"isinstance",
"(",
"keys",
",",
"string_types",
")",
"if",
"isinstance",
"(",
"vals",
",",
"NDArray",
")",
":",
"c_keys",
"=",
"c_str_array",
"(",
"[",
"keys",
"]",
")",
"if",
"use_str_keys",
"else",
"c_array_buf",
"(",
"ctypes",
".",
"c_int",
",",
"array",
"(",
"'i'",
",",
"[",
"keys",
"]",
")",
")",
"return",
"(",
"c_keys",
",",
"c_handle_array",
"(",
"[",
"vals",
"]",
")",
",",
"use_str_keys",
")",
"else",
":",
"for",
"value",
"in",
"vals",
":",
"assert",
"(",
"isinstance",
"(",
"value",
",",
"NDArray",
")",
")",
"c_keys",
"=",
"c_str_array",
"(",
"[",
"keys",
"]",
"*",
"len",
"(",
"vals",
")",
")",
"if",
"use_str_keys",
"else",
"c_array_buf",
"(",
"ctypes",
".",
"c_int",
",",
"array",
"(",
"'i'",
",",
"[",
"keys",
"]",
"*",
"len",
"(",
"vals",
")",
")",
")",
"return",
"(",
"c_keys",
",",
"c_handle_array",
"(",
"vals",
")",
",",
"use_str_keys",
")"
] | Returns ctype arrays for the key-value args, and the whether string keys are used.
For internal use only. | [
"Returns",
"ctype",
"arrays",
"for",
"the",
"key",
"-",
"value",
"args",
"and",
"the",
"whether",
"string",
"keys",
"are",
"used",
".",
"For",
"internal",
"use",
"only",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L33-L66 |
23,428 | apache/incubator-mxnet | python/mxnet/kvstore.py | create | def create(name='local'):
"""Creates a new KVStore.
For single machine training, there are two commonly used types:
``local``: Copies all gradients to CPU memory and updates weights there.
``device``: Aggregates gradients and updates weights on GPUs. With this setting,
the KVStore also attempts to use GPU peer-to-peer communication,
potentially accelerating the communication.
For distributed training, KVStore also supports a number of types:
``dist_sync``: Behaves similarly to ``local`` but with one major difference.
With ``dist_sync``, batch-size now means the batch size used on each machine.
So if there are ``n`` machines and we use batch size ``b``,
then ``dist_sync`` behaves like ``local`` with batch size ``n * b``.
``dist_device_sync``: Identical to ``dist_sync`` with the difference similar
to ``device`` vs ``local``.
``dist_async``: Performs asynchronous updates.
The weights are updated whenever gradients are received from any machine.
No two updates happen on the same weight at the same time. However, the order is not
guaranteed.
Parameters
----------
name : {'local', 'device', 'nccl', 'dist_sync', 'dist_device_sync', 'dist_async'}
The type of KVStore.
Returns
-------
kv : KVStore
The created KVStore.
"""
if not isinstance(name, string_types):
raise TypeError('name must be a string')
handle = KVStoreHandle()
check_call(_LIB.MXKVStoreCreate(c_str(name),
ctypes.byref(handle)))
kv = KVStore(handle)
set_kvstore_handle(kv.handle)
return kv | python | def create(name='local'):
"""Creates a new KVStore.
For single machine training, there are two commonly used types:
``local``: Copies all gradients to CPU memory and updates weights there.
``device``: Aggregates gradients and updates weights on GPUs. With this setting,
the KVStore also attempts to use GPU peer-to-peer communication,
potentially accelerating the communication.
For distributed training, KVStore also supports a number of types:
``dist_sync``: Behaves similarly to ``local`` but with one major difference.
With ``dist_sync``, batch-size now means the batch size used on each machine.
So if there are ``n`` machines and we use batch size ``b``,
then ``dist_sync`` behaves like ``local`` with batch size ``n * b``.
``dist_device_sync``: Identical to ``dist_sync`` with the difference similar
to ``device`` vs ``local``.
``dist_async``: Performs asynchronous updates.
The weights are updated whenever gradients are received from any machine.
No two updates happen on the same weight at the same time. However, the order is not
guaranteed.
Parameters
----------
name : {'local', 'device', 'nccl', 'dist_sync', 'dist_device_sync', 'dist_async'}
The type of KVStore.
Returns
-------
kv : KVStore
The created KVStore.
"""
if not isinstance(name, string_types):
raise TypeError('name must be a string')
handle = KVStoreHandle()
check_call(_LIB.MXKVStoreCreate(c_str(name),
ctypes.byref(handle)))
kv = KVStore(handle)
set_kvstore_handle(kv.handle)
return kv | [
"def",
"create",
"(",
"name",
"=",
"'local'",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'name must be a string'",
")",
"handle",
"=",
"KVStoreHandle",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreCreate",
"(",
"c_str",
"(",
"name",
")",
",",
"ctypes",
".",
"byref",
"(",
"handle",
")",
")",
")",
"kv",
"=",
"KVStore",
"(",
"handle",
")",
"set_kvstore_handle",
"(",
"kv",
".",
"handle",
")",
"return",
"kv"
] | Creates a new KVStore.
For single machine training, there are two commonly used types:
``local``: Copies all gradients to CPU memory and updates weights there.
``device``: Aggregates gradients and updates weights on GPUs. With this setting,
the KVStore also attempts to use GPU peer-to-peer communication,
potentially accelerating the communication.
For distributed training, KVStore also supports a number of types:
``dist_sync``: Behaves similarly to ``local`` but with one major difference.
With ``dist_sync``, batch-size now means the batch size used on each machine.
So if there are ``n`` machines and we use batch size ``b``,
then ``dist_sync`` behaves like ``local`` with batch size ``n * b``.
``dist_device_sync``: Identical to ``dist_sync`` with the difference similar
to ``device`` vs ``local``.
``dist_async``: Performs asynchronous updates.
The weights are updated whenever gradients are received from any machine.
No two updates happen on the same weight at the same time. However, the order is not
guaranteed.
Parameters
----------
name : {'local', 'device', 'nccl', 'dist_sync', 'dist_device_sync', 'dist_async'}
The type of KVStore.
Returns
-------
kv : KVStore
The created KVStore. | [
"Creates",
"a",
"new",
"KVStore",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L635-L677 |
23,429 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.init | def init(self, key, value):
""" Initializes a single or a sequence of key-value pairs into the store.
For each key, one must `init` it before calling `push` or `pull`.
When multiple workers invoke `init` for the same key, only
the value supplied by worker with rank `0` is used. This function returns
after data has been initialized successfully.
Parameters
----------
key : str, int, or sequence of str or int
The keys.
value : NDArray, RowSparseNDArray or sequence of NDArray or RowSparseNDArray
Values corresponding to the keys.
Examples
--------
>>> # init a single key-value pair
>>> shape = (2,3)
>>> kv = mx.kv.create('local')
>>> kv.init('3', mx.nd.ones(shape)*2)
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # init a list of key-value pairs
>>> keys = ['5', '7', '9']
>>> kv.init(keys, [mx.nd.ones(shape)]*len(keys))
>>> # init a row_sparse value
>>> kv.init('4', mx.nd.ones(shape).tostype('row_sparse'))
>>> b = mx.nd.sparse.zeros('row_sparse', shape)
>>> kv.row_sparse_pull('4', row_ids=mx.nd.array([0, 1]), out=b)
>>> print b
<RowSparseNDArray 2x3 @cpu(0)>
"""
ckeys, cvals, use_str_keys = _ctype_key_value(key, value)
if use_str_keys:
check_call(_LIB.MXKVStoreInitEx(self.handle, mx_uint(len(ckeys)), ckeys, cvals))
else:
check_call(_LIB.MXKVStoreInit(self.handle, mx_uint(len(ckeys)), ckeys, cvals)) | python | def init(self, key, value):
""" Initializes a single or a sequence of key-value pairs into the store.
For each key, one must `init` it before calling `push` or `pull`.
When multiple workers invoke `init` for the same key, only
the value supplied by worker with rank `0` is used. This function returns
after data has been initialized successfully.
Parameters
----------
key : str, int, or sequence of str or int
The keys.
value : NDArray, RowSparseNDArray or sequence of NDArray or RowSparseNDArray
Values corresponding to the keys.
Examples
--------
>>> # init a single key-value pair
>>> shape = (2,3)
>>> kv = mx.kv.create('local')
>>> kv.init('3', mx.nd.ones(shape)*2)
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # init a list of key-value pairs
>>> keys = ['5', '7', '9']
>>> kv.init(keys, [mx.nd.ones(shape)]*len(keys))
>>> # init a row_sparse value
>>> kv.init('4', mx.nd.ones(shape).tostype('row_sparse'))
>>> b = mx.nd.sparse.zeros('row_sparse', shape)
>>> kv.row_sparse_pull('4', row_ids=mx.nd.array([0, 1]), out=b)
>>> print b
<RowSparseNDArray 2x3 @cpu(0)>
"""
ckeys, cvals, use_str_keys = _ctype_key_value(key, value)
if use_str_keys:
check_call(_LIB.MXKVStoreInitEx(self.handle, mx_uint(len(ckeys)), ckeys, cvals))
else:
check_call(_LIB.MXKVStoreInit(self.handle, mx_uint(len(ckeys)), ckeys, cvals)) | [
"def",
"init",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"ckeys",
",",
"cvals",
",",
"use_str_keys",
"=",
"_ctype_key_value",
"(",
"key",
",",
"value",
")",
"if",
"use_str_keys",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreInitEx",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
")",
")",
"else",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreInit",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
")",
")"
] | Initializes a single or a sequence of key-value pairs into the store.
For each key, one must `init` it before calling `push` or `pull`.
When multiple workers invoke `init` for the same key, only
the value supplied by worker with rank `0` is used. This function returns
after data has been initialized successfully.
Parameters
----------
key : str, int, or sequence of str or int
The keys.
value : NDArray, RowSparseNDArray or sequence of NDArray or RowSparseNDArray
Values corresponding to the keys.
Examples
--------
>>> # init a single key-value pair
>>> shape = (2,3)
>>> kv = mx.kv.create('local')
>>> kv.init('3', mx.nd.ones(shape)*2)
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # init a list of key-value pairs
>>> keys = ['5', '7', '9']
>>> kv.init(keys, [mx.nd.ones(shape)]*len(keys))
>>> # init a row_sparse value
>>> kv.init('4', mx.nd.ones(shape).tostype('row_sparse'))
>>> b = mx.nd.sparse.zeros('row_sparse', shape)
>>> kv.row_sparse_pull('4', row_ids=mx.nd.array([0, 1]), out=b)
>>> print b
<RowSparseNDArray 2x3 @cpu(0)> | [
"Initializes",
"a",
"single",
"or",
"a",
"sequence",
"of",
"key",
"-",
"value",
"pairs",
"into",
"the",
"store",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L116-L158 |
23,430 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.push | def push(self, key, value, priority=0):
""" Pushes a single or a sequence of key-value pairs into the store.
This function returns immediately after adding an operator to the engine.
The actual operation is executed asynchronously. If there are consecutive
pushes to the same key, there is no guarantee on the serialization of pushes.
The execution of a push does not guarantee that all previous pushes are
finished.
There is no synchronization between workers.
One can use ``_barrier()`` to sync all workers.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
value : NDArray, RowSparseNDArray, list of NDArray or RowSparseNDArray,
or list of list of NDArray or RowSparseNDArray
Values corresponding to the keys.
priority : int, optional
The priority of the push operation.
Higher priority push operations are likely to be executed before
other push actions.
Examples
--------
>>> # push a single key-value pair
>>> kv.push('3', mx.nd.ones(shape)*8)
>>> kv.pull('3', out=a) # pull out the value
>>> print a.asnumpy()
[[ 8. 8. 8.]
[ 8. 8. 8.]]
>>> # aggregate the value and the push
>>> gpus = [mx.gpu(i) for i in range(4)]
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.push('3', b)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> # push a list of keys.
>>> # single device
>>> keys = ['4', '5', '6']
>>> kv.push(keys, [mx.nd.ones(shape)]*len(keys))
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 1. 1. 1.]
[ 1. 1. 1.]]
>>> # multiple devices:
>>> keys = ['7', '8', '9']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.push(keys, b)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> # push a row_sparse value
>>> b = mx.nd.sparse.zeros('row_sparse', shape)
>>> kv.init('10', mx.nd.sparse.zeros('row_sparse', shape))
>>> kv.push('10', mx.nd.ones(shape).tostype('row_sparse'))
>>> # pull out the value
>>> kv.row_sparse_pull('10', row_ids=mx.nd.array([0, 1]), out=b)
>>> print b
<RowSparseNDArray 2x3 @cpu(0)>
"""
ckeys, cvals, use_str_keys = _ctype_key_value(key, value)
if use_str_keys:
check_call(_LIB.MXKVStorePushEx(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority)))
else:
check_call(_LIB.MXKVStorePush(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority))) | python | def push(self, key, value, priority=0):
""" Pushes a single or a sequence of key-value pairs into the store.
This function returns immediately after adding an operator to the engine.
The actual operation is executed asynchronously. If there are consecutive
pushes to the same key, there is no guarantee on the serialization of pushes.
The execution of a push does not guarantee that all previous pushes are
finished.
There is no synchronization between workers.
One can use ``_barrier()`` to sync all workers.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
value : NDArray, RowSparseNDArray, list of NDArray or RowSparseNDArray,
or list of list of NDArray or RowSparseNDArray
Values corresponding to the keys.
priority : int, optional
The priority of the push operation.
Higher priority push operations are likely to be executed before
other push actions.
Examples
--------
>>> # push a single key-value pair
>>> kv.push('3', mx.nd.ones(shape)*8)
>>> kv.pull('3', out=a) # pull out the value
>>> print a.asnumpy()
[[ 8. 8. 8.]
[ 8. 8. 8.]]
>>> # aggregate the value and the push
>>> gpus = [mx.gpu(i) for i in range(4)]
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.push('3', b)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> # push a list of keys.
>>> # single device
>>> keys = ['4', '5', '6']
>>> kv.push(keys, [mx.nd.ones(shape)]*len(keys))
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 1. 1. 1.]
[ 1. 1. 1.]]
>>> # multiple devices:
>>> keys = ['7', '8', '9']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.push(keys, b)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> # push a row_sparse value
>>> b = mx.nd.sparse.zeros('row_sparse', shape)
>>> kv.init('10', mx.nd.sparse.zeros('row_sparse', shape))
>>> kv.push('10', mx.nd.ones(shape).tostype('row_sparse'))
>>> # pull out the value
>>> kv.row_sparse_pull('10', row_ids=mx.nd.array([0, 1]), out=b)
>>> print b
<RowSparseNDArray 2x3 @cpu(0)>
"""
ckeys, cvals, use_str_keys = _ctype_key_value(key, value)
if use_str_keys:
check_call(_LIB.MXKVStorePushEx(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority)))
else:
check_call(_LIB.MXKVStorePush(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority))) | [
"def",
"push",
"(",
"self",
",",
"key",
",",
"value",
",",
"priority",
"=",
"0",
")",
":",
"ckeys",
",",
"cvals",
",",
"use_str_keys",
"=",
"_ctype_key_value",
"(",
"key",
",",
"value",
")",
"if",
"use_str_keys",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePushEx",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
")",
")",
"else",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePush",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
")",
")"
] | Pushes a single or a sequence of key-value pairs into the store.
This function returns immediately after adding an operator to the engine.
The actual operation is executed asynchronously. If there are consecutive
pushes to the same key, there is no guarantee on the serialization of pushes.
The execution of a push does not guarantee that all previous pushes are
finished.
There is no synchronization between workers.
One can use ``_barrier()`` to sync all workers.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
value : NDArray, RowSparseNDArray, list of NDArray or RowSparseNDArray,
or list of list of NDArray or RowSparseNDArray
Values corresponding to the keys.
priority : int, optional
The priority of the push operation.
Higher priority push operations are likely to be executed before
other push actions.
Examples
--------
>>> # push a single key-value pair
>>> kv.push('3', mx.nd.ones(shape)*8)
>>> kv.pull('3', out=a) # pull out the value
>>> print a.asnumpy()
[[ 8. 8. 8.]
[ 8. 8. 8.]]
>>> # aggregate the value and the push
>>> gpus = [mx.gpu(i) for i in range(4)]
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.push('3', b)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> # push a list of keys.
>>> # single device
>>> keys = ['4', '5', '6']
>>> kv.push(keys, [mx.nd.ones(shape)]*len(keys))
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 1. 1. 1.]
[ 1. 1. 1.]]
>>> # multiple devices:
>>> keys = ['7', '8', '9']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.push(keys, b)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> # push a row_sparse value
>>> b = mx.nd.sparse.zeros('row_sparse', shape)
>>> kv.init('10', mx.nd.sparse.zeros('row_sparse', shape))
>>> kv.push('10', mx.nd.ones(shape).tostype('row_sparse'))
>>> # pull out the value
>>> kv.row_sparse_pull('10', row_ids=mx.nd.array([0, 1]), out=b)
>>> print b
<RowSparseNDArray 2x3 @cpu(0)> | [
"Pushes",
"a",
"single",
"or",
"a",
"sequence",
"of",
"key",
"-",
"value",
"pairs",
"into",
"the",
"store",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L160-L237 |
23,431 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.pull | def pull(self, key, out=None, priority=0, ignore_sparse=True):
""" Pulls a single value or a sequence of values from the store.
This function returns immediately after adding an operator to the engine.
Subsequent attempts to read from the `out` variable will be blocked until the
pull operation completes.
`pull` is executed asynchronously after all previous `pull` calls and only
the last `push` call for the same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
pull with `RowSparseNDArray` is not supported for dist kvstore.
Please use ``row_sparse_pull`` instead.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: NDArray or list of NDArray or list of list of NDArray
Values corresponding to the keys.
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
ignore_sparse: bool, optional, default True
Whether to ignore sparse arrays in the request.
Examples
--------
>>> # pull a single key-value pair
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull into multiple devices
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.pull('3', out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull a list of key-value pairs.
>>> # On single device
>>> keys = ['5', '7', '9']
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # On multiple devices
>>> keys = ['6', '8', '10']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
"""
assert(out is not None)
ckeys, cvals, use_str_keys = _ctype_key_value(key, out)
if use_str_keys:
check_call(_LIB.MXKVStorePullWithSparseEx(self.handle, mx_uint(len(ckeys)), ckeys,
cvals, ctypes.c_int(priority),
ctypes.c_bool(ignore_sparse)))
else:
check_call(_LIB.MXKVStorePullWithSparse(self.handle, mx_uint(len(ckeys)), ckeys,
cvals, ctypes.c_int(priority),
ctypes.c_bool(ignore_sparse))) | python | def pull(self, key, out=None, priority=0, ignore_sparse=True):
""" Pulls a single value or a sequence of values from the store.
This function returns immediately after adding an operator to the engine.
Subsequent attempts to read from the `out` variable will be blocked until the
pull operation completes.
`pull` is executed asynchronously after all previous `pull` calls and only
the last `push` call for the same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
pull with `RowSparseNDArray` is not supported for dist kvstore.
Please use ``row_sparse_pull`` instead.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: NDArray or list of NDArray or list of list of NDArray
Values corresponding to the keys.
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
ignore_sparse: bool, optional, default True
Whether to ignore sparse arrays in the request.
Examples
--------
>>> # pull a single key-value pair
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull into multiple devices
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.pull('3', out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull a list of key-value pairs.
>>> # On single device
>>> keys = ['5', '7', '9']
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # On multiple devices
>>> keys = ['6', '8', '10']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
"""
assert(out is not None)
ckeys, cvals, use_str_keys = _ctype_key_value(key, out)
if use_str_keys:
check_call(_LIB.MXKVStorePullWithSparseEx(self.handle, mx_uint(len(ckeys)), ckeys,
cvals, ctypes.c_int(priority),
ctypes.c_bool(ignore_sparse)))
else:
check_call(_LIB.MXKVStorePullWithSparse(self.handle, mx_uint(len(ckeys)), ckeys,
cvals, ctypes.c_int(priority),
ctypes.c_bool(ignore_sparse))) | [
"def",
"pull",
"(",
"self",
",",
"key",
",",
"out",
"=",
"None",
",",
"priority",
"=",
"0",
",",
"ignore_sparse",
"=",
"True",
")",
":",
"assert",
"(",
"out",
"is",
"not",
"None",
")",
"ckeys",
",",
"cvals",
",",
"use_str_keys",
"=",
"_ctype_key_value",
"(",
"key",
",",
"out",
")",
"if",
"use_str_keys",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePullWithSparseEx",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
",",
"ctypes",
".",
"c_bool",
"(",
"ignore_sparse",
")",
")",
")",
"else",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePullWithSparse",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
",",
"ctypes",
".",
"c_bool",
"(",
"ignore_sparse",
")",
")",
")"
] | Pulls a single value or a sequence of values from the store.
This function returns immediately after adding an operator to the engine.
Subsequent attempts to read from the `out` variable will be blocked until the
pull operation completes.
`pull` is executed asynchronously after all previous `pull` calls and only
the last `push` call for the same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
pull with `RowSparseNDArray` is not supported for dist kvstore.
Please use ``row_sparse_pull`` instead.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: NDArray or list of NDArray or list of list of NDArray
Values corresponding to the keys.
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
ignore_sparse: bool, optional, default True
Whether to ignore sparse arrays in the request.
Examples
--------
>>> # pull a single key-value pair
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull into multiple devices
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.pull('3', out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull a list of key-value pairs.
>>> # On single device
>>> keys = ['5', '7', '9']
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # On multiple devices
>>> keys = ['6', '8', '10']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]] | [
"Pulls",
"a",
"single",
"value",
"or",
"a",
"sequence",
"of",
"values",
"from",
"the",
"store",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L240-L312 |
23,432 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.row_sparse_pull | def row_sparse_pull(self, key, out=None, priority=0, row_ids=None):
""" Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \
from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \
is invoked just once and the result is broadcast to all the rest of outputs.
`row_sparse_pull` is executed asynchronously after all previous
`pull`/`row_sparse_pull` calls and the last `push` call for the
same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: RowSparseNDArray or list of RowSparseNDArray or list of list of RowSparseNDArray
Values corresponding to the keys. The stype is expected to be row_sparse
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
row_ids : NDArray or list of NDArray
The row_ids for which to pull for each value. Each row_id is an 1-D NDArray \
whose values don't have to be unique nor sorted.
Examples
--------
>>> shape = (3, 3)
>>> kv.init('3', mx.nd.ones(shape).tostype('row_sparse'))
>>> a = mx.nd.sparse.zeros('row_sparse', shape)
>>> row_ids = mx.nd.array([0, 2], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=row_ids)
>>> print a.asnumpy()
[[ 1. 1. 1.]
[ 0. 0. 0.]
[ 1. 1. 1.]]
>>> duplicate_row_ids = mx.nd.array([2, 2], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=duplicate_row_ids)
>>> print a.asnumpy()
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 1. 1. 1.]]
>>> unsorted_row_ids = mx.nd.array([1, 0], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=unsorted_row_ids)
>>> print a.asnumpy()
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 0. 0. 0.]]
"""
assert(out is not None)
assert(row_ids is not None)
if isinstance(row_ids, NDArray):
row_ids = [row_ids]
assert(isinstance(row_ids, list)), \
"row_ids should be NDArray or list of NDArray"
first_out = out
# whether row_ids are the same
single_rowid = False
if len(row_ids) == 1 and isinstance(out, list):
single_rowid = True
first_out = [out[0]]
ckeys, cvals, use_str_keys = _ctype_key_value(key, first_out)
_, crow_ids, _ = _ctype_key_value(key, row_ids)
assert(len(crow_ids) == len(cvals)), \
"the number of row_ids doesn't match the number of values"
if use_str_keys:
check_call(_LIB.MXKVStorePullRowSparseEx(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, crow_ids, ctypes.c_int(priority)))
else:
check_call(_LIB.MXKVStorePullRowSparse(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, crow_ids, ctypes.c_int(priority)))
# the result can be copied to other devices without invoking row_sparse_pull
# if the indices are the same
if single_rowid:
for out_i in out[1:]:
out[0].copyto(out_i) | python | def row_sparse_pull(self, key, out=None, priority=0, row_ids=None):
""" Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \
from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \
is invoked just once and the result is broadcast to all the rest of outputs.
`row_sparse_pull` is executed asynchronously after all previous
`pull`/`row_sparse_pull` calls and the last `push` call for the
same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: RowSparseNDArray or list of RowSparseNDArray or list of list of RowSparseNDArray
Values corresponding to the keys. The stype is expected to be row_sparse
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
row_ids : NDArray or list of NDArray
The row_ids for which to pull for each value. Each row_id is an 1-D NDArray \
whose values don't have to be unique nor sorted.
Examples
--------
>>> shape = (3, 3)
>>> kv.init('3', mx.nd.ones(shape).tostype('row_sparse'))
>>> a = mx.nd.sparse.zeros('row_sparse', shape)
>>> row_ids = mx.nd.array([0, 2], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=row_ids)
>>> print a.asnumpy()
[[ 1. 1. 1.]
[ 0. 0. 0.]
[ 1. 1. 1.]]
>>> duplicate_row_ids = mx.nd.array([2, 2], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=duplicate_row_ids)
>>> print a.asnumpy()
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 1. 1. 1.]]
>>> unsorted_row_ids = mx.nd.array([1, 0], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=unsorted_row_ids)
>>> print a.asnumpy()
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 0. 0. 0.]]
"""
assert(out is not None)
assert(row_ids is not None)
if isinstance(row_ids, NDArray):
row_ids = [row_ids]
assert(isinstance(row_ids, list)), \
"row_ids should be NDArray or list of NDArray"
first_out = out
# whether row_ids are the same
single_rowid = False
if len(row_ids) == 1 and isinstance(out, list):
single_rowid = True
first_out = [out[0]]
ckeys, cvals, use_str_keys = _ctype_key_value(key, first_out)
_, crow_ids, _ = _ctype_key_value(key, row_ids)
assert(len(crow_ids) == len(cvals)), \
"the number of row_ids doesn't match the number of values"
if use_str_keys:
check_call(_LIB.MXKVStorePullRowSparseEx(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, crow_ids, ctypes.c_int(priority)))
else:
check_call(_LIB.MXKVStorePullRowSparse(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, crow_ids, ctypes.c_int(priority)))
# the result can be copied to other devices without invoking row_sparse_pull
# if the indices are the same
if single_rowid:
for out_i in out[1:]:
out[0].copyto(out_i) | [
"def",
"row_sparse_pull",
"(",
"self",
",",
"key",
",",
"out",
"=",
"None",
",",
"priority",
"=",
"0",
",",
"row_ids",
"=",
"None",
")",
":",
"assert",
"(",
"out",
"is",
"not",
"None",
")",
"assert",
"(",
"row_ids",
"is",
"not",
"None",
")",
"if",
"isinstance",
"(",
"row_ids",
",",
"NDArray",
")",
":",
"row_ids",
"=",
"[",
"row_ids",
"]",
"assert",
"(",
"isinstance",
"(",
"row_ids",
",",
"list",
")",
")",
",",
"\"row_ids should be NDArray or list of NDArray\"",
"first_out",
"=",
"out",
"# whether row_ids are the same",
"single_rowid",
"=",
"False",
"if",
"len",
"(",
"row_ids",
")",
"==",
"1",
"and",
"isinstance",
"(",
"out",
",",
"list",
")",
":",
"single_rowid",
"=",
"True",
"first_out",
"=",
"[",
"out",
"[",
"0",
"]",
"]",
"ckeys",
",",
"cvals",
",",
"use_str_keys",
"=",
"_ctype_key_value",
"(",
"key",
",",
"first_out",
")",
"_",
",",
"crow_ids",
",",
"_",
"=",
"_ctype_key_value",
"(",
"key",
",",
"row_ids",
")",
"assert",
"(",
"len",
"(",
"crow_ids",
")",
"==",
"len",
"(",
"cvals",
")",
")",
",",
"\"the number of row_ids doesn't match the number of values\"",
"if",
"use_str_keys",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePullRowSparseEx",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"crow_ids",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
")",
")",
"else",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePullRowSparse",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"crow_ids",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
")",
")",
"# the result can be copied to other devices without invoking row_sparse_pull",
"# if the indices are the same",
"if",
"single_rowid",
":",
"for",
"out_i",
"in",
"out",
"[",
"1",
":",
"]",
":",
"out",
"[",
"0",
"]",
".",
"copyto",
"(",
"out_i",
")"
] | Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \
from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \
is invoked just once and the result is broadcast to all the rest of outputs.
`row_sparse_pull` is executed asynchronously after all previous
`pull`/`row_sparse_pull` calls and the last `push` call for the
same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: RowSparseNDArray or list of RowSparseNDArray or list of list of RowSparseNDArray
Values corresponding to the keys. The stype is expected to be row_sparse
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
row_ids : NDArray or list of NDArray
The row_ids for which to pull for each value. Each row_id is an 1-D NDArray \
whose values don't have to be unique nor sorted.
Examples
--------
>>> shape = (3, 3)
>>> kv.init('3', mx.nd.ones(shape).tostype('row_sparse'))
>>> a = mx.nd.sparse.zeros('row_sparse', shape)
>>> row_ids = mx.nd.array([0, 2], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=row_ids)
>>> print a.asnumpy()
[[ 1. 1. 1.]
[ 0. 0. 0.]
[ 1. 1. 1.]]
>>> duplicate_row_ids = mx.nd.array([2, 2], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=duplicate_row_ids)
>>> print a.asnumpy()
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 1. 1. 1.]]
>>> unsorted_row_ids = mx.nd.array([1, 0], dtype='int64')
>>> kv.row_sparse_pull('3', out=a, row_ids=unsorted_row_ids)
>>> print a.asnumpy()
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 0. 0. 0.]] | [
"Pulls",
"a",
"single",
"RowSparseNDArray",
"value",
"or",
"a",
"sequence",
"of",
"RowSparseNDArray",
"values",
"\\",
"from",
"the",
"store",
"with",
"specified",
"row_ids",
".",
"When",
"there",
"is",
"only",
"one",
"row_id",
"KVStoreRowSparsePull",
"\\",
"is",
"invoked",
"just",
"once",
"and",
"the",
"result",
"is",
"broadcast",
"to",
"all",
"the",
"rest",
"of",
"outputs",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L314-L392 |
23,433 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.set_gradient_compression | def set_gradient_compression(self, compression_params):
""" Specifies type of low-bit quantization for gradient compression \
and additional arguments depending on the type of compression being used.
2bit Gradient Compression takes a positive float `threshold`.
The technique works by thresholding values such that positive values in the
gradient above threshold will be set to threshold. Negative values whose absolute
values are higher than threshold, will be set to the negative of threshold.
Values whose absolute values are less than threshold will be set to 0.
By doing so, each value in the gradient is in one of three states. 2bits are
used to represent these states, and every 16 float values in the original
gradient can be represented using one float. This compressed representation
can reduce communication costs. The difference between these thresholded values and
original values is stored at the sender's end as residual and added to the
gradient in the next iteration.
When kvstore is 'local', gradient compression is used to reduce communication
between multiple devices (gpus). Gradient is quantized on each GPU which
computed the gradients, then sent to the GPU which merges the gradients. This
receiving GPU dequantizes the gradients and merges them. Note that this
increases memory usage on each GPU because of the residual array stored.
When kvstore is 'dist', gradient compression is used to reduce communication
from worker to sender. Gradient is quantized on each worker which
computed the gradients, then sent to the server which dequantizes
this data and merges the gradients from each worker. Note that this
increases CPU memory usage on each worker because of the residual array stored.
Only worker to server communication is compressed in this setting.
If each machine has multiple GPUs, currently this GPU to GPU or GPU to CPU communication
is not compressed. Server to worker communication (in the case of pull)
is also not compressed.
To use 2bit compression, we need to specify `type` as `2bit`.
Only specifying `type` would use default value for the threshold.
To completely specify the arguments for 2bit compression, we would need to pass
a dictionary which includes `threshold` like:
{'type': '2bit', 'threshold': 0.5}
Parameters
----------
compression_params : dict
A dictionary specifying the type and parameters for gradient compression.
The key `type` in this dictionary is a
required string argument and specifies the type of gradient compression.
Currently `type` can be only `2bit`
Other keys in this dictionary are optional and specific to the type
of gradient compression.
"""
if ('device' in self.type) or ('dist' in self.type): # pylint: disable=unsupported-membership-test
ckeys, cvals = _ctype_dict(compression_params)
check_call(_LIB.MXKVStoreSetGradientCompression(self.handle,
mx_uint(len(compression_params)),
ckeys, cvals))
else:
raise Exception('Gradient compression is not supported for this type of kvstore') | python | def set_gradient_compression(self, compression_params):
""" Specifies type of low-bit quantization for gradient compression \
and additional arguments depending on the type of compression being used.
2bit Gradient Compression takes a positive float `threshold`.
The technique works by thresholding values such that positive values in the
gradient above threshold will be set to threshold. Negative values whose absolute
values are higher than threshold, will be set to the negative of threshold.
Values whose absolute values are less than threshold will be set to 0.
By doing so, each value in the gradient is in one of three states. 2bits are
used to represent these states, and every 16 float values in the original
gradient can be represented using one float. This compressed representation
can reduce communication costs. The difference between these thresholded values and
original values is stored at the sender's end as residual and added to the
gradient in the next iteration.
When kvstore is 'local', gradient compression is used to reduce communication
between multiple devices (gpus). Gradient is quantized on each GPU which
computed the gradients, then sent to the GPU which merges the gradients. This
receiving GPU dequantizes the gradients and merges them. Note that this
increases memory usage on each GPU because of the residual array stored.
When kvstore is 'dist', gradient compression is used to reduce communication
from worker to sender. Gradient is quantized on each worker which
computed the gradients, then sent to the server which dequantizes
this data and merges the gradients from each worker. Note that this
increases CPU memory usage on each worker because of the residual array stored.
Only worker to server communication is compressed in this setting.
If each machine has multiple GPUs, currently this GPU to GPU or GPU to CPU communication
is not compressed. Server to worker communication (in the case of pull)
is also not compressed.
To use 2bit compression, we need to specify `type` as `2bit`.
Only specifying `type` would use default value for the threshold.
To completely specify the arguments for 2bit compression, we would need to pass
a dictionary which includes `threshold` like:
{'type': '2bit', 'threshold': 0.5}
Parameters
----------
compression_params : dict
A dictionary specifying the type and parameters for gradient compression.
The key `type` in this dictionary is a
required string argument and specifies the type of gradient compression.
Currently `type` can be only `2bit`
Other keys in this dictionary are optional and specific to the type
of gradient compression.
"""
if ('device' in self.type) or ('dist' in self.type): # pylint: disable=unsupported-membership-test
ckeys, cvals = _ctype_dict(compression_params)
check_call(_LIB.MXKVStoreSetGradientCompression(self.handle,
mx_uint(len(compression_params)),
ckeys, cvals))
else:
raise Exception('Gradient compression is not supported for this type of kvstore') | [
"def",
"set_gradient_compression",
"(",
"self",
",",
"compression_params",
")",
":",
"if",
"(",
"'device'",
"in",
"self",
".",
"type",
")",
"or",
"(",
"'dist'",
"in",
"self",
".",
"type",
")",
":",
"# pylint: disable=unsupported-membership-test",
"ckeys",
",",
"cvals",
"=",
"_ctype_dict",
"(",
"compression_params",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreSetGradientCompression",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"compression_params",
")",
")",
",",
"ckeys",
",",
"cvals",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Gradient compression is not supported for this type of kvstore'",
")"
] | Specifies type of low-bit quantization for gradient compression \
and additional arguments depending on the type of compression being used.
2bit Gradient Compression takes a positive float `threshold`.
The technique works by thresholding values such that positive values in the
gradient above threshold will be set to threshold. Negative values whose absolute
values are higher than threshold, will be set to the negative of threshold.
Values whose absolute values are less than threshold will be set to 0.
By doing so, each value in the gradient is in one of three states. 2bits are
used to represent these states, and every 16 float values in the original
gradient can be represented using one float. This compressed representation
can reduce communication costs. The difference between these thresholded values and
original values is stored at the sender's end as residual and added to the
gradient in the next iteration.
When kvstore is 'local', gradient compression is used to reduce communication
between multiple devices (gpus). Gradient is quantized on each GPU which
computed the gradients, then sent to the GPU which merges the gradients. This
receiving GPU dequantizes the gradients and merges them. Note that this
increases memory usage on each GPU because of the residual array stored.
When kvstore is 'dist', gradient compression is used to reduce communication
from worker to sender. Gradient is quantized on each worker which
computed the gradients, then sent to the server which dequantizes
this data and merges the gradients from each worker. Note that this
increases CPU memory usage on each worker because of the residual array stored.
Only worker to server communication is compressed in this setting.
If each machine has multiple GPUs, currently this GPU to GPU or GPU to CPU communication
is not compressed. Server to worker communication (in the case of pull)
is also not compressed.
To use 2bit compression, we need to specify `type` as `2bit`.
Only specifying `type` would use default value for the threshold.
To completely specify the arguments for 2bit compression, we would need to pass
a dictionary which includes `threshold` like:
{'type': '2bit', 'threshold': 0.5}
Parameters
----------
compression_params : dict
A dictionary specifying the type and parameters for gradient compression.
The key `type` in this dictionary is a
required string argument and specifies the type of gradient compression.
Currently `type` can be only `2bit`
Other keys in this dictionary are optional and specific to the type
of gradient compression. | [
"Specifies",
"type",
"of",
"low",
"-",
"bit",
"quantization",
"for",
"gradient",
"compression",
"\\",
"and",
"additional",
"arguments",
"depending",
"on",
"the",
"type",
"of",
"compression",
"being",
"used",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L394-L448 |
23,434 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.set_optimizer | def set_optimizer(self, optimizer):
""" Registers an optimizer with the kvstore.
When using a single machine, this function updates the local optimizer.
If using multiple machines and this operation is invoked from a worker node,
it will serialized the optimizer with pickle and send it to all servers.
The function returns after all servers have been updated.
Parameters
----------
optimizer : Optimizer
The new optimizer for the store
Examples
--------
>>> kv = mx.kv.create()
>>> shape = (2, 2)
>>> weight = mx.nd.zeros(shape)
>>> kv.init(3, weight)
>>> # set the optimizer for kvstore as the default SGD optimizer
>>> kv.set_optimizer(mx.optimizer.SGD())
>>> grad = mx.nd.ones(shape)
>>> kv.push(3, grad)
>>> kv.pull(3, out = weight)
>>> # weight is updated via gradient descent
>>> weight.asnumpy()
array([[-0.01, -0.01],
[-0.01, -0.01]], dtype=float32)
"""
is_worker = ctypes.c_int()
check_call(_LIB.MXKVStoreIsWorkerNode(ctypes.byref(is_worker)))
# pylint: disable=invalid-name
if 'dist' in self.type and is_worker.value: # pylint: disable=unsupported-membership-test
# send the optimizer to server
try:
# use ASCII protocol 0, might be slower, but not a big ideal
optim_str = py_str(pickle.dumps(optimizer, 0))
except:
raise
cmd = _get_kvstore_server_command_type('kController')
self._send_command_to_servers(cmd, optim_str)
if optimizer.multi_precision:
cmd = _get_kvstore_server_command_type('kSetMultiPrecision')
self._send_command_to_servers(cmd, '')
else:
self._set_updater(opt.get_updater(optimizer)) | python | def set_optimizer(self, optimizer):
""" Registers an optimizer with the kvstore.
When using a single machine, this function updates the local optimizer.
If using multiple machines and this operation is invoked from a worker node,
it will serialized the optimizer with pickle and send it to all servers.
The function returns after all servers have been updated.
Parameters
----------
optimizer : Optimizer
The new optimizer for the store
Examples
--------
>>> kv = mx.kv.create()
>>> shape = (2, 2)
>>> weight = mx.nd.zeros(shape)
>>> kv.init(3, weight)
>>> # set the optimizer for kvstore as the default SGD optimizer
>>> kv.set_optimizer(mx.optimizer.SGD())
>>> grad = mx.nd.ones(shape)
>>> kv.push(3, grad)
>>> kv.pull(3, out = weight)
>>> # weight is updated via gradient descent
>>> weight.asnumpy()
array([[-0.01, -0.01],
[-0.01, -0.01]], dtype=float32)
"""
is_worker = ctypes.c_int()
check_call(_LIB.MXKVStoreIsWorkerNode(ctypes.byref(is_worker)))
# pylint: disable=invalid-name
if 'dist' in self.type and is_worker.value: # pylint: disable=unsupported-membership-test
# send the optimizer to server
try:
# use ASCII protocol 0, might be slower, but not a big ideal
optim_str = py_str(pickle.dumps(optimizer, 0))
except:
raise
cmd = _get_kvstore_server_command_type('kController')
self._send_command_to_servers(cmd, optim_str)
if optimizer.multi_precision:
cmd = _get_kvstore_server_command_type('kSetMultiPrecision')
self._send_command_to_servers(cmd, '')
else:
self._set_updater(opt.get_updater(optimizer)) | [
"def",
"set_optimizer",
"(",
"self",
",",
"optimizer",
")",
":",
"is_worker",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreIsWorkerNode",
"(",
"ctypes",
".",
"byref",
"(",
"is_worker",
")",
")",
")",
"# pylint: disable=invalid-name",
"if",
"'dist'",
"in",
"self",
".",
"type",
"and",
"is_worker",
".",
"value",
":",
"# pylint: disable=unsupported-membership-test",
"# send the optimizer to server",
"try",
":",
"# use ASCII protocol 0, might be slower, but not a big ideal",
"optim_str",
"=",
"py_str",
"(",
"pickle",
".",
"dumps",
"(",
"optimizer",
",",
"0",
")",
")",
"except",
":",
"raise",
"cmd",
"=",
"_get_kvstore_server_command_type",
"(",
"'kController'",
")",
"self",
".",
"_send_command_to_servers",
"(",
"cmd",
",",
"optim_str",
")",
"if",
"optimizer",
".",
"multi_precision",
":",
"cmd",
"=",
"_get_kvstore_server_command_type",
"(",
"'kSetMultiPrecision'",
")",
"self",
".",
"_send_command_to_servers",
"(",
"cmd",
",",
"''",
")",
"else",
":",
"self",
".",
"_set_updater",
"(",
"opt",
".",
"get_updater",
"(",
"optimizer",
")",
")"
] | Registers an optimizer with the kvstore.
When using a single machine, this function updates the local optimizer.
If using multiple machines and this operation is invoked from a worker node,
it will serialized the optimizer with pickle and send it to all servers.
The function returns after all servers have been updated.
Parameters
----------
optimizer : Optimizer
The new optimizer for the store
Examples
--------
>>> kv = mx.kv.create()
>>> shape = (2, 2)
>>> weight = mx.nd.zeros(shape)
>>> kv.init(3, weight)
>>> # set the optimizer for kvstore as the default SGD optimizer
>>> kv.set_optimizer(mx.optimizer.SGD())
>>> grad = mx.nd.ones(shape)
>>> kv.push(3, grad)
>>> kv.pull(3, out = weight)
>>> # weight is updated via gradient descent
>>> weight.asnumpy()
array([[-0.01, -0.01],
[-0.01, -0.01]], dtype=float32) | [
"Registers",
"an",
"optimizer",
"with",
"the",
"kvstore",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L450-L497 |
23,435 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.type | def type(self):
""" Returns the type of this kvstore.
Returns
-------
type : str
the string type
"""
kv_type = ctypes.c_char_p()
check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type)))
return py_str(kv_type.value) | python | def type(self):
""" Returns the type of this kvstore.
Returns
-------
type : str
the string type
"""
kv_type = ctypes.c_char_p()
check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type)))
return py_str(kv_type.value) | [
"def",
"type",
"(",
"self",
")",
":",
"kv_type",
"=",
"ctypes",
".",
"c_char_p",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreGetType",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"kv_type",
")",
")",
")",
"return",
"py_str",
"(",
"kv_type",
".",
"value",
")"
] | Returns the type of this kvstore.
Returns
-------
type : str
the string type | [
"Returns",
"the",
"type",
"of",
"this",
"kvstore",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L500-L510 |
23,436 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.rank | def rank(self):
""" Returns the rank of this worker node.
Returns
-------
rank : int
The rank of this node, which is in range [0, num_workers())
"""
rank = ctypes.c_int()
check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank)))
return rank.value | python | def rank(self):
""" Returns the rank of this worker node.
Returns
-------
rank : int
The rank of this node, which is in range [0, num_workers())
"""
rank = ctypes.c_int()
check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank)))
return rank.value | [
"def",
"rank",
"(",
"self",
")",
":",
"rank",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreGetRank",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"rank",
")",
")",
")",
"return",
"rank",
".",
"value"
] | Returns the rank of this worker node.
Returns
-------
rank : int
The rank of this node, which is in range [0, num_workers()) | [
"Returns",
"the",
"rank",
"of",
"this",
"worker",
"node",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L513-L523 |
23,437 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore.num_workers | def num_workers(self):
"""Returns the number of worker nodes.
Returns
-------
size :int
The number of worker nodes.
"""
size = ctypes.c_int()
check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size)))
return size.value | python | def num_workers(self):
"""Returns the number of worker nodes.
Returns
-------
size :int
The number of worker nodes.
"""
size = ctypes.c_int()
check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size)))
return size.value | [
"def",
"num_workers",
"(",
"self",
")",
":",
"size",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreGetGroupSize",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"size",
")",
")",
")",
"return",
"size",
".",
"value"
] | Returns the number of worker nodes.
Returns
-------
size :int
The number of worker nodes. | [
"Returns",
"the",
"number",
"of",
"worker",
"nodes",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L526-L536 |
23,438 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore._set_updater | def _set_updater(self, updater):
"""Sets a push updater into the store.
This function only changes the local store. When running on multiple machines one must
use `set_optimizer`.
Parameters
----------
updater : function
The updater function.
Examples
--------
>>> def update(key, input, stored):
... print "update on key: %d" % key
... stored += input * 2
>>> kv._set_updater(update)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> kv.push('3', mx.nd.ones(shape))
update on key: 3
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 6. 6. 6.]
[ 6. 6. 6.]]
"""
self._updater = updater
# set updater with int keys
_updater_proto = ctypes.CFUNCTYPE(
None, ctypes.c_int, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
self._updater_func = _updater_proto(_updater_wrapper(updater))
# set updater with str keys
_str_updater_proto = ctypes.CFUNCTYPE(
None, ctypes.c_char_p, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
self._str_updater_func = _str_updater_proto(_updater_wrapper(updater))
check_call(_LIB.MXKVStoreSetUpdaterEx(self.handle, self._updater_func,
self._str_updater_func, None)) | python | def _set_updater(self, updater):
"""Sets a push updater into the store.
This function only changes the local store. When running on multiple machines one must
use `set_optimizer`.
Parameters
----------
updater : function
The updater function.
Examples
--------
>>> def update(key, input, stored):
... print "update on key: %d" % key
... stored += input * 2
>>> kv._set_updater(update)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> kv.push('3', mx.nd.ones(shape))
update on key: 3
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 6. 6. 6.]
[ 6. 6. 6.]]
"""
self._updater = updater
# set updater with int keys
_updater_proto = ctypes.CFUNCTYPE(
None, ctypes.c_int, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
self._updater_func = _updater_proto(_updater_wrapper(updater))
# set updater with str keys
_str_updater_proto = ctypes.CFUNCTYPE(
None, ctypes.c_char_p, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
self._str_updater_func = _str_updater_proto(_updater_wrapper(updater))
check_call(_LIB.MXKVStoreSetUpdaterEx(self.handle, self._updater_func,
self._str_updater_func, None)) | [
"def",
"_set_updater",
"(",
"self",
",",
"updater",
")",
":",
"self",
".",
"_updater",
"=",
"updater",
"# set updater with int keys",
"_updater_proto",
"=",
"ctypes",
".",
"CFUNCTYPE",
"(",
"None",
",",
"ctypes",
".",
"c_int",
",",
"NDArrayHandle",
",",
"NDArrayHandle",
",",
"ctypes",
".",
"c_void_p",
")",
"self",
".",
"_updater_func",
"=",
"_updater_proto",
"(",
"_updater_wrapper",
"(",
"updater",
")",
")",
"# set updater with str keys",
"_str_updater_proto",
"=",
"ctypes",
".",
"CFUNCTYPE",
"(",
"None",
",",
"ctypes",
".",
"c_char_p",
",",
"NDArrayHandle",
",",
"NDArrayHandle",
",",
"ctypes",
".",
"c_void_p",
")",
"self",
".",
"_str_updater_func",
"=",
"_str_updater_proto",
"(",
"_updater_wrapper",
"(",
"updater",
")",
")",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreSetUpdaterEx",
"(",
"self",
".",
"handle",
",",
"self",
".",
"_updater_func",
",",
"self",
".",
"_str_updater_func",
",",
"None",
")",
")"
] | Sets a push updater into the store.
This function only changes the local store. When running on multiple machines one must
use `set_optimizer`.
Parameters
----------
updater : function
The updater function.
Examples
--------
>>> def update(key, input, stored):
... print "update on key: %d" % key
... stored += input * 2
>>> kv._set_updater(update)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> kv.push('3', mx.nd.ones(shape))
update on key: 3
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 6. 6. 6.]
[ 6. 6. 6.]] | [
"Sets",
"a",
"push",
"updater",
"into",
"the",
"store",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L565-L603 |
23,439 | apache/incubator-mxnet | python/mxnet/kvstore.py | KVStore._send_command_to_servers | def _send_command_to_servers(self, head, body):
"""Sends a command to all server nodes.
Sending command to a server node will cause that server node to invoke
``KVStoreServer.controller`` to execute the command.
This function returns after the command has been executed on all server
nodes.
Parameters
----------
head : int
the head of the command.
body : str
the body of the command.
"""
check_call(_LIB.MXKVStoreSendCommmandToServers(
self.handle, mx_uint(head), c_str(body))) | python | def _send_command_to_servers(self, head, body):
"""Sends a command to all server nodes.
Sending command to a server node will cause that server node to invoke
``KVStoreServer.controller`` to execute the command.
This function returns after the command has been executed on all server
nodes.
Parameters
----------
head : int
the head of the command.
body : str
the body of the command.
"""
check_call(_LIB.MXKVStoreSendCommmandToServers(
self.handle, mx_uint(head), c_str(body))) | [
"def",
"_send_command_to_servers",
"(",
"self",
",",
"head",
",",
"body",
")",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreSendCommmandToServers",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"head",
")",
",",
"c_str",
"(",
"body",
")",
")",
")"
] | Sends a command to all server nodes.
Sending command to a server node will cause that server node to invoke
``KVStoreServer.controller`` to execute the command.
This function returns after the command has been executed on all server
nodes.
Parameters
----------
head : int
the head of the command.
body : str
the body of the command. | [
"Sends",
"a",
"command",
"to",
"all",
"server",
"nodes",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L616-L633 |
23,440 | apache/incubator-mxnet | python/mxnet/module/sequential_module.py | SequentialModule.add | def add(self, module, **kwargs):
"""Add a module to the chain.
Parameters
----------
module : BaseModule
The new module to add.
kwargs : ``**keywords``
All the keyword arguments are saved as meta information
for the added module. The currently known meta includes
- `take_labels`: indicating whether the module expect to
take labels when doing computation. Note any module in
the chain can take labels (not necessarily only the top
most one), and they all take the same labels passed
from the original data batch for the `SequentialModule`.
Returns
-------
self
This function returns `self` to allow us to easily chain a
series of `add` calls.
Examples
--------
>>> # An example of addinging two modules to a chain.
>>> seq_mod = mx.mod.SequentialModule()
>>> seq_mod.add(mod1)
>>> seq_mod.add(mod2)
"""
self._modules.append(module)
# a sanity check to avoid typo
for key in kwargs:
assert key in self._meta_keys, ('Unknown meta "%s", a typo?' % key)
self._metas.append(kwargs)
# after adding new modules, we are reset back to raw states, needs
# to bind, init_params, etc.
self.binded = False
self.params_initialized = False
self.optimizer_initialized = False
return self | python | def add(self, module, **kwargs):
"""Add a module to the chain.
Parameters
----------
module : BaseModule
The new module to add.
kwargs : ``**keywords``
All the keyword arguments are saved as meta information
for the added module. The currently known meta includes
- `take_labels`: indicating whether the module expect to
take labels when doing computation. Note any module in
the chain can take labels (not necessarily only the top
most one), and they all take the same labels passed
from the original data batch for the `SequentialModule`.
Returns
-------
self
This function returns `self` to allow us to easily chain a
series of `add` calls.
Examples
--------
>>> # An example of addinging two modules to a chain.
>>> seq_mod = mx.mod.SequentialModule()
>>> seq_mod.add(mod1)
>>> seq_mod.add(mod2)
"""
self._modules.append(module)
# a sanity check to avoid typo
for key in kwargs:
assert key in self._meta_keys, ('Unknown meta "%s", a typo?' % key)
self._metas.append(kwargs)
# after adding new modules, we are reset back to raw states, needs
# to bind, init_params, etc.
self.binded = False
self.params_initialized = False
self.optimizer_initialized = False
return self | [
"def",
"add",
"(",
"self",
",",
"module",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_modules",
".",
"append",
"(",
"module",
")",
"# a sanity check to avoid typo",
"for",
"key",
"in",
"kwargs",
":",
"assert",
"key",
"in",
"self",
".",
"_meta_keys",
",",
"(",
"'Unknown meta \"%s\", a typo?'",
"%",
"key",
")",
"self",
".",
"_metas",
".",
"append",
"(",
"kwargs",
")",
"# after adding new modules, we are reset back to raw states, needs",
"# to bind, init_params, etc.",
"self",
".",
"binded",
"=",
"False",
"self",
".",
"params_initialized",
"=",
"False",
"self",
".",
"optimizer_initialized",
"=",
"False",
"return",
"self"
] | Add a module to the chain.
Parameters
----------
module : BaseModule
The new module to add.
kwargs : ``**keywords``
All the keyword arguments are saved as meta information
for the added module. The currently known meta includes
- `take_labels`: indicating whether the module expect to
take labels when doing computation. Note any module in
the chain can take labels (not necessarily only the top
most one), and they all take the same labels passed
from the original data batch for the `SequentialModule`.
Returns
-------
self
This function returns `self` to allow us to easily chain a
series of `add` calls.
Examples
--------
>>> # An example of addinging two modules to a chain.
>>> seq_mod = mx.mod.SequentialModule()
>>> seq_mod.add(mod1)
>>> seq_mod.add(mod2) | [
"Add",
"a",
"module",
"to",
"the",
"chain",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L52-L97 |
23,441 | apache/incubator-mxnet | python/mxnet/module/sequential_module.py | SequentialModule.install_monitor | def install_monitor(self, mon):
"""Installs monitor on all executors."""
assert self.binded
for module in self._modules:
module.install_monitor(mon) | python | def install_monitor(self, mon):
"""Installs monitor on all executors."""
assert self.binded
for module in self._modules:
module.install_monitor(mon) | [
"def",
"install_monitor",
"(",
"self",
",",
"mon",
")",
":",
"assert",
"self",
".",
"binded",
"for",
"module",
"in",
"self",
".",
"_modules",
":",
"module",
".",
"install_monitor",
"(",
"mon",
")"
] | Installs monitor on all executors. | [
"Installs",
"monitor",
"on",
"all",
"executors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L436-L440 |
23,442 | apache/incubator-mxnet | example/caffe/data.py | get_iterator | def get_iterator(data_shape, use_caffe_data):
"""Generate the iterator of mnist dataset"""
def get_iterator_impl_mnist(args, kv):
"""return train and val iterators for mnist"""
# download data
get_mnist_ubyte()
flat = False if len(data_shape) != 1 else True
train = mx.io.MNISTIter(
image="data/train-images-idx3-ubyte",
label="data/train-labels-idx1-ubyte",
input_shape=data_shape,
batch_size=args.batch_size,
shuffle=True,
flat=flat,
num_parts=kv.num_workers,
part_index=kv.rank)
val = mx.io.MNISTIter(
image="data/t10k-images-idx3-ubyte",
label="data/t10k-labels-idx1-ubyte",
input_shape=data_shape,
batch_size=args.batch_size,
flat=flat,
num_parts=kv.num_workers,
part_index=kv.rank)
return (train, val)
def get_iterator_impl_caffe(args, kv):
flat = False if len(data_shape) != 1 else True
train = mx.io.CaffeDataIter(
prototxt=
'layer { \
name: "mnist" \
type: "Data" \
top: "data" \
top: "label" \
include { \
phase: TRAIN \
} \
transform_param { \
scale: 0.00390625 \
} \
data_param { \
source: "mnist_train_lmdb" \
batch_size: 64 \
backend: LMDB \
} \
}',
flat=flat,
num_examples=60000
# float32 is the default, so left out here in order to illustrate
)
val = mx.io.CaffeDataIter(
prototxt=
'layer { \
name: "mnist" \
type: "Data" \
top: "data" \
top: "label" \
include { \
phase: TEST \
} \
transform_param { \
scale: 0.00390625 \
} \
data_param { \
source: "mnist_test_lmdb" \
batch_size: 100 \
backend: LMDB \
} \
}',
flat=flat,
num_examples=10000,
dtype="float32" # float32 is the default
)
return train, val
if use_caffe_data:
return get_iterator_impl_caffe
else:
return get_iterator_impl_mnist | python | def get_iterator(data_shape, use_caffe_data):
"""Generate the iterator of mnist dataset"""
def get_iterator_impl_mnist(args, kv):
"""return train and val iterators for mnist"""
# download data
get_mnist_ubyte()
flat = False if len(data_shape) != 1 else True
train = mx.io.MNISTIter(
image="data/train-images-idx3-ubyte",
label="data/train-labels-idx1-ubyte",
input_shape=data_shape,
batch_size=args.batch_size,
shuffle=True,
flat=flat,
num_parts=kv.num_workers,
part_index=kv.rank)
val = mx.io.MNISTIter(
image="data/t10k-images-idx3-ubyte",
label="data/t10k-labels-idx1-ubyte",
input_shape=data_shape,
batch_size=args.batch_size,
flat=flat,
num_parts=kv.num_workers,
part_index=kv.rank)
return (train, val)
def get_iterator_impl_caffe(args, kv):
flat = False if len(data_shape) != 1 else True
train = mx.io.CaffeDataIter(
prototxt=
'layer { \
name: "mnist" \
type: "Data" \
top: "data" \
top: "label" \
include { \
phase: TRAIN \
} \
transform_param { \
scale: 0.00390625 \
} \
data_param { \
source: "mnist_train_lmdb" \
batch_size: 64 \
backend: LMDB \
} \
}',
flat=flat,
num_examples=60000
# float32 is the default, so left out here in order to illustrate
)
val = mx.io.CaffeDataIter(
prototxt=
'layer { \
name: "mnist" \
type: "Data" \
top: "data" \
top: "label" \
include { \
phase: TEST \
} \
transform_param { \
scale: 0.00390625 \
} \
data_param { \
source: "mnist_test_lmdb" \
batch_size: 100 \
backend: LMDB \
} \
}',
flat=flat,
num_examples=10000,
dtype="float32" # float32 is the default
)
return train, val
if use_caffe_data:
return get_iterator_impl_caffe
else:
return get_iterator_impl_mnist | [
"def",
"get_iterator",
"(",
"data_shape",
",",
"use_caffe_data",
")",
":",
"def",
"get_iterator_impl_mnist",
"(",
"args",
",",
"kv",
")",
":",
"\"\"\"return train and val iterators for mnist\"\"\"",
"# download data",
"get_mnist_ubyte",
"(",
")",
"flat",
"=",
"False",
"if",
"len",
"(",
"data_shape",
")",
"!=",
"1",
"else",
"True",
"train",
"=",
"mx",
".",
"io",
".",
"MNISTIter",
"(",
"image",
"=",
"\"data/train-images-idx3-ubyte\"",
",",
"label",
"=",
"\"data/train-labels-idx1-ubyte\"",
",",
"input_shape",
"=",
"data_shape",
",",
"batch_size",
"=",
"args",
".",
"batch_size",
",",
"shuffle",
"=",
"True",
",",
"flat",
"=",
"flat",
",",
"num_parts",
"=",
"kv",
".",
"num_workers",
",",
"part_index",
"=",
"kv",
".",
"rank",
")",
"val",
"=",
"mx",
".",
"io",
".",
"MNISTIter",
"(",
"image",
"=",
"\"data/t10k-images-idx3-ubyte\"",
",",
"label",
"=",
"\"data/t10k-labels-idx1-ubyte\"",
",",
"input_shape",
"=",
"data_shape",
",",
"batch_size",
"=",
"args",
".",
"batch_size",
",",
"flat",
"=",
"flat",
",",
"num_parts",
"=",
"kv",
".",
"num_workers",
",",
"part_index",
"=",
"kv",
".",
"rank",
")",
"return",
"(",
"train",
",",
"val",
")",
"def",
"get_iterator_impl_caffe",
"(",
"args",
",",
"kv",
")",
":",
"flat",
"=",
"False",
"if",
"len",
"(",
"data_shape",
")",
"!=",
"1",
"else",
"True",
"train",
"=",
"mx",
".",
"io",
".",
"CaffeDataIter",
"(",
"prototxt",
"=",
"'layer { \\\n name: \"mnist\" \\\n type: \"Data\" \\\n top: \"data\" \\\n top: \"label\" \\\n include { \\\n phase: TRAIN \\\n } \\\n transform_param { \\\n scale: 0.00390625 \\\n } \\\n data_param { \\\n source: \"mnist_train_lmdb\" \\\n batch_size: 64 \\\n backend: LMDB \\\n } \\\n }'",
",",
"flat",
"=",
"flat",
",",
"num_examples",
"=",
"60000",
"# float32 is the default, so left out here in order to illustrate",
")",
"val",
"=",
"mx",
".",
"io",
".",
"CaffeDataIter",
"(",
"prototxt",
"=",
"'layer { \\\n name: \"mnist\" \\\n type: \"Data\" \\\n top: \"data\" \\\n top: \"label\" \\\n include { \\\n phase: TEST \\\n } \\\n transform_param { \\\n scale: 0.00390625 \\\n } \\\n data_param { \\\n source: \"mnist_test_lmdb\" \\\n batch_size: 100 \\\n backend: LMDB \\\n } \\\n }'",
",",
"flat",
"=",
"flat",
",",
"num_examples",
"=",
"10000",
",",
"dtype",
"=",
"\"float32\"",
"# float32 is the default",
")",
"return",
"train",
",",
"val",
"if",
"use_caffe_data",
":",
"return",
"get_iterator_impl_caffe",
"else",
":",
"return",
"get_iterator_impl_mnist"
] | Generate the iterator of mnist dataset | [
"Generate",
"the",
"iterator",
"of",
"mnist",
"dataset"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/caffe/data.py#L22-L106 |
23,443 | apache/incubator-mxnet | example/gluon/audio/urban_sounds/predict.py | predict | def predict(prediction_dir='./Test'):
"""The function is used to run predictions on the audio files in the directory `pred_directory`.
Parameters
----------
net:
The model that has been trained.
prediction_dir: string, default ./Test
The directory that contains the audio files on which predictions are to be made
"""
if not os.path.exists(prediction_dir):
warnings.warn("The directory on which predictions are to be made is not found!")
return
if len(os.listdir(prediction_dir)) == 0:
warnings.warn("The directory on which predictions are to be made is empty! Exiting...")
return
# Loading synsets
if not os.path.exists('./synset.txt'):
warnings.warn("The synset or labels for the dataset do not exist. Please run the training script first.")
return
with open("./synset.txt", "r") as f:
synset = [l.rstrip() for l in f]
net = get_net(len(synset))
print("Trying to load the model with the saved parameters...")
if not os.path.exists("./net.params"):
warnings.warn("The model does not have any saved parameters... Cannot proceed! Train the model first")
return
net.load_parameters("./net.params")
file_names = os.listdir(prediction_dir)
full_file_names = [os.path.join(prediction_dir, item) for item in file_names]
from transforms import MFCC
mfcc = MFCC()
print("\nStarting predictions for audio files in ", prediction_dir, " ....\n")
for filename in full_file_names:
# Argument kaiser_fast to res_type is faster than 'kaiser_best'. To reduce the load time, passing kaiser_fast.
X1, _ = librosa.load(filename, res_type='kaiser_fast')
transformed_test_data = mfcc(mx.nd.array(X1))
output = net(transformed_test_data.reshape((1, -1)))
prediction = nd.argmax(output, axis=1)
print(filename, " -> ", synset[(int)(prediction.asscalar())]) | python | def predict(prediction_dir='./Test'):
"""The function is used to run predictions on the audio files in the directory `pred_directory`.
Parameters
----------
net:
The model that has been trained.
prediction_dir: string, default ./Test
The directory that contains the audio files on which predictions are to be made
"""
if not os.path.exists(prediction_dir):
warnings.warn("The directory on which predictions are to be made is not found!")
return
if len(os.listdir(prediction_dir)) == 0:
warnings.warn("The directory on which predictions are to be made is empty! Exiting...")
return
# Loading synsets
if not os.path.exists('./synset.txt'):
warnings.warn("The synset or labels for the dataset do not exist. Please run the training script first.")
return
with open("./synset.txt", "r") as f:
synset = [l.rstrip() for l in f]
net = get_net(len(synset))
print("Trying to load the model with the saved parameters...")
if not os.path.exists("./net.params"):
warnings.warn("The model does not have any saved parameters... Cannot proceed! Train the model first")
return
net.load_parameters("./net.params")
file_names = os.listdir(prediction_dir)
full_file_names = [os.path.join(prediction_dir, item) for item in file_names]
from transforms import MFCC
mfcc = MFCC()
print("\nStarting predictions for audio files in ", prediction_dir, " ....\n")
for filename in full_file_names:
# Argument kaiser_fast to res_type is faster than 'kaiser_best'. To reduce the load time, passing kaiser_fast.
X1, _ = librosa.load(filename, res_type='kaiser_fast')
transformed_test_data = mfcc(mx.nd.array(X1))
output = net(transformed_test_data.reshape((1, -1)))
prediction = nd.argmax(output, axis=1)
print(filename, " -> ", synset[(int)(prediction.asscalar())]) | [
"def",
"predict",
"(",
"prediction_dir",
"=",
"'./Test'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"prediction_dir",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The directory on which predictions are to be made is not found!\"",
")",
"return",
"if",
"len",
"(",
"os",
".",
"listdir",
"(",
"prediction_dir",
")",
")",
"==",
"0",
":",
"warnings",
".",
"warn",
"(",
"\"The directory on which predictions are to be made is empty! Exiting...\"",
")",
"return",
"# Loading synsets",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'./synset.txt'",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The synset or labels for the dataset do not exist. Please run the training script first.\"",
")",
"return",
"with",
"open",
"(",
"\"./synset.txt\"",
",",
"\"r\"",
")",
"as",
"f",
":",
"synset",
"=",
"[",
"l",
".",
"rstrip",
"(",
")",
"for",
"l",
"in",
"f",
"]",
"net",
"=",
"get_net",
"(",
"len",
"(",
"synset",
")",
")",
"print",
"(",
"\"Trying to load the model with the saved parameters...\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"./net.params\"",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The model does not have any saved parameters... Cannot proceed! Train the model first\"",
")",
"return",
"net",
".",
"load_parameters",
"(",
"\"./net.params\"",
")",
"file_names",
"=",
"os",
".",
"listdir",
"(",
"prediction_dir",
")",
"full_file_names",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"prediction_dir",
",",
"item",
")",
"for",
"item",
"in",
"file_names",
"]",
"from",
"transforms",
"import",
"MFCC",
"mfcc",
"=",
"MFCC",
"(",
")",
"print",
"(",
"\"\\nStarting predictions for audio files in \"",
",",
"prediction_dir",
",",
"\" ....\\n\"",
")",
"for",
"filename",
"in",
"full_file_names",
":",
"# Argument kaiser_fast to res_type is faster than 'kaiser_best'. To reduce the load time, passing kaiser_fast.",
"X1",
",",
"_",
"=",
"librosa",
".",
"load",
"(",
"filename",
",",
"res_type",
"=",
"'kaiser_fast'",
")",
"transformed_test_data",
"=",
"mfcc",
"(",
"mx",
".",
"nd",
".",
"array",
"(",
"X1",
")",
")",
"output",
"=",
"net",
"(",
"transformed_test_data",
".",
"reshape",
"(",
"(",
"1",
",",
"-",
"1",
")",
")",
")",
"prediction",
"=",
"nd",
".",
"argmax",
"(",
"output",
",",
"axis",
"=",
"1",
")",
"print",
"(",
"filename",
",",
"\" -> \"",
",",
"synset",
"[",
"(",
"int",
")",
"(",
"prediction",
".",
"asscalar",
"(",
")",
")",
"]",
")"
] | The function is used to run predictions on the audio files in the directory `pred_directory`.
Parameters
----------
net:
The model that has been trained.
prediction_dir: string, default ./Test
The directory that contains the audio files on which predictions are to be made | [
"The",
"function",
"is",
"used",
"to",
"run",
"predictions",
"on",
"the",
"audio",
"files",
"in",
"the",
"directory",
"pred_directory",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/audio/urban_sounds/predict.py#L32-L77 |
23,444 | apache/incubator-mxnet | example/ctc/multiproc_data.py | MPData._proc_loop | def _proc_loop(proc_id, alive, queue, fn):
"""Thread loop for generating data
Parameters
----------
proc_id: int
Process id
alive: multiprocessing.Value
variable for signaling whether process should continue or not
queue: multiprocessing.Queue
queue for passing data back
fn: function
function object that returns a sample to be pushed into the queue
"""
print("proc {} started".format(proc_id))
try:
while alive.value:
data = fn()
put_success = False
while alive.value and not put_success:
try:
queue.put(data, timeout=0.5)
put_success = True
except QFullExcept:
# print("Queue Full")
pass
except KeyboardInterrupt:
print("W: interrupt received, stopping process {} ...".format(proc_id))
print("Closing process {}".format(proc_id))
queue.close() | python | def _proc_loop(proc_id, alive, queue, fn):
"""Thread loop for generating data
Parameters
----------
proc_id: int
Process id
alive: multiprocessing.Value
variable for signaling whether process should continue or not
queue: multiprocessing.Queue
queue for passing data back
fn: function
function object that returns a sample to be pushed into the queue
"""
print("proc {} started".format(proc_id))
try:
while alive.value:
data = fn()
put_success = False
while alive.value and not put_success:
try:
queue.put(data, timeout=0.5)
put_success = True
except QFullExcept:
# print("Queue Full")
pass
except KeyboardInterrupt:
print("W: interrupt received, stopping process {} ...".format(proc_id))
print("Closing process {}".format(proc_id))
queue.close() | [
"def",
"_proc_loop",
"(",
"proc_id",
",",
"alive",
",",
"queue",
",",
"fn",
")",
":",
"print",
"(",
"\"proc {} started\"",
".",
"format",
"(",
"proc_id",
")",
")",
"try",
":",
"while",
"alive",
".",
"value",
":",
"data",
"=",
"fn",
"(",
")",
"put_success",
"=",
"False",
"while",
"alive",
".",
"value",
"and",
"not",
"put_success",
":",
"try",
":",
"queue",
".",
"put",
"(",
"data",
",",
"timeout",
"=",
"0.5",
")",
"put_success",
"=",
"True",
"except",
"QFullExcept",
":",
"# print(\"Queue Full\")",
"pass",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"\"W: interrupt received, stopping process {} ...\"",
".",
"format",
"(",
"proc_id",
")",
")",
"print",
"(",
"\"Closing process {}\"",
".",
"format",
"(",
"proc_id",
")",
")",
"queue",
".",
"close",
"(",
")"
] | Thread loop for generating data
Parameters
----------
proc_id: int
Process id
alive: multiprocessing.Value
variable for signaling whether process should continue or not
queue: multiprocessing.Queue
queue for passing data back
fn: function
function object that returns a sample to be pushed into the queue | [
"Thread",
"loop",
"for",
"generating",
"data"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L59-L88 |
23,445 | apache/incubator-mxnet | example/ctc/multiproc_data.py | MPData._init_proc | def _init_proc(self):
"""Start processes if not already started"""
if not self.proc:
self.proc = [
mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn))
for i in range(self.num_proc)
]
self.alive.value = True
for p in self.proc:
p.start() | python | def _init_proc(self):
"""Start processes if not already started"""
if not self.proc:
self.proc = [
mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn))
for i in range(self.num_proc)
]
self.alive.value = True
for p in self.proc:
p.start() | [
"def",
"_init_proc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"proc",
":",
"self",
".",
"proc",
"=",
"[",
"mp",
".",
"Process",
"(",
"target",
"=",
"self",
".",
"_proc_loop",
",",
"args",
"=",
"(",
"i",
",",
"self",
".",
"alive",
",",
"self",
".",
"queue",
",",
"self",
".",
"fn",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_proc",
")",
"]",
"self",
".",
"alive",
".",
"value",
"=",
"True",
"for",
"p",
"in",
"self",
".",
"proc",
":",
"p",
".",
"start",
"(",
")"
] | Start processes if not already started | [
"Start",
"processes",
"if",
"not",
"already",
"started"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L90-L99 |
23,446 | apache/incubator-mxnet | example/ctc/multiproc_data.py | MPData.reset | def reset(self):
"""Resets the generator by stopping all processes"""
self.alive.value = False
qsize = 0
try:
while True:
self.queue.get(timeout=0.1)
qsize += 1
except QEmptyExcept:
pass
print("Queue size on reset: {}".format(qsize))
for i, p in enumerate(self.proc):
p.join()
self.proc.clear() | python | def reset(self):
"""Resets the generator by stopping all processes"""
self.alive.value = False
qsize = 0
try:
while True:
self.queue.get(timeout=0.1)
qsize += 1
except QEmptyExcept:
pass
print("Queue size on reset: {}".format(qsize))
for i, p in enumerate(self.proc):
p.join()
self.proc.clear() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"alive",
".",
"value",
"=",
"False",
"qsize",
"=",
"0",
"try",
":",
"while",
"True",
":",
"self",
".",
"queue",
".",
"get",
"(",
"timeout",
"=",
"0.1",
")",
"qsize",
"+=",
"1",
"except",
"QEmptyExcept",
":",
"pass",
"print",
"(",
"\"Queue size on reset: {}\"",
".",
"format",
"(",
"qsize",
")",
")",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"self",
".",
"proc",
")",
":",
"p",
".",
"join",
"(",
")",
"self",
".",
"proc",
".",
"clear",
"(",
")"
] | Resets the generator by stopping all processes | [
"Resets",
"the",
"generator",
"by",
"stopping",
"all",
"processes"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L112-L125 |
23,447 | apache/incubator-mxnet | python/mxnet/base.py | _load_lib | def _load_lib():
"""Load library by searching possible path."""
lib_path = libinfo.find_lib_path()
lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib | python | def _load_lib():
"""Load library by searching possible path."""
lib_path = libinfo.find_lib_path()
lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib | [
"def",
"_load_lib",
"(",
")",
":",
"lib_path",
"=",
"libinfo",
".",
"find_lib_path",
"(",
")",
"lib",
"=",
"ctypes",
".",
"CDLL",
"(",
"lib_path",
"[",
"0",
"]",
",",
"ctypes",
".",
"RTLD_LOCAL",
")",
"# DMatrix functions",
"lib",
".",
"MXGetLastError",
".",
"restype",
"=",
"ctypes",
".",
"c_char_p",
"return",
"lib"
] | Load library by searching possible path. | [
"Load",
"library",
"by",
"searching",
"possible",
"path",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L202-L208 |
23,448 | apache/incubator-mxnet | python/mxnet/base.py | c_array | def c_array(ctype, values):
"""Create ctypes array from a Python array.
Parameters
----------
ctype : ctypes data type
Data type of the array we want to convert to, such as mx_float.
values : tuple or list
Data content.
Returns
-------
out : ctypes array
Created ctypes array.
Examples
--------
>>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3])
>>> print len(x)
3
>>> x[1]
2.0
"""
out = (ctype * len(values))()
out[:] = values
return out | python | def c_array(ctype, values):
"""Create ctypes array from a Python array.
Parameters
----------
ctype : ctypes data type
Data type of the array we want to convert to, such as mx_float.
values : tuple or list
Data content.
Returns
-------
out : ctypes array
Created ctypes array.
Examples
--------
>>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3])
>>> print len(x)
3
>>> x[1]
2.0
"""
out = (ctype * len(values))()
out[:] = values
return out | [
"def",
"c_array",
"(",
"ctype",
",",
"values",
")",
":",
"out",
"=",
"(",
"ctype",
"*",
"len",
"(",
"values",
")",
")",
"(",
")",
"out",
"[",
":",
"]",
"=",
"values",
"return",
"out"
] | Create ctypes array from a Python array.
Parameters
----------
ctype : ctypes data type
Data type of the array we want to convert to, such as mx_float.
values : tuple or list
Data content.
Returns
-------
out : ctypes array
Created ctypes array.
Examples
--------
>>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3])
>>> print len(x)
3
>>> x[1]
2.0 | [
"Create",
"ctypes",
"array",
"from",
"a",
"Python",
"array",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L336-L362 |
23,449 | apache/incubator-mxnet | python/mxnet/base.py | ctypes2numpy_shared | def ctypes2numpy_shared(cptr, shape):
"""Convert a ctypes pointer to a numpy array.
The resulting NumPy array shares the memory with the pointer.
Parameters
----------
cptr : ctypes.POINTER(mx_float)
pointer to the memory region
shape : tuple
Shape of target `NDArray`.
Returns
-------
out : numpy_array
A numpy array : numpy array.
"""
if not isinstance(cptr, ctypes.POINTER(mx_float)):
raise RuntimeError('expected float pointer')
size = 1
for s in shape:
size *= s
dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents))
return _np.frombuffer(dbuffer, dtype=_np.float32).reshape(shape) | python | def ctypes2numpy_shared(cptr, shape):
"""Convert a ctypes pointer to a numpy array.
The resulting NumPy array shares the memory with the pointer.
Parameters
----------
cptr : ctypes.POINTER(mx_float)
pointer to the memory region
shape : tuple
Shape of target `NDArray`.
Returns
-------
out : numpy_array
A numpy array : numpy array.
"""
if not isinstance(cptr, ctypes.POINTER(mx_float)):
raise RuntimeError('expected float pointer')
size = 1
for s in shape:
size *= s
dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents))
return _np.frombuffer(dbuffer, dtype=_np.float32).reshape(shape) | [
"def",
"ctypes2numpy_shared",
"(",
"cptr",
",",
"shape",
")",
":",
"if",
"not",
"isinstance",
"(",
"cptr",
",",
"ctypes",
".",
"POINTER",
"(",
"mx_float",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"'expected float pointer'",
")",
"size",
"=",
"1",
"for",
"s",
"in",
"shape",
":",
"size",
"*=",
"s",
"dbuffer",
"=",
"(",
"mx_float",
"*",
"size",
")",
".",
"from_address",
"(",
"ctypes",
".",
"addressof",
"(",
"cptr",
".",
"contents",
")",
")",
"return",
"_np",
".",
"frombuffer",
"(",
"dbuffer",
",",
"dtype",
"=",
"_np",
".",
"float32",
")",
".",
"reshape",
"(",
"shape",
")"
] | Convert a ctypes pointer to a numpy array.
The resulting NumPy array shares the memory with the pointer.
Parameters
----------
cptr : ctypes.POINTER(mx_float)
pointer to the memory region
shape : tuple
Shape of target `NDArray`.
Returns
-------
out : numpy_array
A numpy array : numpy array. | [
"Convert",
"a",
"ctypes",
"pointer",
"to",
"a",
"numpy",
"array",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L436-L460 |
23,450 | apache/incubator-mxnet | python/mxnet/base.py | build_param_doc | def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):
"""Build argument docs in python style.
arg_names : list of str
Argument names.
arg_types : list of str
Argument type information.
arg_descs : list of str
Argument description information.
remove_dup : boolean, optional
Whether remove duplication or not.
Returns
-------
docstr : str
Python docstring of parameter sections.
"""
param_keys = set()
param_str = []
for key, type_info, desc in zip(arg_names, arg_types, arg_descs):
if key in param_keys and remove_dup:
continue
if key == 'num_args':
continue
param_keys.add(key)
ret = '%s : %s' % (key, type_info)
if len(desc) != 0:
ret += '\n ' + desc
param_str.append(ret)
doc_str = ('Parameters\n' +
'----------\n' +
'%s\n')
doc_str = doc_str % ('\n'.join(param_str))
return doc_str | python | def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):
"""Build argument docs in python style.
arg_names : list of str
Argument names.
arg_types : list of str
Argument type information.
arg_descs : list of str
Argument description information.
remove_dup : boolean, optional
Whether remove duplication or not.
Returns
-------
docstr : str
Python docstring of parameter sections.
"""
param_keys = set()
param_str = []
for key, type_info, desc in zip(arg_names, arg_types, arg_descs):
if key in param_keys and remove_dup:
continue
if key == 'num_args':
continue
param_keys.add(key)
ret = '%s : %s' % (key, type_info)
if len(desc) != 0:
ret += '\n ' + desc
param_str.append(ret)
doc_str = ('Parameters\n' +
'----------\n' +
'%s\n')
doc_str = doc_str % ('\n'.join(param_str))
return doc_str | [
"def",
"build_param_doc",
"(",
"arg_names",
",",
"arg_types",
",",
"arg_descs",
",",
"remove_dup",
"=",
"True",
")",
":",
"param_keys",
"=",
"set",
"(",
")",
"param_str",
"=",
"[",
"]",
"for",
"key",
",",
"type_info",
",",
"desc",
"in",
"zip",
"(",
"arg_names",
",",
"arg_types",
",",
"arg_descs",
")",
":",
"if",
"key",
"in",
"param_keys",
"and",
"remove_dup",
":",
"continue",
"if",
"key",
"==",
"'num_args'",
":",
"continue",
"param_keys",
".",
"add",
"(",
"key",
")",
"ret",
"=",
"'%s : %s'",
"%",
"(",
"key",
",",
"type_info",
")",
"if",
"len",
"(",
"desc",
")",
"!=",
"0",
":",
"ret",
"+=",
"'\\n '",
"+",
"desc",
"param_str",
".",
"append",
"(",
"ret",
")",
"doc_str",
"=",
"(",
"'Parameters\\n'",
"+",
"'----------\\n'",
"+",
"'%s\\n'",
")",
"doc_str",
"=",
"doc_str",
"%",
"(",
"'\\n'",
".",
"join",
"(",
"param_str",
")",
")",
"return",
"doc_str"
] | Build argument docs in python style.
arg_names : list of str
Argument names.
arg_types : list of str
Argument type information.
arg_descs : list of str
Argument description information.
remove_dup : boolean, optional
Whether remove duplication or not.
Returns
-------
docstr : str
Python docstring of parameter sections. | [
"Build",
"argument",
"docs",
"in",
"python",
"style",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L463-L499 |
23,451 | apache/incubator-mxnet | python/mxnet/base.py | add_fileline_to_docstring | def add_fileline_to_docstring(module, incursive=True):
"""Append the definition position to each function contained in module.
Examples
--------
# Put the following codes at the end of a file
add_fileline_to_docstring(__name__)
"""
def _add_fileline(obj):
"""Add fileinto to a object.
"""
if obj.__doc__ is None or 'From:' in obj.__doc__:
return
fname = inspect.getsourcefile(obj)
if fname is None:
return
try:
line = inspect.getsourcelines(obj)[-1]
except IOError:
return
obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line)
if isinstance(module, str):
module = sys.modules[module]
for _, obj in inspect.getmembers(module):
if inspect.isbuiltin(obj):
continue
if inspect.isfunction(obj):
_add_fileline(obj)
if inspect.ismethod(obj):
_add_fileline(obj.__func__)
if inspect.isclass(obj) and incursive:
add_fileline_to_docstring(obj, False) | python | def add_fileline_to_docstring(module, incursive=True):
"""Append the definition position to each function contained in module.
Examples
--------
# Put the following codes at the end of a file
add_fileline_to_docstring(__name__)
"""
def _add_fileline(obj):
"""Add fileinto to a object.
"""
if obj.__doc__ is None or 'From:' in obj.__doc__:
return
fname = inspect.getsourcefile(obj)
if fname is None:
return
try:
line = inspect.getsourcelines(obj)[-1]
except IOError:
return
obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line)
if isinstance(module, str):
module = sys.modules[module]
for _, obj in inspect.getmembers(module):
if inspect.isbuiltin(obj):
continue
if inspect.isfunction(obj):
_add_fileline(obj)
if inspect.ismethod(obj):
_add_fileline(obj.__func__)
if inspect.isclass(obj) and incursive:
add_fileline_to_docstring(obj, False) | [
"def",
"add_fileline_to_docstring",
"(",
"module",
",",
"incursive",
"=",
"True",
")",
":",
"def",
"_add_fileline",
"(",
"obj",
")",
":",
"\"\"\"Add fileinto to a object.\n \"\"\"",
"if",
"obj",
".",
"__doc__",
"is",
"None",
"or",
"'From:'",
"in",
"obj",
".",
"__doc__",
":",
"return",
"fname",
"=",
"inspect",
".",
"getsourcefile",
"(",
"obj",
")",
"if",
"fname",
"is",
"None",
":",
"return",
"try",
":",
"line",
"=",
"inspect",
".",
"getsourcelines",
"(",
"obj",
")",
"[",
"-",
"1",
"]",
"except",
"IOError",
":",
"return",
"obj",
".",
"__doc__",
"+=",
"'\\n\\nFrom:%s:%d'",
"%",
"(",
"fname",
",",
"line",
")",
"if",
"isinstance",
"(",
"module",
",",
"str",
")",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"module",
"]",
"for",
"_",
",",
"obj",
"in",
"inspect",
".",
"getmembers",
"(",
"module",
")",
":",
"if",
"inspect",
".",
"isbuiltin",
"(",
"obj",
")",
":",
"continue",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
":",
"_add_fileline",
"(",
"obj",
")",
"if",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
":",
"_add_fileline",
"(",
"obj",
".",
"__func__",
")",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
"and",
"incursive",
":",
"add_fileline_to_docstring",
"(",
"obj",
",",
"False",
")"
] | Append the definition position to each function contained in module.
Examples
--------
# Put the following codes at the end of a file
add_fileline_to_docstring(__name__) | [
"Append",
"the",
"definition",
"position",
"to",
"each",
"function",
"contained",
"in",
"module",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L510-L543 |
23,452 | apache/incubator-mxnet | python/mxnet/base.py | is_np_compat | def is_np_compat():
"""
Checks whether the NumPy compatibility is currently turned on.
NumPy-compatibility is turned off by default in backend.
Returns
-------
A bool value indicating whether the NumPy compatibility is currently on.
"""
curr = ctypes.c_bool()
check_call(_LIB.MXIsNumpyCompatible(ctypes.byref(curr)))
return curr.value | python | def is_np_compat():
"""
Checks whether the NumPy compatibility is currently turned on.
NumPy-compatibility is turned off by default in backend.
Returns
-------
A bool value indicating whether the NumPy compatibility is currently on.
"""
curr = ctypes.c_bool()
check_call(_LIB.MXIsNumpyCompatible(ctypes.byref(curr)))
return curr.value | [
"def",
"is_np_compat",
"(",
")",
":",
"curr",
"=",
"ctypes",
".",
"c_bool",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXIsNumpyCompatible",
"(",
"ctypes",
".",
"byref",
"(",
"curr",
")",
")",
")",
"return",
"curr",
".",
"value"
] | Checks whether the NumPy compatibility is currently turned on.
NumPy-compatibility is turned off by default in backend.
Returns
-------
A bool value indicating whether the NumPy compatibility is currently on. | [
"Checks",
"whether",
"the",
"NumPy",
"compatibility",
"is",
"currently",
"turned",
"on",
".",
"NumPy",
"-",
"compatibility",
"is",
"turned",
"off",
"by",
"default",
"in",
"backend",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L758-L769 |
23,453 | apache/incubator-mxnet | python/mxnet/base.py | use_np_compat | def use_np_compat(func):
"""Wraps a function with an activated NumPy-compatibility scope. This ensures
that the execution of the function is guaranteed with NumPy compatible semantics,
such as zero-dim and zero size tensors.
Example::
import mxnet as mx
@mx.use_np_compat
def scalar_one():
return mx.nd.ones(())
print(scalar_one())
Parameters
----------
func : a user-provided callable function to be scoped by the NumPy compatibility state.
Returns
-------
Function
A function for wrapping the user functions in the NumPy compatibility scope.
"""
@wraps(func)
def _with_np_compat(*args, **kwargs):
with np_compat(active=True):
return func(*args, **kwargs)
return _with_np_compat | python | def use_np_compat(func):
"""Wraps a function with an activated NumPy-compatibility scope. This ensures
that the execution of the function is guaranteed with NumPy compatible semantics,
such as zero-dim and zero size tensors.
Example::
import mxnet as mx
@mx.use_np_compat
def scalar_one():
return mx.nd.ones(())
print(scalar_one())
Parameters
----------
func : a user-provided callable function to be scoped by the NumPy compatibility state.
Returns
-------
Function
A function for wrapping the user functions in the NumPy compatibility scope.
"""
@wraps(func)
def _with_np_compat(*args, **kwargs):
with np_compat(active=True):
return func(*args, **kwargs)
return _with_np_compat | [
"def",
"use_np_compat",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_with_np_compat",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"np_compat",
"(",
"active",
"=",
"True",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_with_np_compat"
] | Wraps a function with an activated NumPy-compatibility scope. This ensures
that the execution of the function is guaranteed with NumPy compatible semantics,
such as zero-dim and zero size tensors.
Example::
import mxnet as mx
@mx.use_np_compat
def scalar_one():
return mx.nd.ones(())
print(scalar_one())
Parameters
----------
func : a user-provided callable function to be scoped by the NumPy compatibility state.
Returns
-------
Function
A function for wrapping the user functions in the NumPy compatibility scope. | [
"Wraps",
"a",
"function",
"with",
"an",
"activated",
"NumPy",
"-",
"compatibility",
"scope",
".",
"This",
"ensures",
"that",
"the",
"execution",
"of",
"the",
"function",
"is",
"guaranteed",
"with",
"NumPy",
"compatible",
"semantics",
"such",
"as",
"zero",
"-",
"dim",
"and",
"zero",
"size",
"tensors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L848-L874 |
23,454 | apache/incubator-mxnet | example/multivariate_time_series/src/metrics.py | corr | def corr(label, pred):
"""computes the empirical correlation coefficient"""
numerator1 = label - np.mean(label, axis=0)
numerator2 = pred - np.mean(pred, axis = 0)
numerator = np.mean(numerator1 * numerator2, axis=0)
denominator = np.std(label, axis=0) * np.std(pred, axis=0)
return np.mean(numerator / denominator) | python | def corr(label, pred):
"""computes the empirical correlation coefficient"""
numerator1 = label - np.mean(label, axis=0)
numerator2 = pred - np.mean(pred, axis = 0)
numerator = np.mean(numerator1 * numerator2, axis=0)
denominator = np.std(label, axis=0) * np.std(pred, axis=0)
return np.mean(numerator / denominator) | [
"def",
"corr",
"(",
"label",
",",
"pred",
")",
":",
"numerator1",
"=",
"label",
"-",
"np",
".",
"mean",
"(",
"label",
",",
"axis",
"=",
"0",
")",
"numerator2",
"=",
"pred",
"-",
"np",
".",
"mean",
"(",
"pred",
",",
"axis",
"=",
"0",
")",
"numerator",
"=",
"np",
".",
"mean",
"(",
"numerator1",
"*",
"numerator2",
",",
"axis",
"=",
"0",
")",
"denominator",
"=",
"np",
".",
"std",
"(",
"label",
",",
"axis",
"=",
"0",
")",
"*",
"np",
".",
"std",
"(",
"pred",
",",
"axis",
"=",
"0",
")",
"return",
"np",
".",
"mean",
"(",
"numerator",
"/",
"denominator",
")"
] | computes the empirical correlation coefficient | [
"computes",
"the",
"empirical",
"correlation",
"coefficient"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/multivariate_time_series/src/metrics.py#L37-L43 |
23,455 | apache/incubator-mxnet | example/ssd/tools/caffe_converter/convert_symbol.py | _get_input | def _get_input(proto):
"""Get input size
"""
layer = caffe_parser.get_layers(proto)
if len(proto.input_dim) > 0:
input_dim = proto.input_dim
elif len(proto.input_shape) > 0:
input_dim = proto.input_shape[0].dim
elif layer[0].type == "Input":
input_dim = layer[0].input_param.shape[0].dim
layer.pop(0)
else:
raise ValueError('Cannot find input size')
assert layer[0].type != "Input", 'only support single input'
# We assume the first bottom blob of first layer is the output from data layer
input_name = layer[0].bottom[0]
return input_name, input_dim, layer | python | def _get_input(proto):
"""Get input size
"""
layer = caffe_parser.get_layers(proto)
if len(proto.input_dim) > 0:
input_dim = proto.input_dim
elif len(proto.input_shape) > 0:
input_dim = proto.input_shape[0].dim
elif layer[0].type == "Input":
input_dim = layer[0].input_param.shape[0].dim
layer.pop(0)
else:
raise ValueError('Cannot find input size')
assert layer[0].type != "Input", 'only support single input'
# We assume the first bottom blob of first layer is the output from data layer
input_name = layer[0].bottom[0]
return input_name, input_dim, layer | [
"def",
"_get_input",
"(",
"proto",
")",
":",
"layer",
"=",
"caffe_parser",
".",
"get_layers",
"(",
"proto",
")",
"if",
"len",
"(",
"proto",
".",
"input_dim",
")",
">",
"0",
":",
"input_dim",
"=",
"proto",
".",
"input_dim",
"elif",
"len",
"(",
"proto",
".",
"input_shape",
")",
">",
"0",
":",
"input_dim",
"=",
"proto",
".",
"input_shape",
"[",
"0",
"]",
".",
"dim",
"elif",
"layer",
"[",
"0",
"]",
".",
"type",
"==",
"\"Input\"",
":",
"input_dim",
"=",
"layer",
"[",
"0",
"]",
".",
"input_param",
".",
"shape",
"[",
"0",
"]",
".",
"dim",
"layer",
".",
"pop",
"(",
"0",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Cannot find input size'",
")",
"assert",
"layer",
"[",
"0",
"]",
".",
"type",
"!=",
"\"Input\"",
",",
"'only support single input'",
"# We assume the first bottom blob of first layer is the output from data layer",
"input_name",
"=",
"layer",
"[",
"0",
"]",
".",
"bottom",
"[",
"0",
"]",
"return",
"input_name",
",",
"input_dim",
",",
"layer"
] | Get input size | [
"Get",
"input",
"size"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L23-L40 |
23,456 | apache/incubator-mxnet | example/ssd/tools/caffe_converter/convert_symbol.py | _convert_conv_param | def _convert_conv_param(param):
"""
Convert convolution layer parameter from Caffe to MXNet
"""
param_string = "num_filter=%d" % param.num_output
pad_w = 0
pad_h = 0
if isinstance(param.pad, int):
pad = param.pad
param_string += ", pad=(%d, %d)" % (pad, pad)
else:
if len(param.pad) > 0:
pad = param.pad[0]
param_string += ", pad=(%d, %d)" % (pad, pad)
else:
if isinstance(param.pad_w, int):
pad_w = param.pad_w
if isinstance(param.pad_h, int):
pad_h = param.pad_h
param_string += ", pad=(%d, %d)" % (pad_h, pad_w)
if isinstance(param.kernel_size, int):
kernel_size = param.kernel_size
param_string += ", kernel=(%d,%d)" % (kernel_size, kernel_size)
else:
if len(param.kernel_size) > 0:
kernel_size = param.kernel_size[0]
param_string += ", kernel=(%d,%d)" % (kernel_size, kernel_size)
else:
assert isinstance(param.kernel_w, int)
kernel_w = param.kernel_w
assert isinstance(param.kernel_h, int)
kernel_h = param.kernel_h
param_string += ", kernel=(%d,%d)" % (kernel_h, kernel_w)
stride = 1
if isinstance(param.stride, int):
stride = param.stride
else:
stride = 1 if len(param.stride) == 0 else param.stride[0]
param_string += ", stride=(%d,%d)" % (stride, stride)
dilate = 1
if hasattr(param, 'dilation'):
if isinstance(param.dilation, int):
dilate = param.dilation
else:
dilate = 1 if len(param.dilation) == 0 else param.dilation[0]
param_string += ", no_bias=%s" % (not param.bias_term)
# deal with dilation. Won't be in deconvolution
if dilate > 1:
param_string += ", dilate=(%d, %d)" % (dilate, dilate)
if isinstance(param.group, int):
if param.group != 1:
param_string += ", num_group=%d" % param.group
return param_string | python | def _convert_conv_param(param):
"""
Convert convolution layer parameter from Caffe to MXNet
"""
param_string = "num_filter=%d" % param.num_output
pad_w = 0
pad_h = 0
if isinstance(param.pad, int):
pad = param.pad
param_string += ", pad=(%d, %d)" % (pad, pad)
else:
if len(param.pad) > 0:
pad = param.pad[0]
param_string += ", pad=(%d, %d)" % (pad, pad)
else:
if isinstance(param.pad_w, int):
pad_w = param.pad_w
if isinstance(param.pad_h, int):
pad_h = param.pad_h
param_string += ", pad=(%d, %d)" % (pad_h, pad_w)
if isinstance(param.kernel_size, int):
kernel_size = param.kernel_size
param_string += ", kernel=(%d,%d)" % (kernel_size, kernel_size)
else:
if len(param.kernel_size) > 0:
kernel_size = param.kernel_size[0]
param_string += ", kernel=(%d,%d)" % (kernel_size, kernel_size)
else:
assert isinstance(param.kernel_w, int)
kernel_w = param.kernel_w
assert isinstance(param.kernel_h, int)
kernel_h = param.kernel_h
param_string += ", kernel=(%d,%d)" % (kernel_h, kernel_w)
stride = 1
if isinstance(param.stride, int):
stride = param.stride
else:
stride = 1 if len(param.stride) == 0 else param.stride[0]
param_string += ", stride=(%d,%d)" % (stride, stride)
dilate = 1
if hasattr(param, 'dilation'):
if isinstance(param.dilation, int):
dilate = param.dilation
else:
dilate = 1 if len(param.dilation) == 0 else param.dilation[0]
param_string += ", no_bias=%s" % (not param.bias_term)
# deal with dilation. Won't be in deconvolution
if dilate > 1:
param_string += ", dilate=(%d, %d)" % (dilate, dilate)
if isinstance(param.group, int):
if param.group != 1:
param_string += ", num_group=%d" % param.group
return param_string | [
"def",
"_convert_conv_param",
"(",
"param",
")",
":",
"param_string",
"=",
"\"num_filter=%d\"",
"%",
"param",
".",
"num_output",
"pad_w",
"=",
"0",
"pad_h",
"=",
"0",
"if",
"isinstance",
"(",
"param",
".",
"pad",
",",
"int",
")",
":",
"pad",
"=",
"param",
".",
"pad",
"param_string",
"+=",
"\", pad=(%d, %d)\"",
"%",
"(",
"pad",
",",
"pad",
")",
"else",
":",
"if",
"len",
"(",
"param",
".",
"pad",
")",
">",
"0",
":",
"pad",
"=",
"param",
".",
"pad",
"[",
"0",
"]",
"param_string",
"+=",
"\", pad=(%d, %d)\"",
"%",
"(",
"pad",
",",
"pad",
")",
"else",
":",
"if",
"isinstance",
"(",
"param",
".",
"pad_w",
",",
"int",
")",
":",
"pad_w",
"=",
"param",
".",
"pad_w",
"if",
"isinstance",
"(",
"param",
".",
"pad_h",
",",
"int",
")",
":",
"pad_h",
"=",
"param",
".",
"pad_h",
"param_string",
"+=",
"\", pad=(%d, %d)\"",
"%",
"(",
"pad_h",
",",
"pad_w",
")",
"if",
"isinstance",
"(",
"param",
".",
"kernel_size",
",",
"int",
")",
":",
"kernel_size",
"=",
"param",
".",
"kernel_size",
"param_string",
"+=",
"\", kernel=(%d,%d)\"",
"%",
"(",
"kernel_size",
",",
"kernel_size",
")",
"else",
":",
"if",
"len",
"(",
"param",
".",
"kernel_size",
")",
">",
"0",
":",
"kernel_size",
"=",
"param",
".",
"kernel_size",
"[",
"0",
"]",
"param_string",
"+=",
"\", kernel=(%d,%d)\"",
"%",
"(",
"kernel_size",
",",
"kernel_size",
")",
"else",
":",
"assert",
"isinstance",
"(",
"param",
".",
"kernel_w",
",",
"int",
")",
"kernel_w",
"=",
"param",
".",
"kernel_w",
"assert",
"isinstance",
"(",
"param",
".",
"kernel_h",
",",
"int",
")",
"kernel_h",
"=",
"param",
".",
"kernel_h",
"param_string",
"+=",
"\", kernel=(%d,%d)\"",
"%",
"(",
"kernel_h",
",",
"kernel_w",
")",
"stride",
"=",
"1",
"if",
"isinstance",
"(",
"param",
".",
"stride",
",",
"int",
")",
":",
"stride",
"=",
"param",
".",
"stride",
"else",
":",
"stride",
"=",
"1",
"if",
"len",
"(",
"param",
".",
"stride",
")",
"==",
"0",
"else",
"param",
".",
"stride",
"[",
"0",
"]",
"param_string",
"+=",
"\", stride=(%d,%d)\"",
"%",
"(",
"stride",
",",
"stride",
")",
"dilate",
"=",
"1",
"if",
"hasattr",
"(",
"param",
",",
"'dilation'",
")",
":",
"if",
"isinstance",
"(",
"param",
".",
"dilation",
",",
"int",
")",
":",
"dilate",
"=",
"param",
".",
"dilation",
"else",
":",
"dilate",
"=",
"1",
"if",
"len",
"(",
"param",
".",
"dilation",
")",
"==",
"0",
"else",
"param",
".",
"dilation",
"[",
"0",
"]",
"param_string",
"+=",
"\", no_bias=%s\"",
"%",
"(",
"not",
"param",
".",
"bias_term",
")",
"# deal with dilation. Won't be in deconvolution",
"if",
"dilate",
">",
"1",
":",
"param_string",
"+=",
"\", dilate=(%d, %d)\"",
"%",
"(",
"dilate",
",",
"dilate",
")",
"if",
"isinstance",
"(",
"param",
".",
"group",
",",
"int",
")",
":",
"if",
"param",
".",
"group",
"!=",
"1",
":",
"param_string",
"+=",
"\", num_group=%d\"",
"%",
"param",
".",
"group",
"return",
"param_string"
] | Convert convolution layer parameter from Caffe to MXNet | [
"Convert",
"convolution",
"layer",
"parameter",
"from",
"Caffe",
"to",
"MXNet"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L42-L103 |
23,457 | apache/incubator-mxnet | example/ssd/tools/caffe_converter/convert_symbol.py | _convert_pooling_param | def _convert_pooling_param(param):
"""Convert the pooling layer parameter
"""
param_string = "pooling_convention='full', "
if param.global_pooling:
param_string += "global_pool=True, kernel=(1,1)"
else:
param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % (
param.pad, param.pad, param.kernel_size, param.kernel_size,
param.stride, param.stride)
if param.pool == 0:
param_string += ", pool_type='max'"
elif param.pool == 1:
param_string += ", pool_type='avg'"
else:
raise ValueError("Unknown Pooling Method!")
return param_string | python | def _convert_pooling_param(param):
"""Convert the pooling layer parameter
"""
param_string = "pooling_convention='full', "
if param.global_pooling:
param_string += "global_pool=True, kernel=(1,1)"
else:
param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % (
param.pad, param.pad, param.kernel_size, param.kernel_size,
param.stride, param.stride)
if param.pool == 0:
param_string += ", pool_type='max'"
elif param.pool == 1:
param_string += ", pool_type='avg'"
else:
raise ValueError("Unknown Pooling Method!")
return param_string | [
"def",
"_convert_pooling_param",
"(",
"param",
")",
":",
"param_string",
"=",
"\"pooling_convention='full', \"",
"if",
"param",
".",
"global_pooling",
":",
"param_string",
"+=",
"\"global_pool=True, kernel=(1,1)\"",
"else",
":",
"param_string",
"+=",
"\"pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)\"",
"%",
"(",
"param",
".",
"pad",
",",
"param",
".",
"pad",
",",
"param",
".",
"kernel_size",
",",
"param",
".",
"kernel_size",
",",
"param",
".",
"stride",
",",
"param",
".",
"stride",
")",
"if",
"param",
".",
"pool",
"==",
"0",
":",
"param_string",
"+=",
"\", pool_type='max'\"",
"elif",
"param",
".",
"pool",
"==",
"1",
":",
"param_string",
"+=",
"\", pool_type='avg'\"",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown Pooling Method!\"",
")",
"return",
"param_string"
] | Convert the pooling layer parameter | [
"Convert",
"the",
"pooling",
"layer",
"parameter"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L105-L121 |
23,458 | apache/incubator-mxnet | example/ssd/tools/caffe_converter/caffe_parse/parse_from_protobuf.py | parse_caffemodel | def parse_caffemodel(file_path):
"""
parses the trained .caffemodel file
filepath: /path/to/trained-model.caffemodel
returns: layers
"""
f = open(file_path, 'rb')
contents = f.read()
net_param = caffe_pb2.NetParameter()
net_param.ParseFromString(contents)
layers = find_layers(net_param)
return layers | python | def parse_caffemodel(file_path):
"""
parses the trained .caffemodel file
filepath: /path/to/trained-model.caffemodel
returns: layers
"""
f = open(file_path, 'rb')
contents = f.read()
net_param = caffe_pb2.NetParameter()
net_param.ParseFromString(contents)
layers = find_layers(net_param)
return layers | [
"def",
"parse_caffemodel",
"(",
"file_path",
")",
":",
"f",
"=",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"net_param",
"=",
"caffe_pb2",
".",
"NetParameter",
"(",
")",
"net_param",
".",
"ParseFromString",
"(",
"contents",
")",
"layers",
"=",
"find_layers",
"(",
"net_param",
")",
"return",
"layers"
] | parses the trained .caffemodel file
filepath: /path/to/trained-model.caffemodel
returns: layers | [
"parses",
"the",
"trained",
".",
"caffemodel",
"file"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/caffe_parse/parse_from_protobuf.py#L23-L38 |
23,459 | apache/incubator-mxnet | example/gluon/embedding_learning/data.py | transform | def transform(data, target_wd, target_ht, is_train, box):
"""Crop and normnalize an image nd array."""
if box is not None:
x, y, w, h = box
data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])]
# Resize to target_wd * target_ht.
data = mx.image.imresize(data, target_wd, target_ht)
# Normalize in the same way as the pre-trained model.
data = data.astype(np.float32) / 255.0
data = (data - mx.nd.array([0.485, 0.456, 0.406])) / mx.nd.array([0.229, 0.224, 0.225])
if is_train:
if random.random() < 0.5:
data = nd.flip(data, axis=1)
data, _ = mx.image.random_crop(data, (224, 224))
else:
data, _ = mx.image.center_crop(data, (224, 224))
# Transpose from (target_wd, target_ht, 3)
# to (3, target_wd, target_ht).
data = nd.transpose(data, (2, 0, 1))
# If image is greyscale, repeat 3 times to get RGB image.
if data.shape[0] == 1:
data = nd.tile(data, (3, 1, 1))
return data.reshape((1,) + data.shape) | python | def transform(data, target_wd, target_ht, is_train, box):
"""Crop and normnalize an image nd array."""
if box is not None:
x, y, w, h = box
data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])]
# Resize to target_wd * target_ht.
data = mx.image.imresize(data, target_wd, target_ht)
# Normalize in the same way as the pre-trained model.
data = data.astype(np.float32) / 255.0
data = (data - mx.nd.array([0.485, 0.456, 0.406])) / mx.nd.array([0.229, 0.224, 0.225])
if is_train:
if random.random() < 0.5:
data = nd.flip(data, axis=1)
data, _ = mx.image.random_crop(data, (224, 224))
else:
data, _ = mx.image.center_crop(data, (224, 224))
# Transpose from (target_wd, target_ht, 3)
# to (3, target_wd, target_ht).
data = nd.transpose(data, (2, 0, 1))
# If image is greyscale, repeat 3 times to get RGB image.
if data.shape[0] == 1:
data = nd.tile(data, (3, 1, 1))
return data.reshape((1,) + data.shape) | [
"def",
"transform",
"(",
"data",
",",
"target_wd",
",",
"target_ht",
",",
"is_train",
",",
"box",
")",
":",
"if",
"box",
"is",
"not",
"None",
":",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"box",
"data",
"=",
"data",
"[",
"y",
":",
"min",
"(",
"y",
"+",
"h",
",",
"data",
".",
"shape",
"[",
"0",
"]",
")",
",",
"x",
":",
"min",
"(",
"x",
"+",
"w",
",",
"data",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"# Resize to target_wd * target_ht.",
"data",
"=",
"mx",
".",
"image",
".",
"imresize",
"(",
"data",
",",
"target_wd",
",",
"target_ht",
")",
"# Normalize in the same way as the pre-trained model.",
"data",
"=",
"data",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"/",
"255.0",
"data",
"=",
"(",
"data",
"-",
"mx",
".",
"nd",
".",
"array",
"(",
"[",
"0.485",
",",
"0.456",
",",
"0.406",
"]",
")",
")",
"/",
"mx",
".",
"nd",
".",
"array",
"(",
"[",
"0.229",
",",
"0.224",
",",
"0.225",
"]",
")",
"if",
"is_train",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"0.5",
":",
"data",
"=",
"nd",
".",
"flip",
"(",
"data",
",",
"axis",
"=",
"1",
")",
"data",
",",
"_",
"=",
"mx",
".",
"image",
".",
"random_crop",
"(",
"data",
",",
"(",
"224",
",",
"224",
")",
")",
"else",
":",
"data",
",",
"_",
"=",
"mx",
".",
"image",
".",
"center_crop",
"(",
"data",
",",
"(",
"224",
",",
"224",
")",
")",
"# Transpose from (target_wd, target_ht, 3)",
"# to (3, target_wd, target_ht).",
"data",
"=",
"nd",
".",
"transpose",
"(",
"data",
",",
"(",
"2",
",",
"0",
",",
"1",
")",
")",
"# If image is greyscale, repeat 3 times to get RGB image.",
"if",
"data",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
":",
"data",
"=",
"nd",
".",
"tile",
"(",
"data",
",",
"(",
"3",
",",
"1",
",",
"1",
")",
")",
"return",
"data",
".",
"reshape",
"(",
"(",
"1",
",",
")",
"+",
"data",
".",
"shape",
")"
] | Crop and normnalize an image nd array. | [
"Crop",
"and",
"normnalize",
"an",
"image",
"nd",
"array",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L26-L53 |
23,460 | apache/incubator-mxnet | example/gluon/embedding_learning/data.py | cub200_iterator | def cub200_iterator(data_path, batch_k, batch_size, data_shape):
"""Return training and testing iterator for the CUB200-2011 dataset."""
return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True),
CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False)) | python | def cub200_iterator(data_path, batch_k, batch_size, data_shape):
"""Return training and testing iterator for the CUB200-2011 dataset."""
return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True),
CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False)) | [
"def",
"cub200_iterator",
"(",
"data_path",
",",
"batch_k",
",",
"batch_size",
",",
"data_shape",
")",
":",
"return",
"(",
"CUB200Iter",
"(",
"data_path",
",",
"batch_k",
",",
"batch_size",
",",
"data_shape",
",",
"is_train",
"=",
"True",
")",
",",
"CUB200Iter",
"(",
"data_path",
",",
"batch_k",
",",
"batch_size",
",",
"data_shape",
",",
"is_train",
"=",
"False",
")",
")"
] | Return training and testing iterator for the CUB200-2011 dataset. | [
"Return",
"training",
"and",
"testing",
"iterator",
"for",
"the",
"CUB200",
"-",
"2011",
"dataset",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L155-L158 |
23,461 | apache/incubator-mxnet | example/gluon/embedding_learning/data.py | CUB200Iter.get_image | def get_image(self, img, is_train):
"""Load and transform an image."""
img_arr = mx.image.imread(img)
img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
return img_arr | python | def get_image(self, img, is_train):
"""Load and transform an image."""
img_arr = mx.image.imread(img)
img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
return img_arr | [
"def",
"get_image",
"(",
"self",
",",
"img",
",",
"is_train",
")",
":",
"img_arr",
"=",
"mx",
".",
"image",
".",
"imread",
"(",
"img",
")",
"img_arr",
"=",
"transform",
"(",
"img_arr",
",",
"256",
",",
"256",
",",
"is_train",
",",
"self",
".",
"boxes",
"[",
"img",
"]",
")",
"return",
"img_arr"
] | Load and transform an image. | [
"Load",
"and",
"transform",
"an",
"image",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L105-L109 |
23,462 | apache/incubator-mxnet | example/gluon/embedding_learning/data.py | CUB200Iter.next | def next(self):
"""Return a batch."""
if self.is_train:
data, labels = self.sample_train_batch()
else:
if self.test_count * self.batch_size < len(self.test_image_files):
data, labels = self.get_test_batch()
self.test_count += 1
else:
self.test_count = 0
raise StopIteration
return mx.io.DataBatch(data=[data], label=[labels]) | python | def next(self):
"""Return a batch."""
if self.is_train:
data, labels = self.sample_train_batch()
else:
if self.test_count * self.batch_size < len(self.test_image_files):
data, labels = self.get_test_batch()
self.test_count += 1
else:
self.test_count = 0
raise StopIteration
return mx.io.DataBatch(data=[data], label=[labels]) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_train",
":",
"data",
",",
"labels",
"=",
"self",
".",
"sample_train_batch",
"(",
")",
"else",
":",
"if",
"self",
".",
"test_count",
"*",
"self",
".",
"batch_size",
"<",
"len",
"(",
"self",
".",
"test_image_files",
")",
":",
"data",
",",
"labels",
"=",
"self",
".",
"get_test_batch",
"(",
")",
"self",
".",
"test_count",
"+=",
"1",
"else",
":",
"self",
".",
"test_count",
"=",
"0",
"raise",
"StopIteration",
"return",
"mx",
".",
"io",
".",
"DataBatch",
"(",
"data",
"=",
"[",
"data",
"]",
",",
"label",
"=",
"[",
"labels",
"]",
")"
] | Return a batch. | [
"Return",
"a",
"batch",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L142-L153 |
23,463 | apache/incubator-mxnet | example/bayesian-methods/data_loader.py | load_mnist | def load_mnist(training_num=50000):
"""Load mnist dataset"""
data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz')
if not os.path.isfile(data_path):
from six.moves import urllib
origin = (
'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz'
)
print('Downloading data from %s to %s' % (origin, data_path))
ctx = ssl._create_unverified_context()
with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f:
f.write(u.read())
print('Done!')
dat = numpy.load(data_path)
X = (dat['X'][:training_num] / 126.0).astype('float32')
Y = dat['Y'][:training_num]
X_test = (dat['X_test'] / 126.0).astype('float32')
Y_test = dat['Y_test']
Y = Y.reshape((Y.shape[0],))
Y_test = Y_test.reshape((Y_test.shape[0],))
return X, Y, X_test, Y_test | python | def load_mnist(training_num=50000):
"""Load mnist dataset"""
data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz')
if not os.path.isfile(data_path):
from six.moves import urllib
origin = (
'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz'
)
print('Downloading data from %s to %s' % (origin, data_path))
ctx = ssl._create_unverified_context()
with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f:
f.write(u.read())
print('Done!')
dat = numpy.load(data_path)
X = (dat['X'][:training_num] / 126.0).astype('float32')
Y = dat['Y'][:training_num]
X_test = (dat['X_test'] / 126.0).astype('float32')
Y_test = dat['Y_test']
Y = Y.reshape((Y.shape[0],))
Y_test = Y_test.reshape((Y_test.shape[0],))
return X, Y, X_test, Y_test | [
"def",
"load_mnist",
"(",
"training_num",
"=",
"50000",
")",
":",
"data_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"'__file__'",
")",
")",
",",
"'mnist.npz'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"data_path",
")",
":",
"from",
"six",
".",
"moves",
"import",
"urllib",
"origin",
"=",
"(",
"'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz'",
")",
"print",
"(",
"'Downloading data from %s to %s'",
"%",
"(",
"origin",
",",
"data_path",
")",
")",
"ctx",
"=",
"ssl",
".",
"_create_unverified_context",
"(",
")",
"with",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"origin",
",",
"context",
"=",
"ctx",
")",
"as",
"u",
",",
"open",
"(",
"data_path",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"u",
".",
"read",
"(",
")",
")",
"print",
"(",
"'Done!'",
")",
"dat",
"=",
"numpy",
".",
"load",
"(",
"data_path",
")",
"X",
"=",
"(",
"dat",
"[",
"'X'",
"]",
"[",
":",
"training_num",
"]",
"/",
"126.0",
")",
".",
"astype",
"(",
"'float32'",
")",
"Y",
"=",
"dat",
"[",
"'Y'",
"]",
"[",
":",
"training_num",
"]",
"X_test",
"=",
"(",
"dat",
"[",
"'X_test'",
"]",
"/",
"126.0",
")",
".",
"astype",
"(",
"'float32'",
")",
"Y_test",
"=",
"dat",
"[",
"'Y_test'",
"]",
"Y",
"=",
"Y",
".",
"reshape",
"(",
"(",
"Y",
".",
"shape",
"[",
"0",
"]",
",",
")",
")",
"Y_test",
"=",
"Y_test",
".",
"reshape",
"(",
"(",
"Y_test",
".",
"shape",
"[",
"0",
"]",
",",
")",
")",
"return",
"X",
",",
"Y",
",",
"X_test",
",",
"Y_test"
] | Load mnist dataset | [
"Load",
"mnist",
"dataset"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/data_loader.py#L24-L44 |
23,464 | apache/incubator-mxnet | python/mxnet/runtime.py | feature_list | def feature_list():
"""
Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects
"""
lib_features_c_array = ctypes.POINTER(Feature)()
lib_features_size = ctypes.c_size_t()
check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size)))
features = [lib_features_c_array[i] for i in range(lib_features_size.value)]
return features | python | def feature_list():
"""
Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects
"""
lib_features_c_array = ctypes.POINTER(Feature)()
lib_features_size = ctypes.c_size_t()
check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size)))
features = [lib_features_c_array[i] for i in range(lib_features_size.value)]
return features | [
"def",
"feature_list",
"(",
")",
":",
"lib_features_c_array",
"=",
"ctypes",
".",
"POINTER",
"(",
"Feature",
")",
"(",
")",
"lib_features_size",
"=",
"ctypes",
".",
"c_size_t",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXLibInfoFeatures",
"(",
"ctypes",
".",
"byref",
"(",
"lib_features_c_array",
")",
",",
"ctypes",
".",
"byref",
"(",
"lib_features_size",
")",
")",
")",
"features",
"=",
"[",
"lib_features_c_array",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"lib_features_size",
".",
"value",
")",
"]",
"return",
"features"
] | Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects | [
"Check",
"the",
"library",
"for",
"compile",
"-",
"time",
"features",
".",
"The",
"list",
"of",
"features",
"are",
"maintained",
"in",
"libinfo",
".",
"h",
"and",
"libinfo",
".",
"cc"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/runtime.py#L57-L70 |
23,465 | apache/incubator-mxnet | python/mxnet/runtime.py | Features.is_enabled | def is_enabled(self, feature_name):
"""
Check for a particular feature by name
Parameters
----------
feature_name: str
The name of a valid feature as string for example 'CUDA'
Returns
-------
Boolean
True if it's enabled, False if it's disabled, RuntimeError if the feature is not known
"""
feature_name = feature_name.upper()
if feature_name not in self:
raise RuntimeError("Feature '{}' is unknown, known features are: {}".format(
feature_name, list(self.keys())))
return self[feature_name].enabled | python | def is_enabled(self, feature_name):
"""
Check for a particular feature by name
Parameters
----------
feature_name: str
The name of a valid feature as string for example 'CUDA'
Returns
-------
Boolean
True if it's enabled, False if it's disabled, RuntimeError if the feature is not known
"""
feature_name = feature_name.upper()
if feature_name not in self:
raise RuntimeError("Feature '{}' is unknown, known features are: {}".format(
feature_name, list(self.keys())))
return self[feature_name].enabled | [
"def",
"is_enabled",
"(",
"self",
",",
"feature_name",
")",
":",
"feature_name",
"=",
"feature_name",
".",
"upper",
"(",
")",
"if",
"feature_name",
"not",
"in",
"self",
":",
"raise",
"RuntimeError",
"(",
"\"Feature '{}' is unknown, known features are: {}\"",
".",
"format",
"(",
"feature_name",
",",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
")",
")",
"return",
"self",
"[",
"feature_name",
"]",
".",
"enabled"
] | Check for a particular feature by name
Parameters
----------
feature_name: str
The name of a valid feature as string for example 'CUDA'
Returns
-------
Boolean
True if it's enabled, False if it's disabled, RuntimeError if the feature is not known | [
"Check",
"for",
"a",
"particular",
"feature",
"by",
"name"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/runtime.py#L82-L100 |
23,466 | apache/incubator-mxnet | example/ssd/dataset/pascal_voc.py | PascalVoc.cache_path | def cache_path(self):
"""
make a directory to store all caches
Returns:
---------
cache path
"""
cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache')
if not os.path.exists(cache_path):
os.mkdir(cache_path)
return cache_path | python | def cache_path(self):
"""
make a directory to store all caches
Returns:
---------
cache path
"""
cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache')
if not os.path.exists(cache_path):
os.mkdir(cache_path)
return cache_path | [
"def",
"cache_path",
"(",
"self",
")",
":",
"cache_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'..'",
",",
"'cache'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cache_path",
")",
":",
"os",
".",
"mkdir",
"(",
"cache_path",
")",
"return",
"cache_path"
] | make a directory to store all caches
Returns:
---------
cache path | [
"make",
"a",
"directory",
"to",
"store",
"all",
"caches"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L67-L78 |
23,467 | apache/incubator-mxnet | example/ssd/dataset/pascal_voc.py | PascalVoc.do_python_eval | def do_python_eval(self):
"""
python evaluation wrapper
Returns:
----------
None
"""
annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml')
imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')
cache_dir = os.path.join(self.cache_path, self.name)
aps = []
# The PASCAL VOC metric changed in 2010
use_07_metric = True if int(self.year) < 2010 else False
print('VOC07 metric? ' + ('Y' if use_07_metric else 'No'))
for cls_ind, cls in enumerate(self.classes):
filename = self.get_result_file_template().format(cls)
rec, prec, ap = voc_eval(filename, annopath, imageset_file, cls, cache_dir,
ovthresh=0.5, use_07_metric=use_07_metric)
aps += [ap]
print('AP for {} = {:.4f}'.format(cls, ap))
print('Mean AP = {:.4f}'.format(np.mean(aps))) | python | def do_python_eval(self):
"""
python evaluation wrapper
Returns:
----------
None
"""
annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml')
imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')
cache_dir = os.path.join(self.cache_path, self.name)
aps = []
# The PASCAL VOC metric changed in 2010
use_07_metric = True if int(self.year) < 2010 else False
print('VOC07 metric? ' + ('Y' if use_07_metric else 'No'))
for cls_ind, cls in enumerate(self.classes):
filename = self.get_result_file_template().format(cls)
rec, prec, ap = voc_eval(filename, annopath, imageset_file, cls, cache_dir,
ovthresh=0.5, use_07_metric=use_07_metric)
aps += [ap]
print('AP for {} = {:.4f}'.format(cls, ap))
print('Mean AP = {:.4f}'.format(np.mean(aps))) | [
"def",
"do_python_eval",
"(",
"self",
")",
":",
"annopath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'Annotations'",
",",
"'{:s}.xml'",
")",
"imageset_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'ImageSets'",
",",
"'Main'",
",",
"self",
".",
"image_set",
"+",
"'.txt'",
")",
"cache_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_path",
",",
"self",
".",
"name",
")",
"aps",
"=",
"[",
"]",
"# The PASCAL VOC metric changed in 2010",
"use_07_metric",
"=",
"True",
"if",
"int",
"(",
"self",
".",
"year",
")",
"<",
"2010",
"else",
"False",
"print",
"(",
"'VOC07 metric? '",
"+",
"(",
"'Y'",
"if",
"use_07_metric",
"else",
"'No'",
")",
")",
"for",
"cls_ind",
",",
"cls",
"in",
"enumerate",
"(",
"self",
".",
"classes",
")",
":",
"filename",
"=",
"self",
".",
"get_result_file_template",
"(",
")",
".",
"format",
"(",
"cls",
")",
"rec",
",",
"prec",
",",
"ap",
"=",
"voc_eval",
"(",
"filename",
",",
"annopath",
",",
"imageset_file",
",",
"cls",
",",
"cache_dir",
",",
"ovthresh",
"=",
"0.5",
",",
"use_07_metric",
"=",
"use_07_metric",
")",
"aps",
"+=",
"[",
"ap",
"]",
"print",
"(",
"'AP for {} = {:.4f}'",
".",
"format",
"(",
"cls",
",",
"ap",
")",
")",
"print",
"(",
"'Mean AP = {:.4f}'",
".",
"format",
"(",
"np",
".",
"mean",
"(",
"aps",
")",
")",
")"
] | python evaluation wrapper
Returns:
----------
None | [
"python",
"evaluation",
"wrapper"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L255-L276 |
23,468 | apache/incubator-mxnet | python/mxnet/image/detection.py | CreateMultiRandCropAugmenter | def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0), min_eject_coverage=0.3,
max_attempts=50, skip_prob=0):
"""Helper function to create multiple random crop augmenters.
Parameters
----------
min_object_covered : float or list of float, default=0.1
The cropped area of the image must contain at least this fraction of
any bounding box supplied. The value of this parameter should be non-negative.
In the case of 0, the cropped area does not need to overlap any of the
bounding boxes supplied.
min_eject_coverage : float or list of float, default=0.3
The minimum coverage of cropped sample w.r.t its original size. With this
constraint, objects that have marginal area after crop will be discarded.
aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33)
The cropped area of the image must have an aspect ratio = width / height
within this range.
area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0)
The cropped area of the image must contain a fraction of the supplied
image within in this range.
max_attempts : int or list of int, default=50
Number of attempts at generating a cropped/padded region of the image of the
specified constraints. After max_attempts failures, return the original image.
Examples
--------
>>> # An example of creating multiple random crop augmenters
>>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters
>>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters
>>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)]
>>> min_eject_coverage = 0.3
>>> max_attempts = 50
>>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered,
aspect_ratio_range=aspect_ratio_range, area_range=area_range,
min_eject_coverage=min_eject_coverage, max_attempts=max_attempts,
skip_prob=0)
>>> aug.dumps() # show some details
"""
def align_parameters(params):
"""Align parameters as pairs"""
out_params = []
num = 1
for p in params:
if not isinstance(p, list):
p = [p]
out_params.append(p)
num = max(num, len(p))
# align for each param
for k, p in enumerate(out_params):
if len(p) != num:
assert len(p) == 1
out_params[k] = p * num
return out_params
aligned_params = align_parameters([min_object_covered, aspect_ratio_range, area_range,
min_eject_coverage, max_attempts])
augs = []
for moc, arr, ar, mec, ma in zip(*aligned_params):
augs.append(DetRandomCropAug(min_object_covered=moc, aspect_ratio_range=arr,
area_range=ar, min_eject_coverage=mec, max_attempts=ma))
return DetRandomSelectAug(augs, skip_prob=skip_prob) | python | def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0), min_eject_coverage=0.3,
max_attempts=50, skip_prob=0):
"""Helper function to create multiple random crop augmenters.
Parameters
----------
min_object_covered : float or list of float, default=0.1
The cropped area of the image must contain at least this fraction of
any bounding box supplied. The value of this parameter should be non-negative.
In the case of 0, the cropped area does not need to overlap any of the
bounding boxes supplied.
min_eject_coverage : float or list of float, default=0.3
The minimum coverage of cropped sample w.r.t its original size. With this
constraint, objects that have marginal area after crop will be discarded.
aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33)
The cropped area of the image must have an aspect ratio = width / height
within this range.
area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0)
The cropped area of the image must contain a fraction of the supplied
image within in this range.
max_attempts : int or list of int, default=50
Number of attempts at generating a cropped/padded region of the image of the
specified constraints. After max_attempts failures, return the original image.
Examples
--------
>>> # An example of creating multiple random crop augmenters
>>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters
>>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters
>>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)]
>>> min_eject_coverage = 0.3
>>> max_attempts = 50
>>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered,
aspect_ratio_range=aspect_ratio_range, area_range=area_range,
min_eject_coverage=min_eject_coverage, max_attempts=max_attempts,
skip_prob=0)
>>> aug.dumps() # show some details
"""
def align_parameters(params):
"""Align parameters as pairs"""
out_params = []
num = 1
for p in params:
if not isinstance(p, list):
p = [p]
out_params.append(p)
num = max(num, len(p))
# align for each param
for k, p in enumerate(out_params):
if len(p) != num:
assert len(p) == 1
out_params[k] = p * num
return out_params
aligned_params = align_parameters([min_object_covered, aspect_ratio_range, area_range,
min_eject_coverage, max_attempts])
augs = []
for moc, arr, ar, mec, ma in zip(*aligned_params):
augs.append(DetRandomCropAug(min_object_covered=moc, aspect_ratio_range=arr,
area_range=ar, min_eject_coverage=mec, max_attempts=ma))
return DetRandomSelectAug(augs, skip_prob=skip_prob) | [
"def",
"CreateMultiRandCropAugmenter",
"(",
"min_object_covered",
"=",
"0.1",
",",
"aspect_ratio_range",
"=",
"(",
"0.75",
",",
"1.33",
")",
",",
"area_range",
"=",
"(",
"0.05",
",",
"1.0",
")",
",",
"min_eject_coverage",
"=",
"0.3",
",",
"max_attempts",
"=",
"50",
",",
"skip_prob",
"=",
"0",
")",
":",
"def",
"align_parameters",
"(",
"params",
")",
":",
"\"\"\"Align parameters as pairs\"\"\"",
"out_params",
"=",
"[",
"]",
"num",
"=",
"1",
"for",
"p",
"in",
"params",
":",
"if",
"not",
"isinstance",
"(",
"p",
",",
"list",
")",
":",
"p",
"=",
"[",
"p",
"]",
"out_params",
".",
"append",
"(",
"p",
")",
"num",
"=",
"max",
"(",
"num",
",",
"len",
"(",
"p",
")",
")",
"# align for each param",
"for",
"k",
",",
"p",
"in",
"enumerate",
"(",
"out_params",
")",
":",
"if",
"len",
"(",
"p",
")",
"!=",
"num",
":",
"assert",
"len",
"(",
"p",
")",
"==",
"1",
"out_params",
"[",
"k",
"]",
"=",
"p",
"*",
"num",
"return",
"out_params",
"aligned_params",
"=",
"align_parameters",
"(",
"[",
"min_object_covered",
",",
"aspect_ratio_range",
",",
"area_range",
",",
"min_eject_coverage",
",",
"max_attempts",
"]",
")",
"augs",
"=",
"[",
"]",
"for",
"moc",
",",
"arr",
",",
"ar",
",",
"mec",
",",
"ma",
"in",
"zip",
"(",
"*",
"aligned_params",
")",
":",
"augs",
".",
"append",
"(",
"DetRandomCropAug",
"(",
"min_object_covered",
"=",
"moc",
",",
"aspect_ratio_range",
"=",
"arr",
",",
"area_range",
"=",
"ar",
",",
"min_eject_coverage",
"=",
"mec",
",",
"max_attempts",
"=",
"ma",
")",
")",
"return",
"DetRandomSelectAug",
"(",
"augs",
",",
"skip_prob",
"=",
"skip_prob",
")"
] | Helper function to create multiple random crop augmenters.
Parameters
----------
min_object_covered : float or list of float, default=0.1
The cropped area of the image must contain at least this fraction of
any bounding box supplied. The value of this parameter should be non-negative.
In the case of 0, the cropped area does not need to overlap any of the
bounding boxes supplied.
min_eject_coverage : float or list of float, default=0.3
The minimum coverage of cropped sample w.r.t its original size. With this
constraint, objects that have marginal area after crop will be discarded.
aspect_ratio_range : tuple of floats or list of tuple of floats, default=(0.75, 1.33)
The cropped area of the image must have an aspect ratio = width / height
within this range.
area_range : tuple of floats or list of tuple of floats, default=(0.05, 1.0)
The cropped area of the image must contain a fraction of the supplied
image within in this range.
max_attempts : int or list of int, default=50
Number of attempts at generating a cropped/padded region of the image of the
specified constraints. After max_attempts failures, return the original image.
Examples
--------
>>> # An example of creating multiple random crop augmenters
>>> min_object_covered = [0.1, 0.3, 0.5, 0.7, 0.9] # use 5 augmenters
>>> aspect_ratio_range = (0.75, 1.33) # use same range for all augmenters
>>> area_range = [(0.1, 1.0), (0.2, 1.0), (0.2, 1.0), (0.3, 0.9), (0.5, 1.0)]
>>> min_eject_coverage = 0.3
>>> max_attempts = 50
>>> aug = mx.image.det.CreateMultiRandCropAugmenter(min_object_covered=min_object_covered,
aspect_ratio_range=aspect_ratio_range, area_range=area_range,
min_eject_coverage=min_eject_coverage, max_attempts=max_attempts,
skip_prob=0)
>>> aug.dumps() # show some details | [
"Helper",
"function",
"to",
"create",
"multiple",
"random",
"crop",
"augmenters",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L417-L479 |
23,469 | apache/incubator-mxnet | python/mxnet/image/detection.py | CreateDetAugmenter | def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0,
rand_mirror=False, mean=None, std=None, brightness=0, contrast=0,
saturation=0, pca_noise=0, hue=0, inter_method=2, min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 3.0),
min_eject_coverage=0.3, max_attempts=50, pad_val=(127, 127, 127)):
"""Create augmenters for detection.
Parameters
----------
data_shape : tuple of int
Shape for output data
resize : int
Resize shorter edge if larger than 0 at the begining
rand_crop : float
[0, 1], probability to apply random cropping
rand_pad : float
[0, 1], probability to apply random padding
rand_gray : float
[0, 1], probability to convert to grayscale for all channels
rand_mirror : bool
Whether to apply horizontal flip to image with probability 0.5
mean : np.ndarray or None
Mean pixel values for [r, g, b]
std : np.ndarray or None
Standard deviations for [r, g, b]
brightness : float
Brightness jittering range (percent)
contrast : float
Contrast jittering range (percent)
saturation : float
Saturation jittering range (percent)
hue : float
Hue jittering range (percent)
pca_noise : float
Pca noise level (percent)
inter_method : int, default=2(Area-based)
Interpolation method for all resizing operations
Possible values:
0: Nearest Neighbors Interpolation.
1: Bilinear interpolation.
2: Area-based (resampling using pixel area relation). It may be a
preferred method for image decimation, as it gives moire-free
results. But when the image is zoomed, it is similar to the Nearest
Neighbors method. (used by default).
3: Bicubic interpolation over 4x4 pixel neighborhood.
4: Lanczos interpolation over 8x8 pixel neighborhood.
9: Cubic for enlarge, area for shrink, bilinear for others
10: Random select from interpolation method metioned above.
Note:
When shrinking an image, it will generally look best with AREA-based
interpolation, whereas, when enlarging an image, it will generally look best
with Bicubic (slow) or Bilinear (faster but still looks OK).
min_object_covered : float
The cropped area of the image must contain at least this fraction of
any bounding box supplied. The value of this parameter should be non-negative.
In the case of 0, the cropped area does not need to overlap any of the
bounding boxes supplied.
min_eject_coverage : float
The minimum coverage of cropped sample w.r.t its original size. With this
constraint, objects that have marginal area after crop will be discarded.
aspect_ratio_range : tuple of floats
The cropped area of the image must have an aspect ratio = width / height
within this range.
area_range : tuple of floats
The cropped area of the image must contain a fraction of the supplied
image within in this range.
max_attempts : int
Number of attempts at generating a cropped/padded region of the image of the
specified constraints. After max_attempts failures, return the original image.
pad_val: float
Pixel value to be filled when padding is enabled. pad_val will automatically
be subtracted by mean and divided by std if applicable.
Examples
--------
>>> # An example of creating multiple augmenters
>>> augs = mx.image.CreateDetAugmenter(data_shape=(3, 300, 300), rand_crop=0.5,
... rand_pad=0.5, rand_mirror=True, mean=True, brightness=0.125, contrast=0.125,
... saturation=0.125, pca_noise=0.05, inter_method=10, min_object_covered=[0.3, 0.5, 0.9],
... area_range=(0.3, 3.0))
>>> # dump the details
>>> for aug in augs:
... aug.dumps()
"""
auglist = []
if resize > 0:
auglist.append(DetBorrowAug(ResizeAug(resize, inter_method)))
if rand_crop > 0:
crop_augs = CreateMultiRandCropAugmenter(min_object_covered, aspect_ratio_range,
area_range, min_eject_coverage,
max_attempts, skip_prob=(1 - rand_crop))
auglist.append(crop_augs)
if rand_mirror > 0:
auglist.append(DetHorizontalFlipAug(0.5))
# apply random padding as late as possible to save computation
if rand_pad > 0:
pad_aug = DetRandomPadAug(aspect_ratio_range,
(1.0, area_range[1]), max_attempts, pad_val)
auglist.append(DetRandomSelectAug([pad_aug], 1 - rand_pad))
# force resize
auglist.append(DetBorrowAug(ForceResizeAug((data_shape[2], data_shape[1]), inter_method)))
auglist.append(DetBorrowAug(CastAug()))
if brightness or contrast or saturation:
auglist.append(DetBorrowAug(ColorJitterAug(brightness, contrast, saturation)))
if hue:
auglist.append(DetBorrowAug(HueJitterAug(hue)))
if pca_noise > 0:
eigval = np.array([55.46, 4.794, 1.148])
eigvec = np.array([[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]])
auglist.append(DetBorrowAug(LightingAug(pca_noise, eigval, eigvec)))
if rand_gray > 0:
auglist.append(DetBorrowAug(RandomGrayAug(rand_gray)))
if mean is True:
mean = np.array([123.68, 116.28, 103.53])
elif mean is not None:
assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3]
if std is True:
std = np.array([58.395, 57.12, 57.375])
elif std is not None:
assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3]
if mean is not None or std is not None:
auglist.append(DetBorrowAug(ColorNormalizeAug(mean, std)))
return auglist | python | def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0,
rand_mirror=False, mean=None, std=None, brightness=0, contrast=0,
saturation=0, pca_noise=0, hue=0, inter_method=2, min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 3.0),
min_eject_coverage=0.3, max_attempts=50, pad_val=(127, 127, 127)):
"""Create augmenters for detection.
Parameters
----------
data_shape : tuple of int
Shape for output data
resize : int
Resize shorter edge if larger than 0 at the begining
rand_crop : float
[0, 1], probability to apply random cropping
rand_pad : float
[0, 1], probability to apply random padding
rand_gray : float
[0, 1], probability to convert to grayscale for all channels
rand_mirror : bool
Whether to apply horizontal flip to image with probability 0.5
mean : np.ndarray or None
Mean pixel values for [r, g, b]
std : np.ndarray or None
Standard deviations for [r, g, b]
brightness : float
Brightness jittering range (percent)
contrast : float
Contrast jittering range (percent)
saturation : float
Saturation jittering range (percent)
hue : float
Hue jittering range (percent)
pca_noise : float
Pca noise level (percent)
inter_method : int, default=2(Area-based)
Interpolation method for all resizing operations
Possible values:
0: Nearest Neighbors Interpolation.
1: Bilinear interpolation.
2: Area-based (resampling using pixel area relation). It may be a
preferred method for image decimation, as it gives moire-free
results. But when the image is zoomed, it is similar to the Nearest
Neighbors method. (used by default).
3: Bicubic interpolation over 4x4 pixel neighborhood.
4: Lanczos interpolation over 8x8 pixel neighborhood.
9: Cubic for enlarge, area for shrink, bilinear for others
10: Random select from interpolation method metioned above.
Note:
When shrinking an image, it will generally look best with AREA-based
interpolation, whereas, when enlarging an image, it will generally look best
with Bicubic (slow) or Bilinear (faster but still looks OK).
min_object_covered : float
The cropped area of the image must contain at least this fraction of
any bounding box supplied. The value of this parameter should be non-negative.
In the case of 0, the cropped area does not need to overlap any of the
bounding boxes supplied.
min_eject_coverage : float
The minimum coverage of cropped sample w.r.t its original size. With this
constraint, objects that have marginal area after crop will be discarded.
aspect_ratio_range : tuple of floats
The cropped area of the image must have an aspect ratio = width / height
within this range.
area_range : tuple of floats
The cropped area of the image must contain a fraction of the supplied
image within in this range.
max_attempts : int
Number of attempts at generating a cropped/padded region of the image of the
specified constraints. After max_attempts failures, return the original image.
pad_val: float
Pixel value to be filled when padding is enabled. pad_val will automatically
be subtracted by mean and divided by std if applicable.
Examples
--------
>>> # An example of creating multiple augmenters
>>> augs = mx.image.CreateDetAugmenter(data_shape=(3, 300, 300), rand_crop=0.5,
... rand_pad=0.5, rand_mirror=True, mean=True, brightness=0.125, contrast=0.125,
... saturation=0.125, pca_noise=0.05, inter_method=10, min_object_covered=[0.3, 0.5, 0.9],
... area_range=(0.3, 3.0))
>>> # dump the details
>>> for aug in augs:
... aug.dumps()
"""
auglist = []
if resize > 0:
auglist.append(DetBorrowAug(ResizeAug(resize, inter_method)))
if rand_crop > 0:
crop_augs = CreateMultiRandCropAugmenter(min_object_covered, aspect_ratio_range,
area_range, min_eject_coverage,
max_attempts, skip_prob=(1 - rand_crop))
auglist.append(crop_augs)
if rand_mirror > 0:
auglist.append(DetHorizontalFlipAug(0.5))
# apply random padding as late as possible to save computation
if rand_pad > 0:
pad_aug = DetRandomPadAug(aspect_ratio_range,
(1.0, area_range[1]), max_attempts, pad_val)
auglist.append(DetRandomSelectAug([pad_aug], 1 - rand_pad))
# force resize
auglist.append(DetBorrowAug(ForceResizeAug((data_shape[2], data_shape[1]), inter_method)))
auglist.append(DetBorrowAug(CastAug()))
if brightness or contrast or saturation:
auglist.append(DetBorrowAug(ColorJitterAug(brightness, contrast, saturation)))
if hue:
auglist.append(DetBorrowAug(HueJitterAug(hue)))
if pca_noise > 0:
eigval = np.array([55.46, 4.794, 1.148])
eigvec = np.array([[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]])
auglist.append(DetBorrowAug(LightingAug(pca_noise, eigval, eigvec)))
if rand_gray > 0:
auglist.append(DetBorrowAug(RandomGrayAug(rand_gray)))
if mean is True:
mean = np.array([123.68, 116.28, 103.53])
elif mean is not None:
assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3]
if std is True:
std = np.array([58.395, 57.12, 57.375])
elif std is not None:
assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3]
if mean is not None or std is not None:
auglist.append(DetBorrowAug(ColorNormalizeAug(mean, std)))
return auglist | [
"def",
"CreateDetAugmenter",
"(",
"data_shape",
",",
"resize",
"=",
"0",
",",
"rand_crop",
"=",
"0",
",",
"rand_pad",
"=",
"0",
",",
"rand_gray",
"=",
"0",
",",
"rand_mirror",
"=",
"False",
",",
"mean",
"=",
"None",
",",
"std",
"=",
"None",
",",
"brightness",
"=",
"0",
",",
"contrast",
"=",
"0",
",",
"saturation",
"=",
"0",
",",
"pca_noise",
"=",
"0",
",",
"hue",
"=",
"0",
",",
"inter_method",
"=",
"2",
",",
"min_object_covered",
"=",
"0.1",
",",
"aspect_ratio_range",
"=",
"(",
"0.75",
",",
"1.33",
")",
",",
"area_range",
"=",
"(",
"0.05",
",",
"3.0",
")",
",",
"min_eject_coverage",
"=",
"0.3",
",",
"max_attempts",
"=",
"50",
",",
"pad_val",
"=",
"(",
"127",
",",
"127",
",",
"127",
")",
")",
":",
"auglist",
"=",
"[",
"]",
"if",
"resize",
">",
"0",
":",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"ResizeAug",
"(",
"resize",
",",
"inter_method",
")",
")",
")",
"if",
"rand_crop",
">",
"0",
":",
"crop_augs",
"=",
"CreateMultiRandCropAugmenter",
"(",
"min_object_covered",
",",
"aspect_ratio_range",
",",
"area_range",
",",
"min_eject_coverage",
",",
"max_attempts",
",",
"skip_prob",
"=",
"(",
"1",
"-",
"rand_crop",
")",
")",
"auglist",
".",
"append",
"(",
"crop_augs",
")",
"if",
"rand_mirror",
">",
"0",
":",
"auglist",
".",
"append",
"(",
"DetHorizontalFlipAug",
"(",
"0.5",
")",
")",
"# apply random padding as late as possible to save computation",
"if",
"rand_pad",
">",
"0",
":",
"pad_aug",
"=",
"DetRandomPadAug",
"(",
"aspect_ratio_range",
",",
"(",
"1.0",
",",
"area_range",
"[",
"1",
"]",
")",
",",
"max_attempts",
",",
"pad_val",
")",
"auglist",
".",
"append",
"(",
"DetRandomSelectAug",
"(",
"[",
"pad_aug",
"]",
",",
"1",
"-",
"rand_pad",
")",
")",
"# force resize",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"ForceResizeAug",
"(",
"(",
"data_shape",
"[",
"2",
"]",
",",
"data_shape",
"[",
"1",
"]",
")",
",",
"inter_method",
")",
")",
")",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"CastAug",
"(",
")",
")",
")",
"if",
"brightness",
"or",
"contrast",
"or",
"saturation",
":",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"ColorJitterAug",
"(",
"brightness",
",",
"contrast",
",",
"saturation",
")",
")",
")",
"if",
"hue",
":",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"HueJitterAug",
"(",
"hue",
")",
")",
")",
"if",
"pca_noise",
">",
"0",
":",
"eigval",
"=",
"np",
".",
"array",
"(",
"[",
"55.46",
",",
"4.794",
",",
"1.148",
"]",
")",
"eigvec",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"-",
"0.5675",
",",
"0.7192",
",",
"0.4009",
"]",
",",
"[",
"-",
"0.5808",
",",
"-",
"0.0045",
",",
"-",
"0.8140",
"]",
",",
"[",
"-",
"0.5836",
",",
"-",
"0.6948",
",",
"0.4203",
"]",
"]",
")",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"LightingAug",
"(",
"pca_noise",
",",
"eigval",
",",
"eigvec",
")",
")",
")",
"if",
"rand_gray",
">",
"0",
":",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"RandomGrayAug",
"(",
"rand_gray",
")",
")",
")",
"if",
"mean",
"is",
"True",
":",
"mean",
"=",
"np",
".",
"array",
"(",
"[",
"123.68",
",",
"116.28",
",",
"103.53",
"]",
")",
"elif",
"mean",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"mean",
",",
"np",
".",
"ndarray",
")",
"and",
"mean",
".",
"shape",
"[",
"0",
"]",
"in",
"[",
"1",
",",
"3",
"]",
"if",
"std",
"is",
"True",
":",
"std",
"=",
"np",
".",
"array",
"(",
"[",
"58.395",
",",
"57.12",
",",
"57.375",
"]",
")",
"elif",
"std",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"std",
",",
"np",
".",
"ndarray",
")",
"and",
"std",
".",
"shape",
"[",
"0",
"]",
"in",
"[",
"1",
",",
"3",
"]",
"if",
"mean",
"is",
"not",
"None",
"or",
"std",
"is",
"not",
"None",
":",
"auglist",
".",
"append",
"(",
"DetBorrowAug",
"(",
"ColorNormalizeAug",
"(",
"mean",
",",
"std",
")",
")",
")",
"return",
"auglist"
] | Create augmenters for detection.
Parameters
----------
data_shape : tuple of int
Shape for output data
resize : int
Resize shorter edge if larger than 0 at the begining
rand_crop : float
[0, 1], probability to apply random cropping
rand_pad : float
[0, 1], probability to apply random padding
rand_gray : float
[0, 1], probability to convert to grayscale for all channels
rand_mirror : bool
Whether to apply horizontal flip to image with probability 0.5
mean : np.ndarray or None
Mean pixel values for [r, g, b]
std : np.ndarray or None
Standard deviations for [r, g, b]
brightness : float
Brightness jittering range (percent)
contrast : float
Contrast jittering range (percent)
saturation : float
Saturation jittering range (percent)
hue : float
Hue jittering range (percent)
pca_noise : float
Pca noise level (percent)
inter_method : int, default=2(Area-based)
Interpolation method for all resizing operations
Possible values:
0: Nearest Neighbors Interpolation.
1: Bilinear interpolation.
2: Area-based (resampling using pixel area relation). It may be a
preferred method for image decimation, as it gives moire-free
results. But when the image is zoomed, it is similar to the Nearest
Neighbors method. (used by default).
3: Bicubic interpolation over 4x4 pixel neighborhood.
4: Lanczos interpolation over 8x8 pixel neighborhood.
9: Cubic for enlarge, area for shrink, bilinear for others
10: Random select from interpolation method metioned above.
Note:
When shrinking an image, it will generally look best with AREA-based
interpolation, whereas, when enlarging an image, it will generally look best
with Bicubic (slow) or Bilinear (faster but still looks OK).
min_object_covered : float
The cropped area of the image must contain at least this fraction of
any bounding box supplied. The value of this parameter should be non-negative.
In the case of 0, the cropped area does not need to overlap any of the
bounding boxes supplied.
min_eject_coverage : float
The minimum coverage of cropped sample w.r.t its original size. With this
constraint, objects that have marginal area after crop will be discarded.
aspect_ratio_range : tuple of floats
The cropped area of the image must have an aspect ratio = width / height
within this range.
area_range : tuple of floats
The cropped area of the image must contain a fraction of the supplied
image within in this range.
max_attempts : int
Number of attempts at generating a cropped/padded region of the image of the
specified constraints. After max_attempts failures, return the original image.
pad_val: float
Pixel value to be filled when padding is enabled. pad_val will automatically
be subtracted by mean and divided by std if applicable.
Examples
--------
>>> # An example of creating multiple augmenters
>>> augs = mx.image.CreateDetAugmenter(data_shape=(3, 300, 300), rand_crop=0.5,
... rand_pad=0.5, rand_mirror=True, mean=True, brightness=0.125, contrast=0.125,
... saturation=0.125, pca_noise=0.05, inter_method=10, min_object_covered=[0.3, 0.5, 0.9],
... area_range=(0.3, 3.0))
>>> # dump the details
>>> for aug in augs:
... aug.dumps() | [
"Create",
"augmenters",
"for",
"detection",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L482-L621 |
23,470 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomSelectAug.dumps | def dumps(self):
"""Override default."""
return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]] | python | def dumps(self):
"""Override default."""
return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]] | [
"def",
"dumps",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"[",
"x",
".",
"dumps",
"(",
")",
"for",
"x",
"in",
"self",
".",
"aug_list",
"]",
"]"
] | Override default. | [
"Override",
"default",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L113-L115 |
23,471 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomCropAug._calculate_areas | def _calculate_areas(self, label):
"""Calculate areas for multiple labels"""
heights = np.maximum(0, label[:, 3] - label[:, 1])
widths = np.maximum(0, label[:, 2] - label[:, 0])
return heights * widths | python | def _calculate_areas(self, label):
"""Calculate areas for multiple labels"""
heights = np.maximum(0, label[:, 3] - label[:, 1])
widths = np.maximum(0, label[:, 2] - label[:, 0])
return heights * widths | [
"def",
"_calculate_areas",
"(",
"self",
",",
"label",
")",
":",
"heights",
"=",
"np",
".",
"maximum",
"(",
"0",
",",
"label",
"[",
":",
",",
"3",
"]",
"-",
"label",
"[",
":",
",",
"1",
"]",
")",
"widths",
"=",
"np",
".",
"maximum",
"(",
"0",
",",
"label",
"[",
":",
",",
"2",
"]",
"-",
"label",
"[",
":",
",",
"0",
"]",
")",
"return",
"heights",
"*",
"widths"
] | Calculate areas for multiple labels | [
"Calculate",
"areas",
"for",
"multiple",
"labels"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L213-L217 |
23,472 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomCropAug._intersect | def _intersect(self, label, xmin, ymin, xmax, ymax):
"""Calculate intersect areas, normalized."""
left = np.maximum(label[:, 0], xmin)
right = np.minimum(label[:, 2], xmax)
top = np.maximum(label[:, 1], ymin)
bot = np.minimum(label[:, 3], ymax)
invalid = np.where(np.logical_or(left >= right, top >= bot))[0]
out = label.copy()
out[:, 0] = left
out[:, 1] = top
out[:, 2] = right
out[:, 3] = bot
out[invalid, :] = 0
return out | python | def _intersect(self, label, xmin, ymin, xmax, ymax):
"""Calculate intersect areas, normalized."""
left = np.maximum(label[:, 0], xmin)
right = np.minimum(label[:, 2], xmax)
top = np.maximum(label[:, 1], ymin)
bot = np.minimum(label[:, 3], ymax)
invalid = np.where(np.logical_or(left >= right, top >= bot))[0]
out = label.copy()
out[:, 0] = left
out[:, 1] = top
out[:, 2] = right
out[:, 3] = bot
out[invalid, :] = 0
return out | [
"def",
"_intersect",
"(",
"self",
",",
"label",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
")",
":",
"left",
"=",
"np",
".",
"maximum",
"(",
"label",
"[",
":",
",",
"0",
"]",
",",
"xmin",
")",
"right",
"=",
"np",
".",
"minimum",
"(",
"label",
"[",
":",
",",
"2",
"]",
",",
"xmax",
")",
"top",
"=",
"np",
".",
"maximum",
"(",
"label",
"[",
":",
",",
"1",
"]",
",",
"ymin",
")",
"bot",
"=",
"np",
".",
"minimum",
"(",
"label",
"[",
":",
",",
"3",
"]",
",",
"ymax",
")",
"invalid",
"=",
"np",
".",
"where",
"(",
"np",
".",
"logical_or",
"(",
"left",
">=",
"right",
",",
"top",
">=",
"bot",
")",
")",
"[",
"0",
"]",
"out",
"=",
"label",
".",
"copy",
"(",
")",
"out",
"[",
":",
",",
"0",
"]",
"=",
"left",
"out",
"[",
":",
",",
"1",
"]",
"=",
"top",
"out",
"[",
":",
",",
"2",
"]",
"=",
"right",
"out",
"[",
":",
",",
"3",
"]",
"=",
"bot",
"out",
"[",
"invalid",
",",
":",
"]",
"=",
"0",
"return",
"out"
] | Calculate intersect areas, normalized. | [
"Calculate",
"intersect",
"areas",
"normalized",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L220-L233 |
23,473 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomCropAug._check_satisfy_constraints | def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height):
"""Check if constrains are satisfied"""
if (xmax - xmin) * (ymax - ymin) < 2:
return False # only 1 pixel
x1 = float(xmin) / width
y1 = float(ymin) / height
x2 = float(xmax) / width
y2 = float(ymax) / height
object_areas = self._calculate_areas(label[:, 1:])
valid_objects = np.where(object_areas * width * height > 2)[0]
if valid_objects.size < 1:
return False
intersects = self._intersect(label[valid_objects, 1:], x1, y1, x2, y2)
coverages = self._calculate_areas(intersects) / object_areas[valid_objects]
coverages = coverages[np.where(coverages > 0)[0]]
return coverages.size > 0 and np.amin(coverages) > self.min_object_covered | python | def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height):
"""Check if constrains are satisfied"""
if (xmax - xmin) * (ymax - ymin) < 2:
return False # only 1 pixel
x1 = float(xmin) / width
y1 = float(ymin) / height
x2 = float(xmax) / width
y2 = float(ymax) / height
object_areas = self._calculate_areas(label[:, 1:])
valid_objects = np.where(object_areas * width * height > 2)[0]
if valid_objects.size < 1:
return False
intersects = self._intersect(label[valid_objects, 1:], x1, y1, x2, y2)
coverages = self._calculate_areas(intersects) / object_areas[valid_objects]
coverages = coverages[np.where(coverages > 0)[0]]
return coverages.size > 0 and np.amin(coverages) > self.min_object_covered | [
"def",
"_check_satisfy_constraints",
"(",
"self",
",",
"label",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"width",
",",
"height",
")",
":",
"if",
"(",
"xmax",
"-",
"xmin",
")",
"*",
"(",
"ymax",
"-",
"ymin",
")",
"<",
"2",
":",
"return",
"False",
"# only 1 pixel",
"x1",
"=",
"float",
"(",
"xmin",
")",
"/",
"width",
"y1",
"=",
"float",
"(",
"ymin",
")",
"/",
"height",
"x2",
"=",
"float",
"(",
"xmax",
")",
"/",
"width",
"y2",
"=",
"float",
"(",
"ymax",
")",
"/",
"height",
"object_areas",
"=",
"self",
".",
"_calculate_areas",
"(",
"label",
"[",
":",
",",
"1",
":",
"]",
")",
"valid_objects",
"=",
"np",
".",
"where",
"(",
"object_areas",
"*",
"width",
"*",
"height",
">",
"2",
")",
"[",
"0",
"]",
"if",
"valid_objects",
".",
"size",
"<",
"1",
":",
"return",
"False",
"intersects",
"=",
"self",
".",
"_intersect",
"(",
"label",
"[",
"valid_objects",
",",
"1",
":",
"]",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"coverages",
"=",
"self",
".",
"_calculate_areas",
"(",
"intersects",
")",
"/",
"object_areas",
"[",
"valid_objects",
"]",
"coverages",
"=",
"coverages",
"[",
"np",
".",
"where",
"(",
"coverages",
">",
"0",
")",
"[",
"0",
"]",
"]",
"return",
"coverages",
".",
"size",
">",
"0",
"and",
"np",
".",
"amin",
"(",
"coverages",
")",
">",
"self",
".",
"min_object_covered"
] | Check if constrains are satisfied | [
"Check",
"if",
"constrains",
"are",
"satisfied"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L235-L250 |
23,474 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomCropAug._update_labels | def _update_labels(self, label, crop_box, height, width):
"""Convert labels according to crop box"""
xmin = float(crop_box[0]) / width
ymin = float(crop_box[1]) / height
w = float(crop_box[2]) / width
h = float(crop_box[3]) / height
out = label.copy()
out[:, (1, 3)] -= xmin
out[:, (2, 4)] -= ymin
out[:, (1, 3)] /= w
out[:, (2, 4)] /= h
out[:, 1:5] = np.maximum(0, out[:, 1:5])
out[:, 1:5] = np.minimum(1, out[:, 1:5])
coverage = self._calculate_areas(out[:, 1:]) * w * h / self._calculate_areas(label[:, 1:])
valid = np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2])
valid = np.logical_and(valid, coverage > self.min_eject_coverage)
valid = np.where(valid)[0]
if valid.size < 1:
return None
out = out[valid, :]
return out | python | def _update_labels(self, label, crop_box, height, width):
"""Convert labels according to crop box"""
xmin = float(crop_box[0]) / width
ymin = float(crop_box[1]) / height
w = float(crop_box[2]) / width
h = float(crop_box[3]) / height
out = label.copy()
out[:, (1, 3)] -= xmin
out[:, (2, 4)] -= ymin
out[:, (1, 3)] /= w
out[:, (2, 4)] /= h
out[:, 1:5] = np.maximum(0, out[:, 1:5])
out[:, 1:5] = np.minimum(1, out[:, 1:5])
coverage = self._calculate_areas(out[:, 1:]) * w * h / self._calculate_areas(label[:, 1:])
valid = np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2])
valid = np.logical_and(valid, coverage > self.min_eject_coverage)
valid = np.where(valid)[0]
if valid.size < 1:
return None
out = out[valid, :]
return out | [
"def",
"_update_labels",
"(",
"self",
",",
"label",
",",
"crop_box",
",",
"height",
",",
"width",
")",
":",
"xmin",
"=",
"float",
"(",
"crop_box",
"[",
"0",
"]",
")",
"/",
"width",
"ymin",
"=",
"float",
"(",
"crop_box",
"[",
"1",
"]",
")",
"/",
"height",
"w",
"=",
"float",
"(",
"crop_box",
"[",
"2",
"]",
")",
"/",
"width",
"h",
"=",
"float",
"(",
"crop_box",
"[",
"3",
"]",
")",
"/",
"height",
"out",
"=",
"label",
".",
"copy",
"(",
")",
"out",
"[",
":",
",",
"(",
"1",
",",
"3",
")",
"]",
"-=",
"xmin",
"out",
"[",
":",
",",
"(",
"2",
",",
"4",
")",
"]",
"-=",
"ymin",
"out",
"[",
":",
",",
"(",
"1",
",",
"3",
")",
"]",
"/=",
"w",
"out",
"[",
":",
",",
"(",
"2",
",",
"4",
")",
"]",
"/=",
"h",
"out",
"[",
":",
",",
"1",
":",
"5",
"]",
"=",
"np",
".",
"maximum",
"(",
"0",
",",
"out",
"[",
":",
",",
"1",
":",
"5",
"]",
")",
"out",
"[",
":",
",",
"1",
":",
"5",
"]",
"=",
"np",
".",
"minimum",
"(",
"1",
",",
"out",
"[",
":",
",",
"1",
":",
"5",
"]",
")",
"coverage",
"=",
"self",
".",
"_calculate_areas",
"(",
"out",
"[",
":",
",",
"1",
":",
"]",
")",
"*",
"w",
"*",
"h",
"/",
"self",
".",
"_calculate_areas",
"(",
"label",
"[",
":",
",",
"1",
":",
"]",
")",
"valid",
"=",
"np",
".",
"logical_and",
"(",
"out",
"[",
":",
",",
"3",
"]",
">",
"out",
"[",
":",
",",
"1",
"]",
",",
"out",
"[",
":",
",",
"4",
"]",
">",
"out",
"[",
":",
",",
"2",
"]",
")",
"valid",
"=",
"np",
".",
"logical_and",
"(",
"valid",
",",
"coverage",
">",
"self",
".",
"min_eject_coverage",
")",
"valid",
"=",
"np",
".",
"where",
"(",
"valid",
")",
"[",
"0",
"]",
"if",
"valid",
".",
"size",
"<",
"1",
":",
"return",
"None",
"out",
"=",
"out",
"[",
"valid",
",",
":",
"]",
"return",
"out"
] | Convert labels according to crop box | [
"Convert",
"labels",
"according",
"to",
"crop",
"box"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L252-L272 |
23,475 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomCropAug._random_crop_proposal | def _random_crop_proposal(self, label, height, width):
"""Propose cropping areas"""
from math import sqrt
if not self.enabled or height <= 0 or width <= 0:
return ()
min_area = self.area_range[0] * height * width
max_area = self.area_range[1] * height * width
for _ in range(self.max_attempts):
ratio = random.uniform(*self.aspect_ratio_range)
if ratio <= 0:
continue
h = int(round(sqrt(min_area / ratio)))
max_h = int(round(sqrt(max_area / ratio)))
if round(max_h * ratio) > width:
# find smallest max_h satifying round(max_h * ratio) <= width
max_h = int((width + 0.4999999) / ratio)
if max_h > height:
max_h = height
if h > max_h:
h = max_h
if h < max_h:
# generate random h in range [h, max_h]
h = random.randint(h, max_h)
w = int(round(h * ratio))
assert w <= width
# trying to fix rounding problems
area = w * h
if area < min_area:
h += 1
w = int(round(h * ratio))
area = w * h
if area > max_area:
h -= 1
w = int(round(h * ratio))
area = w * h
if not (min_area <= area <= max_area and 0 <= w <= width and 0 <= h <= height):
continue
y = random.randint(0, max(0, height - h))
x = random.randint(0, max(0, width - w))
if self._check_satisfy_constraints(label, x, y, x + w, y + h, width, height):
new_label = self._update_labels(label, (x, y, w, h), height, width)
if new_label is not None:
return (x, y, w, h, new_label)
return () | python | def _random_crop_proposal(self, label, height, width):
"""Propose cropping areas"""
from math import sqrt
if not self.enabled or height <= 0 or width <= 0:
return ()
min_area = self.area_range[0] * height * width
max_area = self.area_range[1] * height * width
for _ in range(self.max_attempts):
ratio = random.uniform(*self.aspect_ratio_range)
if ratio <= 0:
continue
h = int(round(sqrt(min_area / ratio)))
max_h = int(round(sqrt(max_area / ratio)))
if round(max_h * ratio) > width:
# find smallest max_h satifying round(max_h * ratio) <= width
max_h = int((width + 0.4999999) / ratio)
if max_h > height:
max_h = height
if h > max_h:
h = max_h
if h < max_h:
# generate random h in range [h, max_h]
h = random.randint(h, max_h)
w = int(round(h * ratio))
assert w <= width
# trying to fix rounding problems
area = w * h
if area < min_area:
h += 1
w = int(round(h * ratio))
area = w * h
if area > max_area:
h -= 1
w = int(round(h * ratio))
area = w * h
if not (min_area <= area <= max_area and 0 <= w <= width and 0 <= h <= height):
continue
y = random.randint(0, max(0, height - h))
x = random.randint(0, max(0, width - w))
if self._check_satisfy_constraints(label, x, y, x + w, y + h, width, height):
new_label = self._update_labels(label, (x, y, w, h), height, width)
if new_label is not None:
return (x, y, w, h, new_label)
return () | [
"def",
"_random_crop_proposal",
"(",
"self",
",",
"label",
",",
"height",
",",
"width",
")",
":",
"from",
"math",
"import",
"sqrt",
"if",
"not",
"self",
".",
"enabled",
"or",
"height",
"<=",
"0",
"or",
"width",
"<=",
"0",
":",
"return",
"(",
")",
"min_area",
"=",
"self",
".",
"area_range",
"[",
"0",
"]",
"*",
"height",
"*",
"width",
"max_area",
"=",
"self",
".",
"area_range",
"[",
"1",
"]",
"*",
"height",
"*",
"width",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"max_attempts",
")",
":",
"ratio",
"=",
"random",
".",
"uniform",
"(",
"*",
"self",
".",
"aspect_ratio_range",
")",
"if",
"ratio",
"<=",
"0",
":",
"continue",
"h",
"=",
"int",
"(",
"round",
"(",
"sqrt",
"(",
"min_area",
"/",
"ratio",
")",
")",
")",
"max_h",
"=",
"int",
"(",
"round",
"(",
"sqrt",
"(",
"max_area",
"/",
"ratio",
")",
")",
")",
"if",
"round",
"(",
"max_h",
"*",
"ratio",
")",
">",
"width",
":",
"# find smallest max_h satifying round(max_h * ratio) <= width",
"max_h",
"=",
"int",
"(",
"(",
"width",
"+",
"0.4999999",
")",
"/",
"ratio",
")",
"if",
"max_h",
">",
"height",
":",
"max_h",
"=",
"height",
"if",
"h",
">",
"max_h",
":",
"h",
"=",
"max_h",
"if",
"h",
"<",
"max_h",
":",
"# generate random h in range [h, max_h]",
"h",
"=",
"random",
".",
"randint",
"(",
"h",
",",
"max_h",
")",
"w",
"=",
"int",
"(",
"round",
"(",
"h",
"*",
"ratio",
")",
")",
"assert",
"w",
"<=",
"width",
"# trying to fix rounding problems",
"area",
"=",
"w",
"*",
"h",
"if",
"area",
"<",
"min_area",
":",
"h",
"+=",
"1",
"w",
"=",
"int",
"(",
"round",
"(",
"h",
"*",
"ratio",
")",
")",
"area",
"=",
"w",
"*",
"h",
"if",
"area",
">",
"max_area",
":",
"h",
"-=",
"1",
"w",
"=",
"int",
"(",
"round",
"(",
"h",
"*",
"ratio",
")",
")",
"area",
"=",
"w",
"*",
"h",
"if",
"not",
"(",
"min_area",
"<=",
"area",
"<=",
"max_area",
"and",
"0",
"<=",
"w",
"<=",
"width",
"and",
"0",
"<=",
"h",
"<=",
"height",
")",
":",
"continue",
"y",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"max",
"(",
"0",
",",
"height",
"-",
"h",
")",
")",
"x",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"max",
"(",
"0",
",",
"width",
"-",
"w",
")",
")",
"if",
"self",
".",
"_check_satisfy_constraints",
"(",
"label",
",",
"x",
",",
"y",
",",
"x",
"+",
"w",
",",
"y",
"+",
"h",
",",
"width",
",",
"height",
")",
":",
"new_label",
"=",
"self",
".",
"_update_labels",
"(",
"label",
",",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
",",
"height",
",",
"width",
")",
"if",
"new_label",
"is",
"not",
"None",
":",
"return",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"new_label",
")",
"return",
"(",
")"
] | Propose cropping areas | [
"Propose",
"cropping",
"areas"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L274-L320 |
23,476 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomPadAug._update_labels | def _update_labels(self, label, pad_box, height, width):
"""Update label according to padding region"""
out = label.copy()
out[:, (1, 3)] = (out[:, (1, 3)] * width + pad_box[0]) / pad_box[2]
out[:, (2, 4)] = (out[:, (2, 4)] * height + pad_box[1]) / pad_box[3]
return out | python | def _update_labels(self, label, pad_box, height, width):
"""Update label according to padding region"""
out = label.copy()
out[:, (1, 3)] = (out[:, (1, 3)] * width + pad_box[0]) / pad_box[2]
out[:, (2, 4)] = (out[:, (2, 4)] * height + pad_box[1]) / pad_box[3]
return out | [
"def",
"_update_labels",
"(",
"self",
",",
"label",
",",
"pad_box",
",",
"height",
",",
"width",
")",
":",
"out",
"=",
"label",
".",
"copy",
"(",
")",
"out",
"[",
":",
",",
"(",
"1",
",",
"3",
")",
"]",
"=",
"(",
"out",
"[",
":",
",",
"(",
"1",
",",
"3",
")",
"]",
"*",
"width",
"+",
"pad_box",
"[",
"0",
"]",
")",
"/",
"pad_box",
"[",
"2",
"]",
"out",
"[",
":",
",",
"(",
"2",
",",
"4",
")",
"]",
"=",
"(",
"out",
"[",
":",
",",
"(",
"2",
",",
"4",
")",
"]",
"*",
"height",
"+",
"pad_box",
"[",
"1",
"]",
")",
"/",
"pad_box",
"[",
"3",
"]",
"return",
"out"
] | Update label according to padding region | [
"Update",
"label",
"according",
"to",
"padding",
"region"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L378-L383 |
23,477 | apache/incubator-mxnet | python/mxnet/image/detection.py | DetRandomPadAug._random_pad_proposal | def _random_pad_proposal(self, label, height, width):
"""Generate random padding region"""
from math import sqrt
if not self.enabled or height <= 0 or width <= 0:
return ()
min_area = self.area_range[0] * height * width
max_area = self.area_range[1] * height * width
for _ in range(self.max_attempts):
ratio = random.uniform(*self.aspect_ratio_range)
if ratio <= 0:
continue
h = int(round(sqrt(min_area / ratio)))
max_h = int(round(sqrt(max_area / ratio)))
if round(h * ratio) < width:
h = int((width + 0.499999) / ratio)
if h < height:
h = height
if h > max_h:
h = max_h
if h < max_h:
h = random.randint(h, max_h)
w = int(round(h * ratio))
if (h - height) < 2 or (w - width) < 2:
continue # marginal padding is not helpful
y = random.randint(0, max(0, h - height))
x = random.randint(0, max(0, w - width))
new_label = self._update_labels(label, (x, y, w, h), height, width)
return (x, y, w, h, new_label)
return () | python | def _random_pad_proposal(self, label, height, width):
"""Generate random padding region"""
from math import sqrt
if not self.enabled or height <= 0 or width <= 0:
return ()
min_area = self.area_range[0] * height * width
max_area = self.area_range[1] * height * width
for _ in range(self.max_attempts):
ratio = random.uniform(*self.aspect_ratio_range)
if ratio <= 0:
continue
h = int(round(sqrt(min_area / ratio)))
max_h = int(round(sqrt(max_area / ratio)))
if round(h * ratio) < width:
h = int((width + 0.499999) / ratio)
if h < height:
h = height
if h > max_h:
h = max_h
if h < max_h:
h = random.randint(h, max_h)
w = int(round(h * ratio))
if (h - height) < 2 or (w - width) < 2:
continue # marginal padding is not helpful
y = random.randint(0, max(0, h - height))
x = random.randint(0, max(0, w - width))
new_label = self._update_labels(label, (x, y, w, h), height, width)
return (x, y, w, h, new_label)
return () | [
"def",
"_random_pad_proposal",
"(",
"self",
",",
"label",
",",
"height",
",",
"width",
")",
":",
"from",
"math",
"import",
"sqrt",
"if",
"not",
"self",
".",
"enabled",
"or",
"height",
"<=",
"0",
"or",
"width",
"<=",
"0",
":",
"return",
"(",
")",
"min_area",
"=",
"self",
".",
"area_range",
"[",
"0",
"]",
"*",
"height",
"*",
"width",
"max_area",
"=",
"self",
".",
"area_range",
"[",
"1",
"]",
"*",
"height",
"*",
"width",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"max_attempts",
")",
":",
"ratio",
"=",
"random",
".",
"uniform",
"(",
"*",
"self",
".",
"aspect_ratio_range",
")",
"if",
"ratio",
"<=",
"0",
":",
"continue",
"h",
"=",
"int",
"(",
"round",
"(",
"sqrt",
"(",
"min_area",
"/",
"ratio",
")",
")",
")",
"max_h",
"=",
"int",
"(",
"round",
"(",
"sqrt",
"(",
"max_area",
"/",
"ratio",
")",
")",
")",
"if",
"round",
"(",
"h",
"*",
"ratio",
")",
"<",
"width",
":",
"h",
"=",
"int",
"(",
"(",
"width",
"+",
"0.499999",
")",
"/",
"ratio",
")",
"if",
"h",
"<",
"height",
":",
"h",
"=",
"height",
"if",
"h",
">",
"max_h",
":",
"h",
"=",
"max_h",
"if",
"h",
"<",
"max_h",
":",
"h",
"=",
"random",
".",
"randint",
"(",
"h",
",",
"max_h",
")",
"w",
"=",
"int",
"(",
"round",
"(",
"h",
"*",
"ratio",
")",
")",
"if",
"(",
"h",
"-",
"height",
")",
"<",
"2",
"or",
"(",
"w",
"-",
"width",
")",
"<",
"2",
":",
"continue",
"# marginal padding is not helpful",
"y",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"max",
"(",
"0",
",",
"h",
"-",
"height",
")",
")",
"x",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"max",
"(",
"0",
",",
"w",
"-",
"width",
")",
")",
"new_label",
"=",
"self",
".",
"_update_labels",
"(",
"label",
",",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
",",
"height",
",",
"width",
")",
"return",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"new_label",
")",
"return",
"(",
")"
] | Generate random padding region | [
"Generate",
"random",
"padding",
"region"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L385-L414 |
23,478 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter._check_valid_label | def _check_valid_label(self, label):
"""Validate label and its shape."""
if len(label.shape) != 2 or label.shape[1] < 5:
msg = "Label with shape (1+, 5+) required, %s received." % str(label)
raise RuntimeError(msg)
valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1],
label[:, 4] > label[:, 2]))[0]
if valid_label.size < 1:
raise RuntimeError('Invalid label occurs.') | python | def _check_valid_label(self, label):
"""Validate label and its shape."""
if len(label.shape) != 2 or label.shape[1] < 5:
msg = "Label with shape (1+, 5+) required, %s received." % str(label)
raise RuntimeError(msg)
valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1],
label[:, 4] > label[:, 2]))[0]
if valid_label.size < 1:
raise RuntimeError('Invalid label occurs.') | [
"def",
"_check_valid_label",
"(",
"self",
",",
"label",
")",
":",
"if",
"len",
"(",
"label",
".",
"shape",
")",
"!=",
"2",
"or",
"label",
".",
"shape",
"[",
"1",
"]",
"<",
"5",
":",
"msg",
"=",
"\"Label with shape (1+, 5+) required, %s received.\"",
"%",
"str",
"(",
"label",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"valid_label",
"=",
"np",
".",
"where",
"(",
"np",
".",
"logical_and",
"(",
"label",
"[",
":",
",",
"0",
"]",
">=",
"0",
",",
"label",
"[",
":",
",",
"3",
"]",
">",
"label",
"[",
":",
",",
"1",
"]",
",",
"label",
"[",
":",
",",
"4",
"]",
">",
"label",
"[",
":",
",",
"2",
"]",
")",
")",
"[",
"0",
"]",
"if",
"valid_label",
".",
"size",
"<",
"1",
":",
"raise",
"RuntimeError",
"(",
"'Invalid label occurs.'",
")"
] | Validate label and its shape. | [
"Validate",
"label",
"and",
"its",
"shape",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L692-L700 |
23,479 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter._estimate_label_shape | def _estimate_label_shape(self):
"""Helper function to estimate label shape"""
max_count = 0
self.reset()
try:
while True:
label, _ = self.next_sample()
label = self._parse_label(label)
max_count = max(max_count, label.shape[0])
except StopIteration:
pass
self.reset()
return (max_count, label.shape[1]) | python | def _estimate_label_shape(self):
"""Helper function to estimate label shape"""
max_count = 0
self.reset()
try:
while True:
label, _ = self.next_sample()
label = self._parse_label(label)
max_count = max(max_count, label.shape[0])
except StopIteration:
pass
self.reset()
return (max_count, label.shape[1]) | [
"def",
"_estimate_label_shape",
"(",
"self",
")",
":",
"max_count",
"=",
"0",
"self",
".",
"reset",
"(",
")",
"try",
":",
"while",
"True",
":",
"label",
",",
"_",
"=",
"self",
".",
"next_sample",
"(",
")",
"label",
"=",
"self",
".",
"_parse_label",
"(",
"label",
")",
"max_count",
"=",
"max",
"(",
"max_count",
",",
"label",
".",
"shape",
"[",
"0",
"]",
")",
"except",
"StopIteration",
":",
"pass",
"self",
".",
"reset",
"(",
")",
"return",
"(",
"max_count",
",",
"label",
".",
"shape",
"[",
"1",
"]",
")"
] | Helper function to estimate label shape | [
"Helper",
"function",
"to",
"estimate",
"label",
"shape"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L702-L714 |
23,480 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter._parse_label | def _parse_label(self, label):
"""Helper function to parse object detection label.
Format for raw label:
n \t k \t ... \t [id \t xmin\t ymin \t xmax \t ymax \t ...] \t [repeat]
where n is the width of header, 2 or larger
k is the width of each object annotation, can be arbitrary, at least 5
"""
if isinstance(label, nd.NDArray):
label = label.asnumpy()
raw = label.ravel()
if raw.size < 7:
raise RuntimeError("Label shape is invalid: " + str(raw.shape))
header_width = int(raw[0])
obj_width = int(raw[1])
if (raw.size - header_width) % obj_width != 0:
msg = "Label shape %s inconsistent with annotation width %d." \
%(str(raw.shape), obj_width)
raise RuntimeError(msg)
out = np.reshape(raw[header_width:], (-1, obj_width))
# remove bad ground-truths
valid = np.where(np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2]))[0]
if valid.size < 1:
raise RuntimeError('Encounter sample with no valid label.')
return out[valid, :] | python | def _parse_label(self, label):
"""Helper function to parse object detection label.
Format for raw label:
n \t k \t ... \t [id \t xmin\t ymin \t xmax \t ymax \t ...] \t [repeat]
where n is the width of header, 2 or larger
k is the width of each object annotation, can be arbitrary, at least 5
"""
if isinstance(label, nd.NDArray):
label = label.asnumpy()
raw = label.ravel()
if raw.size < 7:
raise RuntimeError("Label shape is invalid: " + str(raw.shape))
header_width = int(raw[0])
obj_width = int(raw[1])
if (raw.size - header_width) % obj_width != 0:
msg = "Label shape %s inconsistent with annotation width %d." \
%(str(raw.shape), obj_width)
raise RuntimeError(msg)
out = np.reshape(raw[header_width:], (-1, obj_width))
# remove bad ground-truths
valid = np.where(np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2]))[0]
if valid.size < 1:
raise RuntimeError('Encounter sample with no valid label.')
return out[valid, :] | [
"def",
"_parse_label",
"(",
"self",
",",
"label",
")",
":",
"if",
"isinstance",
"(",
"label",
",",
"nd",
".",
"NDArray",
")",
":",
"label",
"=",
"label",
".",
"asnumpy",
"(",
")",
"raw",
"=",
"label",
".",
"ravel",
"(",
")",
"if",
"raw",
".",
"size",
"<",
"7",
":",
"raise",
"RuntimeError",
"(",
"\"Label shape is invalid: \"",
"+",
"str",
"(",
"raw",
".",
"shape",
")",
")",
"header_width",
"=",
"int",
"(",
"raw",
"[",
"0",
"]",
")",
"obj_width",
"=",
"int",
"(",
"raw",
"[",
"1",
"]",
")",
"if",
"(",
"raw",
".",
"size",
"-",
"header_width",
")",
"%",
"obj_width",
"!=",
"0",
":",
"msg",
"=",
"\"Label shape %s inconsistent with annotation width %d.\"",
"%",
"(",
"str",
"(",
"raw",
".",
"shape",
")",
",",
"obj_width",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"out",
"=",
"np",
".",
"reshape",
"(",
"raw",
"[",
"header_width",
":",
"]",
",",
"(",
"-",
"1",
",",
"obj_width",
")",
")",
"# remove bad ground-truths",
"valid",
"=",
"np",
".",
"where",
"(",
"np",
".",
"logical_and",
"(",
"out",
"[",
":",
",",
"3",
"]",
">",
"out",
"[",
":",
",",
"1",
"]",
",",
"out",
"[",
":",
",",
"4",
"]",
">",
"out",
"[",
":",
",",
"2",
"]",
")",
")",
"[",
"0",
"]",
"if",
"valid",
".",
"size",
"<",
"1",
":",
"raise",
"RuntimeError",
"(",
"'Encounter sample with no valid label.'",
")",
"return",
"out",
"[",
"valid",
",",
":",
"]"
] | Helper function to parse object detection label.
Format for raw label:
n \t k \t ... \t [id \t xmin\t ymin \t xmax \t ymax \t ...] \t [repeat]
where n is the width of header, 2 or larger
k is the width of each object annotation, can be arbitrary, at least 5 | [
"Helper",
"function",
"to",
"parse",
"object",
"detection",
"label",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L716-L740 |
23,481 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter.reshape | def reshape(self, data_shape=None, label_shape=None):
"""Reshape iterator for data_shape or label_shape.
Parameters
----------
data_shape : tuple or None
Reshape the data_shape to the new shape if not None
label_shape : tuple or None
Reshape label shape to new shape if not None
"""
if data_shape is not None:
self.check_data_shape(data_shape)
self.provide_data = [(self.provide_data[0][0], (self.batch_size,) + data_shape)]
self.data_shape = data_shape
if label_shape is not None:
self.check_label_shape(label_shape)
self.provide_label = [(self.provide_label[0][0], (self.batch_size,) + label_shape)]
self.label_shape = label_shape | python | def reshape(self, data_shape=None, label_shape=None):
"""Reshape iterator for data_shape or label_shape.
Parameters
----------
data_shape : tuple or None
Reshape the data_shape to the new shape if not None
label_shape : tuple or None
Reshape label shape to new shape if not None
"""
if data_shape is not None:
self.check_data_shape(data_shape)
self.provide_data = [(self.provide_data[0][0], (self.batch_size,) + data_shape)]
self.data_shape = data_shape
if label_shape is not None:
self.check_label_shape(label_shape)
self.provide_label = [(self.provide_label[0][0], (self.batch_size,) + label_shape)]
self.label_shape = label_shape | [
"def",
"reshape",
"(",
"self",
",",
"data_shape",
"=",
"None",
",",
"label_shape",
"=",
"None",
")",
":",
"if",
"data_shape",
"is",
"not",
"None",
":",
"self",
".",
"check_data_shape",
"(",
"data_shape",
")",
"self",
".",
"provide_data",
"=",
"[",
"(",
"self",
".",
"provide_data",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"(",
"self",
".",
"batch_size",
",",
")",
"+",
"data_shape",
")",
"]",
"self",
".",
"data_shape",
"=",
"data_shape",
"if",
"label_shape",
"is",
"not",
"None",
":",
"self",
".",
"check_label_shape",
"(",
"label_shape",
")",
"self",
".",
"provide_label",
"=",
"[",
"(",
"self",
".",
"provide_label",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"(",
"self",
".",
"batch_size",
",",
")",
"+",
"label_shape",
")",
"]",
"self",
".",
"label_shape",
"=",
"label_shape"
] | Reshape iterator for data_shape or label_shape.
Parameters
----------
data_shape : tuple or None
Reshape the data_shape to the new shape if not None
label_shape : tuple or None
Reshape label shape to new shape if not None | [
"Reshape",
"iterator",
"for",
"data_shape",
"or",
"label_shape",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L742-L759 |
23,482 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter._batchify | def _batchify(self, batch_data, batch_label, start=0):
"""Override the helper function for batchifying data"""
i = start
batch_size = self.batch_size
try:
while i < batch_size:
label, s = self.next_sample()
data = self.imdecode(s)
try:
self.check_valid_image([data])
label = self._parse_label(label)
data, label = self.augmentation_transform(data, label)
self._check_valid_label(label)
except RuntimeError as e:
logging.debug('Invalid image, skipping: %s', str(e))
continue
for datum in [data]:
assert i < batch_size, 'Batch size must be multiples of augmenter output length'
batch_data[i] = self.postprocess_data(datum)
num_object = label.shape[0]
batch_label[i][0:num_object] = nd.array(label)
if num_object < batch_label[i].shape[0]:
batch_label[i][num_object:] = -1
i += 1
except StopIteration:
if not i:
raise StopIteration
return i | python | def _batchify(self, batch_data, batch_label, start=0):
"""Override the helper function for batchifying data"""
i = start
batch_size = self.batch_size
try:
while i < batch_size:
label, s = self.next_sample()
data = self.imdecode(s)
try:
self.check_valid_image([data])
label = self._parse_label(label)
data, label = self.augmentation_transform(data, label)
self._check_valid_label(label)
except RuntimeError as e:
logging.debug('Invalid image, skipping: %s', str(e))
continue
for datum in [data]:
assert i < batch_size, 'Batch size must be multiples of augmenter output length'
batch_data[i] = self.postprocess_data(datum)
num_object = label.shape[0]
batch_label[i][0:num_object] = nd.array(label)
if num_object < batch_label[i].shape[0]:
batch_label[i][num_object:] = -1
i += 1
except StopIteration:
if not i:
raise StopIteration
return i | [
"def",
"_batchify",
"(",
"self",
",",
"batch_data",
",",
"batch_label",
",",
"start",
"=",
"0",
")",
":",
"i",
"=",
"start",
"batch_size",
"=",
"self",
".",
"batch_size",
"try",
":",
"while",
"i",
"<",
"batch_size",
":",
"label",
",",
"s",
"=",
"self",
".",
"next_sample",
"(",
")",
"data",
"=",
"self",
".",
"imdecode",
"(",
"s",
")",
"try",
":",
"self",
".",
"check_valid_image",
"(",
"[",
"data",
"]",
")",
"label",
"=",
"self",
".",
"_parse_label",
"(",
"label",
")",
"data",
",",
"label",
"=",
"self",
".",
"augmentation_transform",
"(",
"data",
",",
"label",
")",
"self",
".",
"_check_valid_label",
"(",
"label",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"logging",
".",
"debug",
"(",
"'Invalid image, skipping: %s'",
",",
"str",
"(",
"e",
")",
")",
"continue",
"for",
"datum",
"in",
"[",
"data",
"]",
":",
"assert",
"i",
"<",
"batch_size",
",",
"'Batch size must be multiples of augmenter output length'",
"batch_data",
"[",
"i",
"]",
"=",
"self",
".",
"postprocess_data",
"(",
"datum",
")",
"num_object",
"=",
"label",
".",
"shape",
"[",
"0",
"]",
"batch_label",
"[",
"i",
"]",
"[",
"0",
":",
"num_object",
"]",
"=",
"nd",
".",
"array",
"(",
"label",
")",
"if",
"num_object",
"<",
"batch_label",
"[",
"i",
"]",
".",
"shape",
"[",
"0",
"]",
":",
"batch_label",
"[",
"i",
"]",
"[",
"num_object",
":",
"]",
"=",
"-",
"1",
"i",
"+=",
"1",
"except",
"StopIteration",
":",
"if",
"not",
"i",
":",
"raise",
"StopIteration",
"return",
"i"
] | Override the helper function for batchifying data | [
"Override",
"the",
"helper",
"function",
"for",
"batchifying",
"data"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L761-L789 |
23,483 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter.next | def next(self):
"""Override the function for returning next batch."""
batch_size = self.batch_size
c, h, w = self.data_shape
# if last batch data is rolled over
if self._cache_data is not None:
# check both the data and label have values
assert self._cache_label is not None, "_cache_label didn't have values"
assert self._cache_idx is not None, "_cache_idx didn't have values"
batch_data = self._cache_data
batch_label = self._cache_label
i = self._cache_idx
else:
batch_data = nd.zeros((batch_size, c, h, w))
batch_label = nd.empty(self.provide_label[0][1])
batch_label[:] = -1
i = self._batchify(batch_data, batch_label)
# calculate the padding
pad = batch_size - i
# handle padding for the last batch
if pad != 0:
if self.last_batch_handle == 'discard':
raise StopIteration
# if the option is 'roll_over', throw StopIteration and cache the data
elif self.last_batch_handle == 'roll_over' and \
self._cache_data is None:
self._cache_data = batch_data
self._cache_label = batch_label
self._cache_idx = i
raise StopIteration
else:
_ = self._batchify(batch_data, batch_label, i)
if self.last_batch_handle == 'pad':
self._allow_read = False
else:
self._cache_data = None
self._cache_label = None
self._cache_idx = None
return io.DataBatch([batch_data], [batch_label], pad=pad) | python | def next(self):
"""Override the function for returning next batch."""
batch_size = self.batch_size
c, h, w = self.data_shape
# if last batch data is rolled over
if self._cache_data is not None:
# check both the data and label have values
assert self._cache_label is not None, "_cache_label didn't have values"
assert self._cache_idx is not None, "_cache_idx didn't have values"
batch_data = self._cache_data
batch_label = self._cache_label
i = self._cache_idx
else:
batch_data = nd.zeros((batch_size, c, h, w))
batch_label = nd.empty(self.provide_label[0][1])
batch_label[:] = -1
i = self._batchify(batch_data, batch_label)
# calculate the padding
pad = batch_size - i
# handle padding for the last batch
if pad != 0:
if self.last_batch_handle == 'discard':
raise StopIteration
# if the option is 'roll_over', throw StopIteration and cache the data
elif self.last_batch_handle == 'roll_over' and \
self._cache_data is None:
self._cache_data = batch_data
self._cache_label = batch_label
self._cache_idx = i
raise StopIteration
else:
_ = self._batchify(batch_data, batch_label, i)
if self.last_batch_handle == 'pad':
self._allow_read = False
else:
self._cache_data = None
self._cache_label = None
self._cache_idx = None
return io.DataBatch([batch_data], [batch_label], pad=pad) | [
"def",
"next",
"(",
"self",
")",
":",
"batch_size",
"=",
"self",
".",
"batch_size",
"c",
",",
"h",
",",
"w",
"=",
"self",
".",
"data_shape",
"# if last batch data is rolled over",
"if",
"self",
".",
"_cache_data",
"is",
"not",
"None",
":",
"# check both the data and label have values",
"assert",
"self",
".",
"_cache_label",
"is",
"not",
"None",
",",
"\"_cache_label didn't have values\"",
"assert",
"self",
".",
"_cache_idx",
"is",
"not",
"None",
",",
"\"_cache_idx didn't have values\"",
"batch_data",
"=",
"self",
".",
"_cache_data",
"batch_label",
"=",
"self",
".",
"_cache_label",
"i",
"=",
"self",
".",
"_cache_idx",
"else",
":",
"batch_data",
"=",
"nd",
".",
"zeros",
"(",
"(",
"batch_size",
",",
"c",
",",
"h",
",",
"w",
")",
")",
"batch_label",
"=",
"nd",
".",
"empty",
"(",
"self",
".",
"provide_label",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"batch_label",
"[",
":",
"]",
"=",
"-",
"1",
"i",
"=",
"self",
".",
"_batchify",
"(",
"batch_data",
",",
"batch_label",
")",
"# calculate the padding",
"pad",
"=",
"batch_size",
"-",
"i",
"# handle padding for the last batch",
"if",
"pad",
"!=",
"0",
":",
"if",
"self",
".",
"last_batch_handle",
"==",
"'discard'",
":",
"raise",
"StopIteration",
"# if the option is 'roll_over', throw StopIteration and cache the data",
"elif",
"self",
".",
"last_batch_handle",
"==",
"'roll_over'",
"and",
"self",
".",
"_cache_data",
"is",
"None",
":",
"self",
".",
"_cache_data",
"=",
"batch_data",
"self",
".",
"_cache_label",
"=",
"batch_label",
"self",
".",
"_cache_idx",
"=",
"i",
"raise",
"StopIteration",
"else",
":",
"_",
"=",
"self",
".",
"_batchify",
"(",
"batch_data",
",",
"batch_label",
",",
"i",
")",
"if",
"self",
".",
"last_batch_handle",
"==",
"'pad'",
":",
"self",
".",
"_allow_read",
"=",
"False",
"else",
":",
"self",
".",
"_cache_data",
"=",
"None",
"self",
".",
"_cache_label",
"=",
"None",
"self",
".",
"_cache_idx",
"=",
"None",
"return",
"io",
".",
"DataBatch",
"(",
"[",
"batch_data",
"]",
",",
"[",
"batch_label",
"]",
",",
"pad",
"=",
"pad",
")"
] | Override the function for returning next batch. | [
"Override",
"the",
"function",
"for",
"returning",
"next",
"batch",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L791-L830 |
23,484 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter.augmentation_transform | def augmentation_transform(self, data, label): # pylint: disable=arguments-differ
"""Override Transforms input data with specified augmentations."""
for aug in self.auglist:
data, label = aug(data, label)
return (data, label) | python | def augmentation_transform(self, data, label): # pylint: disable=arguments-differ
"""Override Transforms input data with specified augmentations."""
for aug in self.auglist:
data, label = aug(data, label)
return (data, label) | [
"def",
"augmentation_transform",
"(",
"self",
",",
"data",
",",
"label",
")",
":",
"# pylint: disable=arguments-differ",
"for",
"aug",
"in",
"self",
".",
"auglist",
":",
"data",
",",
"label",
"=",
"aug",
"(",
"data",
",",
"label",
")",
"return",
"(",
"data",
",",
"label",
")"
] | Override Transforms input data with specified augmentations. | [
"Override",
"Transforms",
"input",
"data",
"with",
"specified",
"augmentations",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L832-L836 |
23,485 | apache/incubator-mxnet | python/mxnet/image/detection.py | ImageDetIter.check_label_shape | def check_label_shape(self, label_shape):
"""Checks if the new label shape is valid"""
if not len(label_shape) == 2:
raise ValueError('label_shape should have length 2')
if label_shape[0] < self.label_shape[0]:
msg = 'Attempts to reduce label count from %d to %d, not allowed.' \
% (self.label_shape[0], label_shape[0])
raise ValueError(msg)
if label_shape[1] != self.provide_label[0][1][2]:
msg = 'label_shape object width inconsistent: %d vs %d.' \
% (self.provide_label[0][1][2], label_shape[1])
raise ValueError(msg) | python | def check_label_shape(self, label_shape):
"""Checks if the new label shape is valid"""
if not len(label_shape) == 2:
raise ValueError('label_shape should have length 2')
if label_shape[0] < self.label_shape[0]:
msg = 'Attempts to reduce label count from %d to %d, not allowed.' \
% (self.label_shape[0], label_shape[0])
raise ValueError(msg)
if label_shape[1] != self.provide_label[0][1][2]:
msg = 'label_shape object width inconsistent: %d vs %d.' \
% (self.provide_label[0][1][2], label_shape[1])
raise ValueError(msg) | [
"def",
"check_label_shape",
"(",
"self",
",",
"label_shape",
")",
":",
"if",
"not",
"len",
"(",
"label_shape",
")",
"==",
"2",
":",
"raise",
"ValueError",
"(",
"'label_shape should have length 2'",
")",
"if",
"label_shape",
"[",
"0",
"]",
"<",
"self",
".",
"label_shape",
"[",
"0",
"]",
":",
"msg",
"=",
"'Attempts to reduce label count from %d to %d, not allowed.'",
"%",
"(",
"self",
".",
"label_shape",
"[",
"0",
"]",
",",
"label_shape",
"[",
"0",
"]",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"if",
"label_shape",
"[",
"1",
"]",
"!=",
"self",
".",
"provide_label",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"2",
"]",
":",
"msg",
"=",
"'label_shape object width inconsistent: %d vs %d.'",
"%",
"(",
"self",
".",
"provide_label",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"2",
"]",
",",
"label_shape",
"[",
"1",
"]",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | Checks if the new label shape is valid | [
"Checks",
"if",
"the",
"new",
"label",
"shape",
"is",
"valid"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L838-L849 |
23,486 | apache/incubator-mxnet | example/rcnn/symdata/anchor.py | AnchorGenerator._ratio_enum | def _ratio_enum(anchor, ratios):
"""
Enumerate a set of anchors for each aspect ratio wrt an anchor.
"""
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hs = np.round(ws * ratios)
anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | python | def _ratio_enum(anchor, ratios):
"""
Enumerate a set of anchors for each aspect ratio wrt an anchor.
"""
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hs = np.round(ws * ratios)
anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | [
"def",
"_ratio_enum",
"(",
"anchor",
",",
"ratios",
")",
":",
"w",
",",
"h",
",",
"x_ctr",
",",
"y_ctr",
"=",
"AnchorGenerator",
".",
"_whctrs",
"(",
"anchor",
")",
"size",
"=",
"w",
"*",
"h",
"size_ratios",
"=",
"size",
"/",
"ratios",
"ws",
"=",
"np",
".",
"round",
"(",
"np",
".",
"sqrt",
"(",
"size_ratios",
")",
")",
"hs",
"=",
"np",
".",
"round",
"(",
"ws",
"*",
"ratios",
")",
"anchors",
"=",
"AnchorGenerator",
".",
"_mkanchors",
"(",
"ws",
",",
"hs",
",",
"x_ctr",
",",
"y_ctr",
")",
"return",
"anchors"
] | Enumerate a set of anchors for each aspect ratio wrt an anchor. | [
"Enumerate",
"a",
"set",
"of",
"anchors",
"for",
"each",
"aspect",
"ratio",
"wrt",
"an",
"anchor",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/anchor.py#L81-L91 |
23,487 | apache/incubator-mxnet | example/rcnn/symdata/anchor.py | AnchorGenerator._scale_enum | def _scale_enum(anchor, scales):
"""
Enumerate a set of anchors for each scale wrt an anchor.
"""
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor)
ws = w * scales
hs = h * scales
anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | python | def _scale_enum(anchor, scales):
"""
Enumerate a set of anchors for each scale wrt an anchor.
"""
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor)
ws = w * scales
hs = h * scales
anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | [
"def",
"_scale_enum",
"(",
"anchor",
",",
"scales",
")",
":",
"w",
",",
"h",
",",
"x_ctr",
",",
"y_ctr",
"=",
"AnchorGenerator",
".",
"_whctrs",
"(",
"anchor",
")",
"ws",
"=",
"w",
"*",
"scales",
"hs",
"=",
"h",
"*",
"scales",
"anchors",
"=",
"AnchorGenerator",
".",
"_mkanchors",
"(",
"ws",
",",
"hs",
",",
"x_ctr",
",",
"y_ctr",
")",
"return",
"anchors"
] | Enumerate a set of anchors for each scale wrt an anchor. | [
"Enumerate",
"a",
"set",
"of",
"anchors",
"for",
"each",
"scale",
"wrt",
"an",
"anchor",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/anchor.py#L94-L102 |
23,488 | apache/incubator-mxnet | example/speech_recognition/arch_deepspeech.py | prepare_data | def prepare_data(args):
"""
set atual shape of data
"""
rnn_type = args.config.get("arch", "rnn_type")
num_rnn_layer = args.config.getint("arch", "num_rnn_layer")
num_hidden_rnn_list = json.loads(args.config.get("arch", "num_hidden_rnn_list"))
batch_size = args.config.getint("common", "batch_size")
if rnn_type == 'lstm':
init_c = [('l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
elif rnn_type == 'bilstm':
forward_init_c = [('forward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
backward_init_c = [('backward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_c = forward_init_c + backward_init_c
forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_h = forward_init_h + backward_init_h
elif rnn_type == 'gru':
init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
elif rnn_type == 'bigru':
forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_h = forward_init_h + backward_init_h
else:
raise Exception('network type should be one of the lstm,bilstm,gru,bigru')
if rnn_type == 'lstm' or rnn_type == 'bilstm':
init_states = init_c + init_h
elif rnn_type == 'gru' or rnn_type == 'bigru':
init_states = init_h
return init_states | python | def prepare_data(args):
"""
set atual shape of data
"""
rnn_type = args.config.get("arch", "rnn_type")
num_rnn_layer = args.config.getint("arch", "num_rnn_layer")
num_hidden_rnn_list = json.loads(args.config.get("arch", "num_hidden_rnn_list"))
batch_size = args.config.getint("common", "batch_size")
if rnn_type == 'lstm':
init_c = [('l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
elif rnn_type == 'bilstm':
forward_init_c = [('forward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
backward_init_c = [('backward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_c = forward_init_c + backward_init_c
forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_h = forward_init_h + backward_init_h
elif rnn_type == 'gru':
init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
elif rnn_type == 'bigru':
forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
for l in range(num_rnn_layer)]
init_h = forward_init_h + backward_init_h
else:
raise Exception('network type should be one of the lstm,bilstm,gru,bigru')
if rnn_type == 'lstm' or rnn_type == 'bilstm':
init_states = init_c + init_h
elif rnn_type == 'gru' or rnn_type == 'bigru':
init_states = init_h
return init_states | [
"def",
"prepare_data",
"(",
"args",
")",
":",
"rnn_type",
"=",
"args",
".",
"config",
".",
"get",
"(",
"\"arch\"",
",",
"\"rnn_type\"",
")",
"num_rnn_layer",
"=",
"args",
".",
"config",
".",
"getint",
"(",
"\"arch\"",
",",
"\"num_rnn_layer\"",
")",
"num_hidden_rnn_list",
"=",
"json",
".",
"loads",
"(",
"args",
".",
"config",
".",
"get",
"(",
"\"arch\"",
",",
"\"num_hidden_rnn_list\"",
")",
")",
"batch_size",
"=",
"args",
".",
"config",
".",
"getint",
"(",
"\"common\"",
",",
"\"batch_size\"",
")",
"if",
"rnn_type",
"==",
"'lstm'",
":",
"init_c",
"=",
"[",
"(",
"'l%d_init_c'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"init_h",
"=",
"[",
"(",
"'l%d_init_h'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"elif",
"rnn_type",
"==",
"'bilstm'",
":",
"forward_init_c",
"=",
"[",
"(",
"'forward_l%d_init_c'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"backward_init_c",
"=",
"[",
"(",
"'backward_l%d_init_c'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"init_c",
"=",
"forward_init_c",
"+",
"backward_init_c",
"forward_init_h",
"=",
"[",
"(",
"'forward_l%d_init_h'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"backward_init_h",
"=",
"[",
"(",
"'backward_l%d_init_h'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"init_h",
"=",
"forward_init_h",
"+",
"backward_init_h",
"elif",
"rnn_type",
"==",
"'gru'",
":",
"init_h",
"=",
"[",
"(",
"'l%d_init_h'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"elif",
"rnn_type",
"==",
"'bigru'",
":",
"forward_init_h",
"=",
"[",
"(",
"'forward_l%d_init_h'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"backward_init_h",
"=",
"[",
"(",
"'backward_l%d_init_h'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden_rnn_list",
"[",
"l",
"]",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_rnn_layer",
")",
"]",
"init_h",
"=",
"forward_init_h",
"+",
"backward_init_h",
"else",
":",
"raise",
"Exception",
"(",
"'network type should be one of the lstm,bilstm,gru,bigru'",
")",
"if",
"rnn_type",
"==",
"'lstm'",
"or",
"rnn_type",
"==",
"'bilstm'",
":",
"init_states",
"=",
"init_c",
"+",
"init_h",
"elif",
"rnn_type",
"==",
"'gru'",
"or",
"rnn_type",
"==",
"'bigru'",
":",
"init_states",
"=",
"init_h",
"return",
"init_states"
] | set atual shape of data | [
"set",
"atual",
"shape",
"of",
"data"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/arch_deepspeech.py#L38-L80 |
23,489 | apache/incubator-mxnet | tools/coreml/converter/_mxnet_converter.py | check_error | def check_error(model, path, shapes, output = 'softmax_output', verbose = True):
"""
Check the difference between predictions from MXNet and CoreML.
"""
coreml_model = _coremltools.models.MLModel(path)
input_data = {}
input_data_copy = {}
for ip in shapes:
input_data[ip] = _np.random.rand(*shapes[ip]).astype('f')
input_data_copy[ip] = _np.copy(input_data[ip])
dataIter = _mxnet.io.NDArrayIter(input_data_copy)
mx_out = model.predict(dataIter).flatten()
e_out_dict = coreml_model.predict(_mxnet_remove_batch(input_data))
e_out = e_out_dict[output].flatten()
error = _np.linalg.norm(e_out - mx_out)
if verbose:
print("First few predictions from CoreML : %s" % e_out[0:10])
print("First few predictions from MXNet : %s" % e_out[0:10])
print("L2 Error on random data %s" % error)
return error | python | def check_error(model, path, shapes, output = 'softmax_output', verbose = True):
"""
Check the difference between predictions from MXNet and CoreML.
"""
coreml_model = _coremltools.models.MLModel(path)
input_data = {}
input_data_copy = {}
for ip in shapes:
input_data[ip] = _np.random.rand(*shapes[ip]).astype('f')
input_data_copy[ip] = _np.copy(input_data[ip])
dataIter = _mxnet.io.NDArrayIter(input_data_copy)
mx_out = model.predict(dataIter).flatten()
e_out_dict = coreml_model.predict(_mxnet_remove_batch(input_data))
e_out = e_out_dict[output].flatten()
error = _np.linalg.norm(e_out - mx_out)
if verbose:
print("First few predictions from CoreML : %s" % e_out[0:10])
print("First few predictions from MXNet : %s" % e_out[0:10])
print("L2 Error on random data %s" % error)
return error | [
"def",
"check_error",
"(",
"model",
",",
"path",
",",
"shapes",
",",
"output",
"=",
"'softmax_output'",
",",
"verbose",
"=",
"True",
")",
":",
"coreml_model",
"=",
"_coremltools",
".",
"models",
".",
"MLModel",
"(",
"path",
")",
"input_data",
"=",
"{",
"}",
"input_data_copy",
"=",
"{",
"}",
"for",
"ip",
"in",
"shapes",
":",
"input_data",
"[",
"ip",
"]",
"=",
"_np",
".",
"random",
".",
"rand",
"(",
"*",
"shapes",
"[",
"ip",
"]",
")",
".",
"astype",
"(",
"'f'",
")",
"input_data_copy",
"[",
"ip",
"]",
"=",
"_np",
".",
"copy",
"(",
"input_data",
"[",
"ip",
"]",
")",
"dataIter",
"=",
"_mxnet",
".",
"io",
".",
"NDArrayIter",
"(",
"input_data_copy",
")",
"mx_out",
"=",
"model",
".",
"predict",
"(",
"dataIter",
")",
".",
"flatten",
"(",
")",
"e_out_dict",
"=",
"coreml_model",
".",
"predict",
"(",
"_mxnet_remove_batch",
"(",
"input_data",
")",
")",
"e_out",
"=",
"e_out_dict",
"[",
"output",
"]",
".",
"flatten",
"(",
")",
"error",
"=",
"_np",
".",
"linalg",
".",
"norm",
"(",
"e_out",
"-",
"mx_out",
")",
"if",
"verbose",
":",
"print",
"(",
"\"First few predictions from CoreML : %s\"",
"%",
"e_out",
"[",
"0",
":",
"10",
"]",
")",
"print",
"(",
"\"First few predictions from MXNet : %s\"",
"%",
"e_out",
"[",
"0",
":",
"10",
"]",
")",
"print",
"(",
"\"L2 Error on random data %s\"",
"%",
"error",
")",
"return",
"error"
] | Check the difference between predictions from MXNet and CoreML. | [
"Check",
"the",
"difference",
"between",
"predictions",
"from",
"MXNet",
"and",
"CoreML",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_mxnet_converter.py#L56-L78 |
23,490 | apache/incubator-mxnet | example/reinforcement-learning/dqn/utils.py | sample_categorical | def sample_categorical(prob, rng):
"""Sample from independent categorical distributions
Each batch is an independent categorical distribution.
Parameters
----------
prob : numpy.ndarray
Probability of the categorical distribution. Shape --> (batch_num, category_num)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
Sampling result. Shape --> (batch_num,)
"""
ret = numpy.empty(prob.shape[0], dtype=numpy.float32)
for ind in range(prob.shape[0]):
ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0,
max=prob.shape[
1] - 0.5)
return ret | python | def sample_categorical(prob, rng):
"""Sample from independent categorical distributions
Each batch is an independent categorical distribution.
Parameters
----------
prob : numpy.ndarray
Probability of the categorical distribution. Shape --> (batch_num, category_num)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
Sampling result. Shape --> (batch_num,)
"""
ret = numpy.empty(prob.shape[0], dtype=numpy.float32)
for ind in range(prob.shape[0]):
ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0,
max=prob.shape[
1] - 0.5)
return ret | [
"def",
"sample_categorical",
"(",
"prob",
",",
"rng",
")",
":",
"ret",
"=",
"numpy",
".",
"empty",
"(",
"prob",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"numpy",
".",
"float32",
")",
"for",
"ind",
"in",
"range",
"(",
"prob",
".",
"shape",
"[",
"0",
"]",
")",
":",
"ret",
"[",
"ind",
"]",
"=",
"numpy",
".",
"searchsorted",
"(",
"numpy",
".",
"cumsum",
"(",
"prob",
"[",
"ind",
"]",
")",
",",
"rng",
".",
"rand",
"(",
")",
")",
".",
"clip",
"(",
"min",
"=",
"0.0",
",",
"max",
"=",
"prob",
".",
"shape",
"[",
"1",
"]",
"-",
"0.5",
")",
"return",
"ret"
] | Sample from independent categorical distributions
Each batch is an independent categorical distribution.
Parameters
----------
prob : numpy.ndarray
Probability of the categorical distribution. Shape --> (batch_num, category_num)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
Sampling result. Shape --> (batch_num,) | [
"Sample",
"from",
"independent",
"categorical",
"distributions"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/reinforcement-learning/dqn/utils.py#L133-L154 |
23,491 | apache/incubator-mxnet | example/reinforcement-learning/dqn/utils.py | sample_normal | def sample_normal(mean, var, rng):
"""Sample from independent normal distributions
Each element is an independent normal distribution.
Parameters
----------
mean : numpy.ndarray
Means of the normal distribution. Shape --> (batch_num, sample_dim)
var : numpy.ndarray
Variance of the normal distribution. Shape --> (batch_num, sample_dim)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
The sampling result. Shape --> (batch_num, sample_dim)
"""
ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean
return ret | python | def sample_normal(mean, var, rng):
"""Sample from independent normal distributions
Each element is an independent normal distribution.
Parameters
----------
mean : numpy.ndarray
Means of the normal distribution. Shape --> (batch_num, sample_dim)
var : numpy.ndarray
Variance of the normal distribution. Shape --> (batch_num, sample_dim)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
The sampling result. Shape --> (batch_num, sample_dim)
"""
ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean
return ret | [
"def",
"sample_normal",
"(",
"mean",
",",
"var",
",",
"rng",
")",
":",
"ret",
"=",
"numpy",
".",
"sqrt",
"(",
"var",
")",
"*",
"rng",
".",
"randn",
"(",
"*",
"mean",
".",
"shape",
")",
"+",
"mean",
"return",
"ret"
] | Sample from independent normal distributions
Each element is an independent normal distribution.
Parameters
----------
mean : numpy.ndarray
Means of the normal distribution. Shape --> (batch_num, sample_dim)
var : numpy.ndarray
Variance of the normal distribution. Shape --> (batch_num, sample_dim)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
The sampling result. Shape --> (batch_num, sample_dim) | [
"Sample",
"from",
"independent",
"normal",
"distributions"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/reinforcement-learning/dqn/utils.py#L157-L176 |
23,492 | apache/incubator-mxnet | example/nce-loss/nce.py | nce_loss_subwords | def nce_loss_subwords(
data, label, label_mask, label_weight, embed_weight, vocab_size, num_hidden):
"""NCE-Loss layer under subword-units input.
"""
# get subword-units embedding.
label_units_embed = mx.sym.Embedding(data=label,
input_dim=vocab_size,
weight=embed_weight,
output_dim=num_hidden)
# get valid subword-units embedding with the help of label_mask
# it's achieved by multiplying zeros to useless units in order to handle variable-length input.
label_units_embed = mx.sym.broadcast_mul(lhs=label_units_embed,
rhs=label_mask,
name='label_units_embed')
# sum over them to get label word embedding.
label_embed = mx.sym.sum(label_units_embed, axis=2, name='label_embed')
# by boardcast_mul and sum you can get prediction scores in all label_embed inputs,
# which is easy to feed into LogisticRegressionOutput and make your code more concise.
data = mx.sym.Reshape(data=data, shape=(-1, 1, num_hidden))
pred = mx.sym.broadcast_mul(data, label_embed)
pred = mx.sym.sum(data=pred, axis=2)
return mx.sym.LogisticRegressionOutput(data=pred,
label=label_weight) | python | def nce_loss_subwords(
data, label, label_mask, label_weight, embed_weight, vocab_size, num_hidden):
"""NCE-Loss layer under subword-units input.
"""
# get subword-units embedding.
label_units_embed = mx.sym.Embedding(data=label,
input_dim=vocab_size,
weight=embed_weight,
output_dim=num_hidden)
# get valid subword-units embedding with the help of label_mask
# it's achieved by multiplying zeros to useless units in order to handle variable-length input.
label_units_embed = mx.sym.broadcast_mul(lhs=label_units_embed,
rhs=label_mask,
name='label_units_embed')
# sum over them to get label word embedding.
label_embed = mx.sym.sum(label_units_embed, axis=2, name='label_embed')
# by boardcast_mul and sum you can get prediction scores in all label_embed inputs,
# which is easy to feed into LogisticRegressionOutput and make your code more concise.
data = mx.sym.Reshape(data=data, shape=(-1, 1, num_hidden))
pred = mx.sym.broadcast_mul(data, label_embed)
pred = mx.sym.sum(data=pred, axis=2)
return mx.sym.LogisticRegressionOutput(data=pred,
label=label_weight) | [
"def",
"nce_loss_subwords",
"(",
"data",
",",
"label",
",",
"label_mask",
",",
"label_weight",
",",
"embed_weight",
",",
"vocab_size",
",",
"num_hidden",
")",
":",
"# get subword-units embedding.",
"label_units_embed",
"=",
"mx",
".",
"sym",
".",
"Embedding",
"(",
"data",
"=",
"label",
",",
"input_dim",
"=",
"vocab_size",
",",
"weight",
"=",
"embed_weight",
",",
"output_dim",
"=",
"num_hidden",
")",
"# get valid subword-units embedding with the help of label_mask",
"# it's achieved by multiplying zeros to useless units in order to handle variable-length input.",
"label_units_embed",
"=",
"mx",
".",
"sym",
".",
"broadcast_mul",
"(",
"lhs",
"=",
"label_units_embed",
",",
"rhs",
"=",
"label_mask",
",",
"name",
"=",
"'label_units_embed'",
")",
"# sum over them to get label word embedding.",
"label_embed",
"=",
"mx",
".",
"sym",
".",
"sum",
"(",
"label_units_embed",
",",
"axis",
"=",
"2",
",",
"name",
"=",
"'label_embed'",
")",
"# by boardcast_mul and sum you can get prediction scores in all label_embed inputs,",
"# which is easy to feed into LogisticRegressionOutput and make your code more concise.",
"data",
"=",
"mx",
".",
"sym",
".",
"Reshape",
"(",
"data",
"=",
"data",
",",
"shape",
"=",
"(",
"-",
"1",
",",
"1",
",",
"num_hidden",
")",
")",
"pred",
"=",
"mx",
".",
"sym",
".",
"broadcast_mul",
"(",
"data",
",",
"label_embed",
")",
"pred",
"=",
"mx",
".",
"sym",
".",
"sum",
"(",
"data",
"=",
"pred",
",",
"axis",
"=",
"2",
")",
"return",
"mx",
".",
"sym",
".",
"LogisticRegressionOutput",
"(",
"data",
"=",
"pred",
",",
"label",
"=",
"label_weight",
")"
] | NCE-Loss layer under subword-units input. | [
"NCE",
"-",
"Loss",
"layer",
"under",
"subword",
"-",
"units",
"input",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/nce-loss/nce.py#L38-L62 |
23,493 | apache/incubator-mxnet | example/gluon/super_resolution/super_resolution.py | get_dataset | def get_dataset(prefetch=False):
"""Download the BSDS500 dataset and return train and test iters."""
if path.exists(data_dir):
print(
"Directory {} already exists, skipping.\n"
"To force download and extraction, delete the directory and re-run."
"".format(data_dir),
file=sys.stderr,
)
else:
print("Downloading dataset...", file=sys.stderr)
downloaded_file = download(dataset_url, dirname=datasets_tmpdir)
print("done", file=sys.stderr)
print("Extracting files...", end="", file=sys.stderr)
os.makedirs(data_dir)
os.makedirs(tmp_dir)
with zipfile.ZipFile(downloaded_file) as archive:
archive.extractall(tmp_dir)
shutil.rmtree(datasets_tmpdir)
shutil.copytree(
path.join(tmp_dir, "BSDS500-master", "BSDS500", "data", "images"),
path.join(data_dir, "images"),
)
shutil.copytree(
path.join(tmp_dir, "BSDS500-master", "BSDS500", "data", "groundTruth"),
path.join(data_dir, "groundTruth"),
)
shutil.rmtree(tmp_dir)
print("done", file=sys.stderr)
crop_size = 256
crop_size -= crop_size % upscale_factor
input_crop_size = crop_size // upscale_factor
input_transform = [CenterCropAug((crop_size, crop_size)), ResizeAug(input_crop_size)]
target_transform = [CenterCropAug((crop_size, crop_size))]
iters = (
ImagePairIter(
path.join(data_dir, "images", "train"),
(input_crop_size, input_crop_size),
(crop_size, crop_size),
batch_size,
color_flag,
input_transform,
target_transform,
),
ImagePairIter(
path.join(data_dir, "images", "test"),
(input_crop_size, input_crop_size),
(crop_size, crop_size),
test_batch_size,
color_flag,
input_transform,
target_transform,
),
)
return [PrefetchingIter(i) for i in iters] if prefetch else iters | python | def get_dataset(prefetch=False):
"""Download the BSDS500 dataset and return train and test iters."""
if path.exists(data_dir):
print(
"Directory {} already exists, skipping.\n"
"To force download and extraction, delete the directory and re-run."
"".format(data_dir),
file=sys.stderr,
)
else:
print("Downloading dataset...", file=sys.stderr)
downloaded_file = download(dataset_url, dirname=datasets_tmpdir)
print("done", file=sys.stderr)
print("Extracting files...", end="", file=sys.stderr)
os.makedirs(data_dir)
os.makedirs(tmp_dir)
with zipfile.ZipFile(downloaded_file) as archive:
archive.extractall(tmp_dir)
shutil.rmtree(datasets_tmpdir)
shutil.copytree(
path.join(tmp_dir, "BSDS500-master", "BSDS500", "data", "images"),
path.join(data_dir, "images"),
)
shutil.copytree(
path.join(tmp_dir, "BSDS500-master", "BSDS500", "data", "groundTruth"),
path.join(data_dir, "groundTruth"),
)
shutil.rmtree(tmp_dir)
print("done", file=sys.stderr)
crop_size = 256
crop_size -= crop_size % upscale_factor
input_crop_size = crop_size // upscale_factor
input_transform = [CenterCropAug((crop_size, crop_size)), ResizeAug(input_crop_size)]
target_transform = [CenterCropAug((crop_size, crop_size))]
iters = (
ImagePairIter(
path.join(data_dir, "images", "train"),
(input_crop_size, input_crop_size),
(crop_size, crop_size),
batch_size,
color_flag,
input_transform,
target_transform,
),
ImagePairIter(
path.join(data_dir, "images", "test"),
(input_crop_size, input_crop_size),
(crop_size, crop_size),
test_batch_size,
color_flag,
input_transform,
target_transform,
),
)
return [PrefetchingIter(i) for i in iters] if prefetch else iters | [
"def",
"get_dataset",
"(",
"prefetch",
"=",
"False",
")",
":",
"if",
"path",
".",
"exists",
"(",
"data_dir",
")",
":",
"print",
"(",
"\"Directory {} already exists, skipping.\\n\"",
"\"To force download and extraction, delete the directory and re-run.\"",
"\"\"",
".",
"format",
"(",
"data_dir",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
",",
")",
"else",
":",
"print",
"(",
"\"Downloading dataset...\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"downloaded_file",
"=",
"download",
"(",
"dataset_url",
",",
"dirname",
"=",
"datasets_tmpdir",
")",
"print",
"(",
"\"done\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"\"Extracting files...\"",
",",
"end",
"=",
"\"\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"os",
".",
"makedirs",
"(",
"data_dir",
")",
"os",
".",
"makedirs",
"(",
"tmp_dir",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"downloaded_file",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
"tmp_dir",
")",
"shutil",
".",
"rmtree",
"(",
"datasets_tmpdir",
")",
"shutil",
".",
"copytree",
"(",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"\"BSDS500-master\"",
",",
"\"BSDS500\"",
",",
"\"data\"",
",",
"\"images\"",
")",
",",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"images\"",
")",
",",
")",
"shutil",
".",
"copytree",
"(",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"\"BSDS500-master\"",
",",
"\"BSDS500\"",
",",
"\"data\"",
",",
"\"groundTruth\"",
")",
",",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"groundTruth\"",
")",
",",
")",
"shutil",
".",
"rmtree",
"(",
"tmp_dir",
")",
"print",
"(",
"\"done\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"crop_size",
"=",
"256",
"crop_size",
"-=",
"crop_size",
"%",
"upscale_factor",
"input_crop_size",
"=",
"crop_size",
"//",
"upscale_factor",
"input_transform",
"=",
"[",
"CenterCropAug",
"(",
"(",
"crop_size",
",",
"crop_size",
")",
")",
",",
"ResizeAug",
"(",
"input_crop_size",
")",
"]",
"target_transform",
"=",
"[",
"CenterCropAug",
"(",
"(",
"crop_size",
",",
"crop_size",
")",
")",
"]",
"iters",
"=",
"(",
"ImagePairIter",
"(",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"images\"",
",",
"\"train\"",
")",
",",
"(",
"input_crop_size",
",",
"input_crop_size",
")",
",",
"(",
"crop_size",
",",
"crop_size",
")",
",",
"batch_size",
",",
"color_flag",
",",
"input_transform",
",",
"target_transform",
",",
")",
",",
"ImagePairIter",
"(",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"images\"",
",",
"\"test\"",
")",
",",
"(",
"input_crop_size",
",",
"input_crop_size",
")",
",",
"(",
"crop_size",
",",
"crop_size",
")",
",",
"test_batch_size",
",",
"color_flag",
",",
"input_transform",
",",
"target_transform",
",",
")",
",",
")",
"return",
"[",
"PrefetchingIter",
"(",
"i",
")",
"for",
"i",
"in",
"iters",
"]",
"if",
"prefetch",
"else",
"iters"
] | Download the BSDS500 dataset and return train and test iters. | [
"Download",
"the",
"BSDS500",
"dataset",
"and",
"return",
"train",
"and",
"test",
"iters",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/super_resolution/super_resolution.py#L69-L130 |
23,494 | apache/incubator-mxnet | example/rnn/large_word_lm/run_utils.py | evaluate | def evaluate(mod, data_iter, epoch, log_interval):
""" Run evaluation on cpu. """
start = time.time()
total_L = 0.0
nbatch = 0
density = 0
mod.set_states(value=0)
for batch in data_iter:
mod.forward(batch, is_train=False)
outputs = mod.get_outputs(merge_multi_context=False)
states = outputs[:-1]
total_L += outputs[-1][0]
mod.set_states(states=states)
nbatch += 1
# don't include padding data in the test perplexity
density += batch.data[1].mean()
if (nbatch + 1) % log_interval == 0:
logging.info("Eval batch %d loss : %.7f" % (nbatch, (total_L / density).asscalar()))
data_iter.reset()
loss = (total_L / density).asscalar()
ppl = math.exp(loss) if loss < 100 else 1e37
end = time.time()
logging.info('Iter[%d]\t\t CE loss %.7f, ppl %.7f. Eval duration = %.2f seconds ' % \
(epoch, loss, ppl, end - start))
return loss | python | def evaluate(mod, data_iter, epoch, log_interval):
""" Run evaluation on cpu. """
start = time.time()
total_L = 0.0
nbatch = 0
density = 0
mod.set_states(value=0)
for batch in data_iter:
mod.forward(batch, is_train=False)
outputs = mod.get_outputs(merge_multi_context=False)
states = outputs[:-1]
total_L += outputs[-1][0]
mod.set_states(states=states)
nbatch += 1
# don't include padding data in the test perplexity
density += batch.data[1].mean()
if (nbatch + 1) % log_interval == 0:
logging.info("Eval batch %d loss : %.7f" % (nbatch, (total_L / density).asscalar()))
data_iter.reset()
loss = (total_L / density).asscalar()
ppl = math.exp(loss) if loss < 100 else 1e37
end = time.time()
logging.info('Iter[%d]\t\t CE loss %.7f, ppl %.7f. Eval duration = %.2f seconds ' % \
(epoch, loss, ppl, end - start))
return loss | [
"def",
"evaluate",
"(",
"mod",
",",
"data_iter",
",",
"epoch",
",",
"log_interval",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"total_L",
"=",
"0.0",
"nbatch",
"=",
"0",
"density",
"=",
"0",
"mod",
".",
"set_states",
"(",
"value",
"=",
"0",
")",
"for",
"batch",
"in",
"data_iter",
":",
"mod",
".",
"forward",
"(",
"batch",
",",
"is_train",
"=",
"False",
")",
"outputs",
"=",
"mod",
".",
"get_outputs",
"(",
"merge_multi_context",
"=",
"False",
")",
"states",
"=",
"outputs",
"[",
":",
"-",
"1",
"]",
"total_L",
"+=",
"outputs",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"mod",
".",
"set_states",
"(",
"states",
"=",
"states",
")",
"nbatch",
"+=",
"1",
"# don't include padding data in the test perplexity",
"density",
"+=",
"batch",
".",
"data",
"[",
"1",
"]",
".",
"mean",
"(",
")",
"if",
"(",
"nbatch",
"+",
"1",
")",
"%",
"log_interval",
"==",
"0",
":",
"logging",
".",
"info",
"(",
"\"Eval batch %d loss : %.7f\"",
"%",
"(",
"nbatch",
",",
"(",
"total_L",
"/",
"density",
")",
".",
"asscalar",
"(",
")",
")",
")",
"data_iter",
".",
"reset",
"(",
")",
"loss",
"=",
"(",
"total_L",
"/",
"density",
")",
".",
"asscalar",
"(",
")",
"ppl",
"=",
"math",
".",
"exp",
"(",
"loss",
")",
"if",
"loss",
"<",
"100",
"else",
"1e37",
"end",
"=",
"time",
".",
"time",
"(",
")",
"logging",
".",
"info",
"(",
"'Iter[%d]\\t\\t CE loss %.7f, ppl %.7f. Eval duration = %.2f seconds '",
"%",
"(",
"epoch",
",",
"loss",
",",
"ppl",
",",
"end",
"-",
"start",
")",
")",
"return",
"loss"
] | Run evaluation on cpu. | [
"Run",
"evaluation",
"on",
"cpu",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/run_utils.py#L66-L90 |
23,495 | apache/incubator-mxnet | example/fcn-xs/data.py | FileIter.next | def next(self):
"""return one dict which contains "data" and "label" """
if self.iter_next():
self.data, self.label = self._read()
return {self.data_name : self.data[0][1],
self.label_name : self.label[0][1]}
else:
raise StopIteration | python | def next(self):
"""return one dict which contains "data" and "label" """
if self.iter_next():
self.data, self.label = self._read()
return {self.data_name : self.data[0][1],
self.label_name : self.label[0][1]}
else:
raise StopIteration | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"iter_next",
"(",
")",
":",
"self",
".",
"data",
",",
"self",
".",
"label",
"=",
"self",
".",
"_read",
"(",
")",
"return",
"{",
"self",
".",
"data_name",
":",
"self",
".",
"data",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"self",
".",
"label_name",
":",
"self",
".",
"label",
"[",
"0",
"]",
"[",
"1",
"]",
"}",
"else",
":",
"raise",
"StopIteration"
] | return one dict which contains "data" and "label" | [
"return",
"one",
"dict",
"which",
"contains",
"data",
"and",
"label"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/fcn-xs/data.py#L132-L139 |
23,496 | apache/incubator-mxnet | python/mxnet/contrib/onnx/onnx2mx/import_onnx.py | GraphProto.from_onnx | def from_onnx(self, graph):
"""Construct symbol from onnx graph.
Parameters
----------
graph : onnx protobuf object
The loaded onnx graph
Returns
-------
sym :symbol.Symbol
The returned mxnet symbol
params : dict
A dict of name: nd.array pairs, used as pretrained weights
"""
# get input, output shapes
self.model_metadata = self.get_graph_metadata(graph)
# parse network inputs, aka parameters
for init_tensor in graph.initializer:
if not init_tensor.name.strip():
raise ValueError("Tensor's name is required.")
self._params[init_tensor.name] = self._parse_array(init_tensor)
# converting GraphProto message
for i in graph.input:
if i.name in self._params:
# i is a param instead of input
self._nodes[i.name] = symbol.Variable(name=i.name,
shape=self._params[i.name].shape)
else:
self._nodes[i.name] = symbol.Variable(name=i.name)
# constructing nodes, nodes are stored as directed acyclic graph
# converting NodeProto message
for node in graph.node:
op_name = node.op_type
node_name = node.name.strip()
node_name = node_name if node_name else None
onnx_attr = self._parse_attr(node.attribute)
inputs = [self._nodes[i] for i in node.input]
mxnet_sym = self._convert_operator(node_name, op_name, onnx_attr, inputs)
for k, i in zip(list(node.output), range(len(mxnet_sym.list_outputs()))):
self._nodes[k] = mxnet_sym[i]
# splitting params into args and aux params
for args in mxnet_sym.list_arguments():
if args in self._params:
self.arg_dict.update({args: nd.array(self._params[args])})
for aux in mxnet_sym.list_auxiliary_states():
if aux in self._params:
self.aux_dict.update({aux: nd.array(self._params[aux])})
# now return the outputs
out = [self._nodes[i.name] for i in graph.output]
if len(out) > 1:
out = symbol.Group(out)
else:
out = out[0]
return out, self.arg_dict, self.aux_dict | python | def from_onnx(self, graph):
"""Construct symbol from onnx graph.
Parameters
----------
graph : onnx protobuf object
The loaded onnx graph
Returns
-------
sym :symbol.Symbol
The returned mxnet symbol
params : dict
A dict of name: nd.array pairs, used as pretrained weights
"""
# get input, output shapes
self.model_metadata = self.get_graph_metadata(graph)
# parse network inputs, aka parameters
for init_tensor in graph.initializer:
if not init_tensor.name.strip():
raise ValueError("Tensor's name is required.")
self._params[init_tensor.name] = self._parse_array(init_tensor)
# converting GraphProto message
for i in graph.input:
if i.name in self._params:
# i is a param instead of input
self._nodes[i.name] = symbol.Variable(name=i.name,
shape=self._params[i.name].shape)
else:
self._nodes[i.name] = symbol.Variable(name=i.name)
# constructing nodes, nodes are stored as directed acyclic graph
# converting NodeProto message
for node in graph.node:
op_name = node.op_type
node_name = node.name.strip()
node_name = node_name if node_name else None
onnx_attr = self._parse_attr(node.attribute)
inputs = [self._nodes[i] for i in node.input]
mxnet_sym = self._convert_operator(node_name, op_name, onnx_attr, inputs)
for k, i in zip(list(node.output), range(len(mxnet_sym.list_outputs()))):
self._nodes[k] = mxnet_sym[i]
# splitting params into args and aux params
for args in mxnet_sym.list_arguments():
if args in self._params:
self.arg_dict.update({args: nd.array(self._params[args])})
for aux in mxnet_sym.list_auxiliary_states():
if aux in self._params:
self.aux_dict.update({aux: nd.array(self._params[aux])})
# now return the outputs
out = [self._nodes[i.name] for i in graph.output]
if len(out) > 1:
out = symbol.Group(out)
else:
out = out[0]
return out, self.arg_dict, self.aux_dict | [
"def",
"from_onnx",
"(",
"self",
",",
"graph",
")",
":",
"# get input, output shapes",
"self",
".",
"model_metadata",
"=",
"self",
".",
"get_graph_metadata",
"(",
"graph",
")",
"# parse network inputs, aka parameters",
"for",
"init_tensor",
"in",
"graph",
".",
"initializer",
":",
"if",
"not",
"init_tensor",
".",
"name",
".",
"strip",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Tensor's name is required.\"",
")",
"self",
".",
"_params",
"[",
"init_tensor",
".",
"name",
"]",
"=",
"self",
".",
"_parse_array",
"(",
"init_tensor",
")",
"# converting GraphProto message",
"for",
"i",
"in",
"graph",
".",
"input",
":",
"if",
"i",
".",
"name",
"in",
"self",
".",
"_params",
":",
"# i is a param instead of input",
"self",
".",
"_nodes",
"[",
"i",
".",
"name",
"]",
"=",
"symbol",
".",
"Variable",
"(",
"name",
"=",
"i",
".",
"name",
",",
"shape",
"=",
"self",
".",
"_params",
"[",
"i",
".",
"name",
"]",
".",
"shape",
")",
"else",
":",
"self",
".",
"_nodes",
"[",
"i",
".",
"name",
"]",
"=",
"symbol",
".",
"Variable",
"(",
"name",
"=",
"i",
".",
"name",
")",
"# constructing nodes, nodes are stored as directed acyclic graph",
"# converting NodeProto message",
"for",
"node",
"in",
"graph",
".",
"node",
":",
"op_name",
"=",
"node",
".",
"op_type",
"node_name",
"=",
"node",
".",
"name",
".",
"strip",
"(",
")",
"node_name",
"=",
"node_name",
"if",
"node_name",
"else",
"None",
"onnx_attr",
"=",
"self",
".",
"_parse_attr",
"(",
"node",
".",
"attribute",
")",
"inputs",
"=",
"[",
"self",
".",
"_nodes",
"[",
"i",
"]",
"for",
"i",
"in",
"node",
".",
"input",
"]",
"mxnet_sym",
"=",
"self",
".",
"_convert_operator",
"(",
"node_name",
",",
"op_name",
",",
"onnx_attr",
",",
"inputs",
")",
"for",
"k",
",",
"i",
"in",
"zip",
"(",
"list",
"(",
"node",
".",
"output",
")",
",",
"range",
"(",
"len",
"(",
"mxnet_sym",
".",
"list_outputs",
"(",
")",
")",
")",
")",
":",
"self",
".",
"_nodes",
"[",
"k",
"]",
"=",
"mxnet_sym",
"[",
"i",
"]",
"# splitting params into args and aux params",
"for",
"args",
"in",
"mxnet_sym",
".",
"list_arguments",
"(",
")",
":",
"if",
"args",
"in",
"self",
".",
"_params",
":",
"self",
".",
"arg_dict",
".",
"update",
"(",
"{",
"args",
":",
"nd",
".",
"array",
"(",
"self",
".",
"_params",
"[",
"args",
"]",
")",
"}",
")",
"for",
"aux",
"in",
"mxnet_sym",
".",
"list_auxiliary_states",
"(",
")",
":",
"if",
"aux",
"in",
"self",
".",
"_params",
":",
"self",
".",
"aux_dict",
".",
"update",
"(",
"{",
"aux",
":",
"nd",
".",
"array",
"(",
"self",
".",
"_params",
"[",
"aux",
"]",
")",
"}",
")",
"# now return the outputs",
"out",
"=",
"[",
"self",
".",
"_nodes",
"[",
"i",
".",
"name",
"]",
"for",
"i",
"in",
"graph",
".",
"output",
"]",
"if",
"len",
"(",
"out",
")",
">",
"1",
":",
"out",
"=",
"symbol",
".",
"Group",
"(",
"out",
")",
"else",
":",
"out",
"=",
"out",
"[",
"0",
"]",
"return",
"out",
",",
"self",
".",
"arg_dict",
",",
"self",
".",
"aux_dict"
] | Construct symbol from onnx graph.
Parameters
----------
graph : onnx protobuf object
The loaded onnx graph
Returns
-------
sym :symbol.Symbol
The returned mxnet symbol
params : dict
A dict of name: nd.array pairs, used as pretrained weights | [
"Construct",
"symbol",
"from",
"onnx",
"graph",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/import_onnx.py#L76-L135 |
23,497 | apache/incubator-mxnet | python/mxnet/contrib/onnx/onnx2mx/import_onnx.py | GraphProto.get_graph_metadata | def get_graph_metadata(self, graph):
"""
Get the model metadata from a given onnx graph.
"""
_params = set()
for tensor_vals in graph.initializer:
_params.add(tensor_vals.name)
input_data = []
for graph_input in graph.input:
if graph_input.name not in _params:
shape = [val.dim_value for val in graph_input.type.tensor_type.shape.dim]
input_data.append((graph_input.name, tuple(shape)))
output_data = []
for graph_out in graph.output:
shape = [val.dim_value for val in graph_out.type.tensor_type.shape.dim]
output_data.append((graph_out.name, tuple(shape)))
metadata = {'input_tensor_data' : input_data,
'output_tensor_data' : output_data
}
return metadata | python | def get_graph_metadata(self, graph):
"""
Get the model metadata from a given onnx graph.
"""
_params = set()
for tensor_vals in graph.initializer:
_params.add(tensor_vals.name)
input_data = []
for graph_input in graph.input:
if graph_input.name not in _params:
shape = [val.dim_value for val in graph_input.type.tensor_type.shape.dim]
input_data.append((graph_input.name, tuple(shape)))
output_data = []
for graph_out in graph.output:
shape = [val.dim_value for val in graph_out.type.tensor_type.shape.dim]
output_data.append((graph_out.name, tuple(shape)))
metadata = {'input_tensor_data' : input_data,
'output_tensor_data' : output_data
}
return metadata | [
"def",
"get_graph_metadata",
"(",
"self",
",",
"graph",
")",
":",
"_params",
"=",
"set",
"(",
")",
"for",
"tensor_vals",
"in",
"graph",
".",
"initializer",
":",
"_params",
".",
"add",
"(",
"tensor_vals",
".",
"name",
")",
"input_data",
"=",
"[",
"]",
"for",
"graph_input",
"in",
"graph",
".",
"input",
":",
"if",
"graph_input",
".",
"name",
"not",
"in",
"_params",
":",
"shape",
"=",
"[",
"val",
".",
"dim_value",
"for",
"val",
"in",
"graph_input",
".",
"type",
".",
"tensor_type",
".",
"shape",
".",
"dim",
"]",
"input_data",
".",
"append",
"(",
"(",
"graph_input",
".",
"name",
",",
"tuple",
"(",
"shape",
")",
")",
")",
"output_data",
"=",
"[",
"]",
"for",
"graph_out",
"in",
"graph",
".",
"output",
":",
"shape",
"=",
"[",
"val",
".",
"dim_value",
"for",
"val",
"in",
"graph_out",
".",
"type",
".",
"tensor_type",
".",
"shape",
".",
"dim",
"]",
"output_data",
".",
"append",
"(",
"(",
"graph_out",
".",
"name",
",",
"tuple",
"(",
"shape",
")",
")",
")",
"metadata",
"=",
"{",
"'input_tensor_data'",
":",
"input_data",
",",
"'output_tensor_data'",
":",
"output_data",
"}",
"return",
"metadata"
] | Get the model metadata from a given onnx graph. | [
"Get",
"the",
"model",
"metadata",
"from",
"a",
"given",
"onnx",
"graph",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/import_onnx.py#L137-L158 |
23,498 | apache/incubator-mxnet | python/mxnet/contrib/onnx/onnx2mx/import_onnx.py | GraphProto.graph_to_gluon | def graph_to_gluon(self, graph, ctx):
"""Construct SymbolBlock from onnx graph.
Parameters
----------
graph : onnx protobuf object
The loaded onnx graph
ctx : Context or list of Context
Loads the model into one or many context(s).
Returns
-------
sym_block :gluon.nn.SymbolBlock
The returned gluon SymbolBlock
"""
sym, arg_params, aux_params = self.from_onnx(graph)
metadata = self.get_graph_metadata(graph)
data_names = [input_tensor[0] for input_tensor in metadata['input_tensor_data']]
data_inputs = [symbol.var(data_name) for data_name in data_names]
from ....gluon import SymbolBlock
net = SymbolBlock(outputs=sym, inputs=data_inputs)
net_params = net.collect_params()
for param in arg_params:
if param in net_params:
net_params[param].shape = arg_params[param].shape
net_params[param]._load_init(arg_params[param], ctx=ctx)
for param in aux_params:
if param in net_params:
net_params[param].shape = aux_params[param].shape
net_params[param]._load_init(aux_params[param], ctx=ctx)
return net | python | def graph_to_gluon(self, graph, ctx):
"""Construct SymbolBlock from onnx graph.
Parameters
----------
graph : onnx protobuf object
The loaded onnx graph
ctx : Context or list of Context
Loads the model into one or many context(s).
Returns
-------
sym_block :gluon.nn.SymbolBlock
The returned gluon SymbolBlock
"""
sym, arg_params, aux_params = self.from_onnx(graph)
metadata = self.get_graph_metadata(graph)
data_names = [input_tensor[0] for input_tensor in metadata['input_tensor_data']]
data_inputs = [symbol.var(data_name) for data_name in data_names]
from ....gluon import SymbolBlock
net = SymbolBlock(outputs=sym, inputs=data_inputs)
net_params = net.collect_params()
for param in arg_params:
if param in net_params:
net_params[param].shape = arg_params[param].shape
net_params[param]._load_init(arg_params[param], ctx=ctx)
for param in aux_params:
if param in net_params:
net_params[param].shape = aux_params[param].shape
net_params[param]._load_init(aux_params[param], ctx=ctx)
return net | [
"def",
"graph_to_gluon",
"(",
"self",
",",
"graph",
",",
"ctx",
")",
":",
"sym",
",",
"arg_params",
",",
"aux_params",
"=",
"self",
".",
"from_onnx",
"(",
"graph",
")",
"metadata",
"=",
"self",
".",
"get_graph_metadata",
"(",
"graph",
")",
"data_names",
"=",
"[",
"input_tensor",
"[",
"0",
"]",
"for",
"input_tensor",
"in",
"metadata",
"[",
"'input_tensor_data'",
"]",
"]",
"data_inputs",
"=",
"[",
"symbol",
".",
"var",
"(",
"data_name",
")",
"for",
"data_name",
"in",
"data_names",
"]",
"from",
".",
".",
".",
".",
"gluon",
"import",
"SymbolBlock",
"net",
"=",
"SymbolBlock",
"(",
"outputs",
"=",
"sym",
",",
"inputs",
"=",
"data_inputs",
")",
"net_params",
"=",
"net",
".",
"collect_params",
"(",
")",
"for",
"param",
"in",
"arg_params",
":",
"if",
"param",
"in",
"net_params",
":",
"net_params",
"[",
"param",
"]",
".",
"shape",
"=",
"arg_params",
"[",
"param",
"]",
".",
"shape",
"net_params",
"[",
"param",
"]",
".",
"_load_init",
"(",
"arg_params",
"[",
"param",
"]",
",",
"ctx",
"=",
"ctx",
")",
"for",
"param",
"in",
"aux_params",
":",
"if",
"param",
"in",
"net_params",
":",
"net_params",
"[",
"param",
"]",
".",
"shape",
"=",
"aux_params",
"[",
"param",
"]",
".",
"shape",
"net_params",
"[",
"param",
"]",
".",
"_load_init",
"(",
"aux_params",
"[",
"param",
"]",
",",
"ctx",
"=",
"ctx",
")",
"return",
"net"
] | Construct SymbolBlock from onnx graph.
Parameters
----------
graph : onnx protobuf object
The loaded onnx graph
ctx : Context or list of Context
Loads the model into one or many context(s).
Returns
-------
sym_block :gluon.nn.SymbolBlock
The returned gluon SymbolBlock | [
"Construct",
"SymbolBlock",
"from",
"onnx",
"graph",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/import_onnx.py#L160-L191 |
23,499 | apache/incubator-mxnet | python/mxnet/contrib/svrg_optimization/svrg_module.py | SVRGModule.reshape | def reshape(self, data_shapes, label_shapes=None):
"""Reshapes both modules for new input shapes.
Parameters
----------
data_shapes : list of (str, tuple)
Typically is ``data_iter.provide_data``.
label_shapes : list of (str, tuple)
Typically is ``data_iter.provide_label``.
"""
super(SVRGModule, self).reshape(data_shapes, label_shapes=label_shapes)
self._mod_aux.reshape(data_shapes, label_shapes=label_shapes) | python | def reshape(self, data_shapes, label_shapes=None):
"""Reshapes both modules for new input shapes.
Parameters
----------
data_shapes : list of (str, tuple)
Typically is ``data_iter.provide_data``.
label_shapes : list of (str, tuple)
Typically is ``data_iter.provide_label``.
"""
super(SVRGModule, self).reshape(data_shapes, label_shapes=label_shapes)
self._mod_aux.reshape(data_shapes, label_shapes=label_shapes) | [
"def",
"reshape",
"(",
"self",
",",
"data_shapes",
",",
"label_shapes",
"=",
"None",
")",
":",
"super",
"(",
"SVRGModule",
",",
"self",
")",
".",
"reshape",
"(",
"data_shapes",
",",
"label_shapes",
"=",
"label_shapes",
")",
"self",
".",
"_mod_aux",
".",
"reshape",
"(",
"data_shapes",
",",
"label_shapes",
"=",
"label_shapes",
")"
] | Reshapes both modules for new input shapes.
Parameters
----------
data_shapes : list of (str, tuple)
Typically is ``data_iter.provide_data``.
label_shapes : list of (str, tuple)
Typically is ``data_iter.provide_label``. | [
"Reshapes",
"both",
"modules",
"for",
"new",
"input",
"shapes",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/svrg_optimization/svrg_module.py#L101-L112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.