partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | Video.process_frames_mouth | Preprocess from frames using mouth detector | example/gluon/lipnet/utils/preprocess_data.py | def process_frames_mouth(self, frames):
"""
Preprocess from frames using mouth detector
"""
self.face = np.array(frames)
self.mouth = np.array(frames)
self.set_data(frames) | def process_frames_mouth(self, frames):
"""
Preprocess from frames using mouth detector
"""
self.face = np.array(frames)
self.mouth = np.array(frames)
self.set_data(frames) | [
"Preprocess",
"from",
"frames",
"using",
"mouth",
"detector"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/preprocess_data.py#L118-L124 | [
"def",
"process_frames_mouth",
"(",
"self",
",",
"frames",
")",
":",
"self",
".",
"face",
"=",
"np",
".",
"array",
"(",
"frames",
")",
"self",
".",
"mouth",
"=",
"np",
".",
"array",
"(",
"frames",
")",
"self",
".",
"set_data",
"(",
"frames",
")"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | Video.get_frames_mouth | Get frames using mouth crop | example/gluon/lipnet/utils/preprocess_data.py | def get_frames_mouth(self, detector, predictor, frames):
"""
Get frames using mouth crop
"""
mouth_width = 100
mouth_height = 50
horizontal_pad = 0.19
normalize_ratio = None
mouth_frames = []
for frame in frames:
dets = detector(frame, ... | def get_frames_mouth(self, detector, predictor, frames):
"""
Get frames using mouth crop
"""
mouth_width = 100
mouth_height = 50
horizontal_pad = 0.19
normalize_ratio = None
mouth_frames = []
for frame in frames:
dets = detector(frame, ... | [
"Get",
"frames",
"using",
"mouth",
"crop"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/preprocess_data.py#L126-L173 | [
"def",
"get_frames_mouth",
"(",
"self",
",",
"detector",
",",
"predictor",
",",
"frames",
")",
":",
"mouth_width",
"=",
"100",
"mouth_height",
"=",
"50",
"horizontal_pad",
"=",
"0.19",
"normalize_ratio",
"=",
"None",
"mouth_frames",
"=",
"[",
"]",
"for",
"fr... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | Video.get_video_frames | Get video frames | example/gluon/lipnet/utils/preprocess_data.py | def get_video_frames(self, path):
"""
Get video frames
"""
videogen = skvideo.io.vreader(path)
frames = np.array([frame for frame in videogen])
return frames | def get_video_frames(self, path):
"""
Get video frames
"""
videogen = skvideo.io.vreader(path)
frames = np.array([frame for frame in videogen])
return frames | [
"Get",
"video",
"frames"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/preprocess_data.py#L175-L181 | [
"def",
"get_video_frames",
"(",
"self",
",",
"path",
")",
":",
"videogen",
"=",
"skvideo",
".",
"io",
".",
"vreader",
"(",
"path",
")",
"frames",
"=",
"np",
".",
"array",
"(",
"[",
"frame",
"for",
"frame",
"in",
"videogen",
"]",
")",
"return",
"frame... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | Video.set_data | Prepare the input of model | example/gluon/lipnet/utils/preprocess_data.py | def set_data(self, frames):
"""
Prepare the input of model
"""
data_frames = []
for frame in frames:
#frame H x W x C
frame = frame.swapaxes(0, 1) # swap width and height to form format W x H x C
if len(frame.shape) < 3:
frame =... | def set_data(self, frames):
"""
Prepare the input of model
"""
data_frames = []
for frame in frames:
#frame H x W x C
frame = frame.swapaxes(0, 1) # swap width and height to form format W x H x C
if len(frame.shape) < 3:
frame =... | [
"Prepare",
"the",
"input",
"of",
"model"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/preprocess_data.py#L183-L200 | [
"def",
"set_data",
"(",
"self",
",",
"frames",
")",
":",
"data_frames",
"=",
"[",
"]",
"for",
"frame",
"in",
"frames",
":",
"#frame H x W x C",
"frame",
"=",
"frame",
".",
"swapaxes",
"(",
"0",
",",
"1",
")",
"# swap width and height to form format W x H x C",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | BucketSTTIter.reset | Resets the iterator to the beginning of the data. | example/speech_recognition/stt_io_bucketingiter.py | def reset(self):
"""Resets the iterator to the beginning of the data."""
self.curr_idx = 0
random.shuffle(self.idx)
for buck in self.data:
np.random.shuffle(buck) | def reset(self):
"""Resets the iterator to the beginning of the data."""
self.curr_idx = 0
random.shuffle(self.idx)
for buck in self.data:
np.random.shuffle(buck) | [
"Resets",
"the",
"iterator",
"to",
"the",
"beginning",
"of",
"the",
"data",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_io_bucketingiter.py#L125-L130 | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"curr_idx",
"=",
"0",
"random",
".",
"shuffle",
"(",
"self",
".",
"idx",
")",
"for",
"buck",
"in",
"self",
".",
"data",
":",
"np",
".",
"random",
".",
"shuffle",
"(",
"buck",
")"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | BucketSTTIter.next | Returns the next batch of data. | example/speech_recognition/stt_io_bucketingiter.py | def next(self):
"""Returns the next batch of data."""
if self.curr_idx == len(self.idx):
raise StopIteration
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
audio_paths = []
texts = []
for duration, audio_path, text in self.data[i][j:j+self.batch_si... | def next(self):
"""Returns the next batch of data."""
if self.curr_idx == len(self.idx):
raise StopIteration
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
audio_paths = []
texts = []
for duration, audio_path, text in self.data[i][j:j+self.batch_si... | [
"Returns",
"the",
"next",
"batch",
"of",
"data",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_io_bucketingiter.py#L132-L165 | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"curr_idx",
"==",
"len",
"(",
"self",
".",
"idx",
")",
":",
"raise",
"StopIteration",
"i",
",",
"j",
"=",
"self",
".",
"idx",
"[",
"self",
".",
"curr_idx",
"]",
"self",
".",
"curr_idx",
"+=... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | subtract_imagenet_mean_preprocess_batch | Subtract ImageNet mean pixel-wise from a BGR image. | example/gluon/style_transfer/utils.py | def subtract_imagenet_mean_preprocess_batch(batch):
"""Subtract ImageNet mean pixel-wise from a BGR image."""
batch = F.swapaxes(batch,0, 1)
(r, g, b) = F.split(batch, num_outputs=3, axis=0)
r = r - 123.680
g = g - 116.779
b = b - 103.939
batch = F.concat(b, g, r, dim=0)
batch = F.swapax... | def subtract_imagenet_mean_preprocess_batch(batch):
"""Subtract ImageNet mean pixel-wise from a BGR image."""
batch = F.swapaxes(batch,0, 1)
(r, g, b) = F.split(batch, num_outputs=3, axis=0)
r = r - 123.680
g = g - 116.779
b = b - 103.939
batch = F.concat(b, g, r, dim=0)
batch = F.swapax... | [
"Subtract",
"ImageNet",
"mean",
"pixel",
"-",
"wise",
"from",
"a",
"BGR",
"image",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/style_transfer/utils.py#L69-L78 | [
"def",
"subtract_imagenet_mean_preprocess_batch",
"(",
"batch",
")",
":",
"batch",
"=",
"F",
".",
"swapaxes",
"(",
"batch",
",",
"0",
",",
"1",
")",
"(",
"r",
",",
"g",
",",
"b",
")",
"=",
"F",
".",
"split",
"(",
"batch",
",",
"num_outputs",
"=",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | imagenet_clamp_batch | Not necessary in practice | example/gluon/style_transfer/utils.py | def imagenet_clamp_batch(batch, low, high):
""" Not necessary in practice """
F.clip(batch[:,0,:,:],low-123.680, high-123.680)
F.clip(batch[:,1,:,:],low-116.779, high-116.779)
F.clip(batch[:,2,:,:],low-103.939, high-103.939) | def imagenet_clamp_batch(batch, low, high):
""" Not necessary in practice """
F.clip(batch[:,0,:,:],low-123.680, high-123.680)
F.clip(batch[:,1,:,:],low-116.779, high-116.779)
F.clip(batch[:,2,:,:],low-103.939, high-103.939) | [
"Not",
"necessary",
"in",
"practice"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/style_transfer/utils.py#L95-L99 | [
"def",
"imagenet_clamp_batch",
"(",
"batch",
",",
"low",
",",
"high",
")",
":",
"F",
".",
"clip",
"(",
"batch",
"[",
":",
",",
"0",
",",
":",
",",
":",
"]",
",",
"low",
"-",
"123.680",
",",
"high",
"-",
"123.680",
")",
"F",
".",
"clip",
"(",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | create_network | Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization | example/svrg_module/api_usage_example/example_inference.py | def create_network(batch_size, update_freq):
"""Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization
"""
head = '%(asctime)-15s %(message)s'
logging.basicConfig(le... | def create_network(batch_size, update_freq):
"""Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization
"""
head = '%(asctime)-15s %(message)s'
logging.basicConfig(le... | [
"Create",
"a",
"linear",
"regression",
"network",
"for",
"performing",
"SVRG",
"optimization",
".",
":",
"return",
":",
"an",
"instance",
"of",
"mx",
".",
"io",
".",
"NDArrayIter",
":",
"return",
":",
"an",
"instance",
"of",
"mx",
".",
"mod",
".",
"svrgm... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/svrg_module/api_usage_example/example_inference.py#L64-L91 | [
"def",
"create_network",
"(",
"batch_size",
",",
"update_freq",
")",
":",
"head",
"=",
"'%(asctime)-15s %(message)s'",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"head",
")",
"data",
"=",
"np",
".",
"random"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | evaluate_accuracy | Function to evaluate accuracy of any data iterator passed to it as an argument | example/gluon/audio/urban_sounds/train.py | def evaluate_accuracy(data_iterator, net):
"""Function to evaluate accuracy of any data iterator passed to it as an argument"""
acc = mx.metric.Accuracy()
for data, label in data_iterator:
output = net(data)
predictions = nd.argmax(output, axis=1)
predictions = predictions.reshape((-... | def evaluate_accuracy(data_iterator, net):
"""Function to evaluate accuracy of any data iterator passed to it as an argument"""
acc = mx.metric.Accuracy()
for data, label in data_iterator:
output = net(data)
predictions = nd.argmax(output, axis=1)
predictions = predictions.reshape((-... | [
"Function",
"to",
"evaluate",
"accuracy",
"of",
"any",
"data",
"iterator",
"passed",
"to",
"it",
"as",
"an",
"argument"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/audio/urban_sounds/train.py#L29-L37 | [
"def",
"evaluate_accuracy",
"(",
"data_iterator",
",",
"net",
")",
":",
"acc",
"=",
"mx",
".",
"metric",
".",
"Accuracy",
"(",
")",
"for",
"data",
",",
"label",
"in",
"data_iterator",
":",
"output",
"=",
"net",
"(",
"data",
")",
"predictions",
"=",
"nd... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | train | Function responsible for running the training the model. | example/gluon/audio/urban_sounds/train.py | def train(train_dir=None, train_csv=None, epochs=30, batch_size=32):
"""Function responsible for running the training the model."""
if not train_dir or not os.path.exists(train_dir) or not train_csv:
warnings.warn("No train directory could be found ")
return
# Make a dataset from the local ... | def train(train_dir=None, train_csv=None, epochs=30, batch_size=32):
"""Function responsible for running the training the model."""
if not train_dir or not os.path.exists(train_dir) or not train_csv:
warnings.warn("No train directory could be found ")
return
# Make a dataset from the local ... | [
"Function",
"responsible",
"for",
"running",
"the",
"training",
"the",
"model",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/audio/urban_sounds/train.py#L40-L117 | [
"def",
"train",
"(",
"train_dir",
"=",
"None",
",",
"train_csv",
"=",
"None",
",",
"epochs",
"=",
"30",
",",
"batch_size",
"=",
"32",
")",
":",
"if",
"not",
"train_dir",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"train_dir",
")",
"or",
"n... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | set_bulk_size | Set size limit on bulk execution.
Bulk execution bundles many operators to run together.
This can improve performance when running a lot of small
operators sequentially.
Parameters
----------
size : int
Maximum number of operators that can be bundled in a bulk.
Returns
-------... | python/mxnet/engine.py | def set_bulk_size(size):
"""Set size limit on bulk execution.
Bulk execution bundles many operators to run together.
This can improve performance when running a lot of small
operators sequentially.
Parameters
----------
size : int
Maximum number of operators that can be bundled in ... | def set_bulk_size(size):
"""Set size limit on bulk execution.
Bulk execution bundles many operators to run together.
This can improve performance when running a lot of small
operators sequentially.
Parameters
----------
size : int
Maximum number of operators that can be bundled in ... | [
"Set",
"size",
"limit",
"on",
"bulk",
"execution",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/engine.py#L26-L46 | [
"def",
"set_bulk_size",
"(",
"size",
")",
":",
"prev",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXEngineSetBulkSize",
"(",
"ctypes",
".",
"c_int",
"(",
"size",
")",
",",
"ctypes",
".",
"byref",
"(",
"prev",
")",
")",
")... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | applyLM | calculate LM score of child beam by taking score from parent beam and bigram probability of last two chars | example/gluon/lipnet/BeamSearch.py | def applyLM(parentBeam, childBeam, classes, lm):
"""
calculate LM score of child beam by taking score from parent beam and bigram probability of last two chars
"""
if lm and not childBeam.lmApplied:
c1 = classes[parentBeam.labeling[-1] if parentBeam.labeling else classes.index(' ')] # first char... | def applyLM(parentBeam, childBeam, classes, lm):
"""
calculate LM score of child beam by taking score from parent beam and bigram probability of last two chars
"""
if lm and not childBeam.lmApplied:
c1 = classes[parentBeam.labeling[-1] if parentBeam.labeling else classes.index(' ')] # first char... | [
"calculate",
"LM",
"score",
"of",
"child",
"beam",
"by",
"taking",
"score",
"from",
"parent",
"beam",
"and",
"bigram",
"probability",
"of",
"last",
"two",
"chars"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/BeamSearch.py#L64-L74 | [
"def",
"applyLM",
"(",
"parentBeam",
",",
"childBeam",
",",
"classes",
",",
"lm",
")",
":",
"if",
"lm",
"and",
"not",
"childBeam",
".",
"lmApplied",
":",
"c1",
"=",
"classes",
"[",
"parentBeam",
".",
"labeling",
"[",
"-",
"1",
"]",
"if",
"parentBeam",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | addBeam | add beam if it does not yet exist | example/gluon/lipnet/BeamSearch.py | def addBeam(beamState, labeling):
"""
add beam if it does not yet exist
"""
if labeling not in beamState.entries:
beamState.entries[labeling] = BeamEntry() | def addBeam(beamState, labeling):
"""
add beam if it does not yet exist
"""
if labeling not in beamState.entries:
beamState.entries[labeling] = BeamEntry() | [
"add",
"beam",
"if",
"it",
"does",
"not",
"yet",
"exist"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/BeamSearch.py#L76-L81 | [
"def",
"addBeam",
"(",
"beamState",
",",
"labeling",
")",
":",
"if",
"labeling",
"not",
"in",
"beamState",
".",
"entries",
":",
"beamState",
".",
"entries",
"[",
"labeling",
"]",
"=",
"BeamEntry",
"(",
")"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | ctcBeamSearch | beam search as described by the paper of Hwang et al. and the paper of Graves et al. | example/gluon/lipnet/BeamSearch.py | def ctcBeamSearch(mat, classes, lm, k, beamWidth):
"""
beam search as described by the paper of Hwang et al. and the paper of Graves et al.
"""
blankIdx = len(classes)
maxT, maxC = mat.shape
# initialise beam state
last = BeamState()
labeling = ()
last.entries[labeling] = BeamEntry... | def ctcBeamSearch(mat, classes, lm, k, beamWidth):
"""
beam search as described by the paper of Hwang et al. and the paper of Graves et al.
"""
blankIdx = len(classes)
maxT, maxC = mat.shape
# initialise beam state
last = BeamState()
labeling = ()
last.entries[labeling] = BeamEntry... | [
"beam",
"search",
"as",
"described",
"by",
"the",
"paper",
"of",
"Hwang",
"et",
"al",
".",
"and",
"the",
"paper",
"of",
"Graves",
"et",
"al",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/BeamSearch.py#L83-L170 | [
"def",
"ctcBeamSearch",
"(",
"mat",
",",
"classes",
",",
"lm",
",",
"k",
",",
"beamWidth",
")",
":",
"blankIdx",
"=",
"len",
"(",
"classes",
")",
"maxT",
",",
"maxC",
"=",
"mat",
".",
"shape",
"# initialise beam state",
"last",
"=",
"BeamState",
"(",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | BeamState.norm | length-normalise LM score | example/gluon/lipnet/BeamSearch.py | def norm(self):
"""
length-normalise LM score
"""
for (k, _) in self.entries.items():
labelingLen = len(self.entries[k].labeling)
self.entries[k].prText = self.entries[k].prText ** (1.0 / (labelingLen if labelingLen else 1.0)) | def norm(self):
"""
length-normalise LM score
"""
for (k, _) in self.entries.items():
labelingLen = len(self.entries[k].labeling)
self.entries[k].prText = self.entries[k].prText ** (1.0 / (labelingLen if labelingLen else 1.0)) | [
"length",
"-",
"normalise",
"LM",
"score"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/BeamSearch.py#L48-L54 | [
"def",
"norm",
"(",
"self",
")",
":",
"for",
"(",
"k",
",",
"_",
")",
"in",
"self",
".",
"entries",
".",
"items",
"(",
")",
":",
"labelingLen",
"=",
"len",
"(",
"self",
".",
"entries",
"[",
"k",
"]",
".",
"labeling",
")",
"self",
".",
"entries"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | BeamState.sort | return beam-labelings, sorted by probability | example/gluon/lipnet/BeamSearch.py | def sort(self):
"""
return beam-labelings, sorted by probability
"""
beams = [v for (_, v) in self.entries.items()]
sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText)
return [x.labeling for x in sortedBeams] | def sort(self):
"""
return beam-labelings, sorted by probability
"""
beams = [v for (_, v) in self.entries.items()]
sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText)
return [x.labeling for x in sortedBeams] | [
"return",
"beam",
"-",
"labelings",
"sorted",
"by",
"probability"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/BeamSearch.py#L56-L62 | [
"def",
"sort",
"(",
"self",
")",
":",
"beams",
"=",
"[",
"v",
"for",
"(",
"_",
",",
"v",
")",
"in",
"self",
".",
"entries",
".",
"items",
"(",
")",
"]",
"sortedBeams",
"=",
"sorted",
"(",
"beams",
",",
"reverse",
"=",
"True",
",",
"key",
"=",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_loc | the localisation network in lenet-stn, it will increase acc about more than 1%,
when num-epoch >=15 | example/image-classification/symbols/lenet.py | def get_loc(data, attr={'lr_mult':'0.01'}):
"""
the localisation network in lenet-stn, it will increase acc about more than 1%,
when num-epoch >=15
"""
loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2))
loc = mx.symbol.Activation(data = loc, act_type='relu')
l... | def get_loc(data, attr={'lr_mult':'0.01'}):
"""
the localisation network in lenet-stn, it will increase acc about more than 1%,
when num-epoch >=15
"""
loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2))
loc = mx.symbol.Activation(data = loc, act_type='relu')
l... | [
"the",
"localisation",
"network",
"in",
"lenet",
"-",
"stn",
"it",
"will",
"increase",
"acc",
"about",
"more",
"than",
"1%",
"when",
"num",
"-",
"epoch",
">",
"=",
"15"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/image-classification/symbols/lenet.py#L25-L38 | [
"def",
"get_loc",
"(",
"data",
",",
"attr",
"=",
"{",
"'lr_mult'",
":",
"'0.01'",
"}",
")",
":",
"loc",
"=",
"mx",
".",
"symbol",
".",
"Convolution",
"(",
"data",
"=",
"data",
",",
"num_filter",
"=",
"30",
",",
"kernel",
"=",
"(",
"5",
",",
"5",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_detector | wrapper for initialize a detector
Parameters:
----------
net : str
test network name
prefix : str
load model prefix
epoch : int
load model epoch
data_shape : int
resize image shape
mean_pixels : tuple (float, float, float)
mean pixel values (R, G, B)
... | example/ssd/demo.py | def get_detector(net, prefix, epoch, data_shape, mean_pixels, ctx, num_class,
nms_thresh=0.5, force_nms=True, nms_topk=400):
"""
wrapper for initialize a detector
Parameters:
----------
net : str
test network name
prefix : str
load model prefix
epoch : int
... | def get_detector(net, prefix, epoch, data_shape, mean_pixels, ctx, num_class,
nms_thresh=0.5, force_nms=True, nms_topk=400):
"""
wrapper for initialize a detector
Parameters:
----------
net : str
test network name
prefix : str
load model prefix
epoch : int
... | [
"wrapper",
"for",
"initialize",
"a",
"detector"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/demo.py#L32-L64 | [
"def",
"get_detector",
"(",
"net",
",",
"prefix",
",",
"epoch",
",",
"data_shape",
",",
"mean_pixels",
",",
"ctx",
",",
"num_class",
",",
"nms_thresh",
"=",
"0.5",
",",
"force_nms",
"=",
"True",
",",
"nms_topk",
"=",
"400",
")",
":",
"if",
"net",
"is",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | parse_class_names | parse # classes and class_names if applicable | example/ssd/demo.py | def parse_class_names(class_names):
""" parse # classes and class_names if applicable """
if len(class_names) > 0:
if os.path.isfile(class_names):
# try to open it to read class names
with open(class_names, 'r') as f:
class_names = [l.strip() for l in f.readlines(... | def parse_class_names(class_names):
""" parse # classes and class_names if applicable """
if len(class_names) > 0:
if os.path.isfile(class_names):
# try to open it to read class names
with open(class_names, 'r') as f:
class_names = [l.strip() for l in f.readlines(... | [
"parse",
"#",
"classes",
"and",
"class_names",
"if",
"applicable"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/demo.py#L117-L130 | [
"def",
"parse_class_names",
"(",
"class_names",
")",
":",
"if",
"len",
"(",
"class_names",
")",
">",
"0",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"class_names",
")",
":",
"# try to open it to read class names",
"with",
"open",
"(",
"class_names",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | parse_data_shape | Parse string to tuple or int | example/ssd/demo.py | def parse_data_shape(data_shape_str):
"""Parse string to tuple or int"""
ds = data_shape_str.strip().split(',')
if len(ds) == 1:
data_shape = (int(ds[0]), int(ds[0]))
elif len(ds) == 2:
data_shape = (int(ds[0]), int(ds[1]))
else:
raise ValueError("Unexpected data_shape: %s", ... | def parse_data_shape(data_shape_str):
"""Parse string to tuple or int"""
ds = data_shape_str.strip().split(',')
if len(ds) == 1:
data_shape = (int(ds[0]), int(ds[0]))
elif len(ds) == 2:
data_shape = (int(ds[0]), int(ds[1]))
else:
raise ValueError("Unexpected data_shape: %s", ... | [
"Parse",
"string",
"to",
"tuple",
"or",
"int"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/demo.py#L141-L150 | [
"def",
"parse_data_shape",
"(",
"data_shape_str",
")",
":",
"ds",
"=",
"data_shape_str",
".",
"strip",
"(",
")",
".",
"split",
"(",
"','",
")",
"if",
"len",
"(",
"ds",
")",
"==",
"1",
":",
"data_shape",
"=",
"(",
"int",
"(",
"ds",
"[",
"0",
"]",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_lenet | A lenet style net, takes difference of each frame as input. | example/kaggle-ndsb2/Train.py | def get_lenet():
""" A lenet style net, takes difference of each frame as input.
"""
source = mx.sym.Variable("data")
source = (source - 128) * (1.0/128)
frames = mx.sym.SliceChannel(source, num_outputs=30)
diffs = [frames[i+1] - frames[i] for i in range(29)]
source = mx.sym.Concat(*diffs)
... | def get_lenet():
""" A lenet style net, takes difference of each frame as input.
"""
source = mx.sym.Variable("data")
source = (source - 128) * (1.0/128)
frames = mx.sym.SliceChannel(source, num_outputs=30)
diffs = [frames[i+1] - frames[i] for i in range(29)]
source = mx.sym.Concat(*diffs)
... | [
"A",
"lenet",
"style",
"net",
"takes",
"difference",
"of",
"each",
"frame",
"as",
"input",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Train.py#L33-L55 | [
"def",
"get_lenet",
"(",
")",
":",
"source",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"\"data\"",
")",
"source",
"=",
"(",
"source",
"-",
"128",
")",
"*",
"(",
"1.0",
"/",
"128",
")",
"frames",
"=",
"mx",
".",
"sym",
".",
"SliceChannel",
"(",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | CRPS | Custom evaluation metric on CRPS. | example/kaggle-ndsb2/Train.py | def CRPS(label, pred):
""" Custom evaluation metric on CRPS.
"""
for i in range(pred.shape[0]):
for j in range(pred.shape[1] - 1):
if pred[i, j] > pred[i, j + 1]:
pred[i, j + 1] = pred[i, j]
return np.sum(np.square(label - pred)) / label.size | def CRPS(label, pred):
""" Custom evaluation metric on CRPS.
"""
for i in range(pred.shape[0]):
for j in range(pred.shape[1] - 1):
if pred[i, j] > pred[i, j + 1]:
pred[i, j + 1] = pred[i, j]
return np.sum(np.square(label - pred)) / label.size | [
"Custom",
"evaluation",
"metric",
"on",
"CRPS",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Train.py#L57-L64 | [
"def",
"CRPS",
"(",
"label",
",",
"pred",
")",
":",
"for",
"i",
"in",
"range",
"(",
"pred",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"pred",
".",
"shape",
"[",
"1",
"]",
"-",
"1",
")",
":",
"if",
"pred",
"[",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | encode_label | Run encoding to encode the label into the CDF target. | example/kaggle-ndsb2/Train.py | def encode_label(label_data):
"""Run encoding to encode the label into the CDF target.
"""
systole = label_data[:, 1]
diastole = label_data[:, 2]
systole_encode = np.array([
(x < np.arange(600)) for x in systole
], dtype=np.uint8)
diastole_encode = np.array([
(x <... | def encode_label(label_data):
"""Run encoding to encode the label into the CDF target.
"""
systole = label_data[:, 1]
diastole = label_data[:, 2]
systole_encode = np.array([
(x < np.arange(600)) for x in systole
], dtype=np.uint8)
diastole_encode = np.array([
(x <... | [
"Run",
"encoding",
"to",
"encode",
"the",
"label",
"into",
"the",
"CDF",
"target",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Train.py#L69-L80 | [
"def",
"encode_label",
"(",
"label_data",
")",
":",
"systole",
"=",
"label_data",
"[",
":",
",",
"1",
"]",
"diastole",
"=",
"label_data",
"[",
":",
",",
"2",
"]",
"systole_encode",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"x",
"<",
"np",
".",
"arang... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | coco._load_annotation | coco ann: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id']
iscrowd:
crowd instances are handled by marking their overlaps with all categories to -1
and later excluded in training
bbox:
[x1, y1, w, h]
:param index: coco image ... | example/rcnn/symimdb/coco.py | def _load_annotation(self, _coco, coco_ind_to_class_ind, index):
"""
coco ann: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id']
iscrowd:
crowd instances are handled by marking their overlaps with all categories to -1
and later excluded i... | def _load_annotation(self, _coco, coco_ind_to_class_ind, index):
"""
coco ann: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id']
iscrowd:
crowd instances are handled by marking their overlaps with all categories to -1
and later excluded i... | [
"coco",
"ann",
":",
"[",
"u",
"segmentation",
"u",
"area",
"u",
"iscrowd",
"u",
"image_id",
"u",
"bbox",
"u",
"category_id",
"u",
"id",
"]",
"iscrowd",
":",
"crowd",
"instances",
"are",
"handled",
"by",
"marking",
"their",
"overlaps",
"with",
"all",
"cat... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symimdb/coco.py#L78-L125 | [
"def",
"_load_annotation",
"(",
"self",
",",
"_coco",
",",
"coco_ind_to_class_ind",
",",
"index",
")",
":",
"im_ann",
"=",
"_coco",
".",
"loadImgs",
"(",
"index",
")",
"[",
"0",
"]",
"filename",
"=",
"self",
".",
"_image_file_tmpl",
".",
"format",
"(",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | coco._write_coco_results | example results
[{"image_id": 42,
"category_id": 18,
"bbox": [258.15,41.29,348.26,243.78],
"score": 0.236}, ...] | example/rcnn/symimdb/coco.py | def _write_coco_results(self, _coco, detections):
""" example results
[{"image_id": 42,
"category_id": 18,
"bbox": [258.15,41.29,348.26,243.78],
"score": 0.236}, ...]
"""
cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())]
class_to_coco... | def _write_coco_results(self, _coco, detections):
""" example results
[{"image_id": 42,
"category_id": 18,
"bbox": [258.15,41.29,348.26,243.78],
"score": 0.236}, ...]
"""
cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())]
class_to_coco... | [
"example",
"results",
"[",
"{",
"image_id",
":",
"42",
"category_id",
":",
"18",
"bbox",
":",
"[",
"258",
".",
"15",
"41",
".",
"29",
"348",
".",
"26",
"243",
".",
"78",
"]",
"score",
":",
"0",
".",
"236",
"}",
"...",
"]"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symimdb/coco.py#L132-L150 | [
"def",
"_write_coco_results",
"(",
"self",
",",
"_coco",
",",
"detections",
")",
":",
"cats",
"=",
"[",
"cat",
"[",
"'name'",
"]",
"for",
"cat",
"in",
"_coco",
".",
"loadCats",
"(",
"_coco",
".",
"getCatIds",
"(",
")",
")",
"]",
"class_to_coco_ind",
"=... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | rand_zipfian | Draw random samples from an approximately log-uniform or Zipfian distribution.
This operation randomly samples *num_sampled* candidates the range of integers [0, range_max).
The elements of sampled_candidates are drawn with replacement from the base distribution.
The base distribution for this operator is... | python/mxnet/ndarray/contrib.py | def rand_zipfian(true_classes, num_sampled, range_max, ctx=None):
"""Draw random samples from an approximately log-uniform or Zipfian distribution.
This operation randomly samples *num_sampled* candidates the range of integers [0, range_max).
The elements of sampled_candidates are drawn with replacement fr... | def rand_zipfian(true_classes, num_sampled, range_max, ctx=None):
"""Draw random samples from an approximately log-uniform or Zipfian distribution.
This operation randomly samples *num_sampled* candidates the range of integers [0, range_max).
The elements of sampled_candidates are drawn with replacement fr... | [
"Draw",
"random",
"samples",
"from",
"an",
"approximately",
"log",
"-",
"uniform",
"or",
"Zipfian",
"distribution",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/contrib.py#L36-L100 | [
"def",
"rand_zipfian",
"(",
"true_classes",
",",
"num_sampled",
",",
"range_max",
",",
"ctx",
"=",
"None",
")",
":",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"current_context",
"(",
")",
"log_range",
"=",
"math",
".",
"log",
"(",
"range_max",
"+",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | foreach | Run a for loop with user-defined computation over NDArrays on dimension 0.
This operator simulates a for loop and body has the computation for an iteration
of the for loop. It runs the computation in body on each slice from the input
NDArrays.
body takes two arguments as input and outputs a tuple of t... | python/mxnet/ndarray/contrib.py | def foreach(body, data, init_states):
"""Run a for loop with user-defined computation over NDArrays on dimension 0.
This operator simulates a for loop and body has the computation for an iteration
of the for loop. It runs the computation in body on each slice from the input
NDArrays.
body takes tw... | def foreach(body, data, init_states):
"""Run a for loop with user-defined computation over NDArrays on dimension 0.
This operator simulates a for loop and body has the computation for an iteration
of the for loop. It runs the computation in body on each slice from the input
NDArrays.
body takes tw... | [
"Run",
"a",
"for",
"loop",
"with",
"user",
"-",
"defined",
"computation",
"over",
"NDArrays",
"on",
"dimension",
"0",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/contrib.py#L136-L230 | [
"def",
"foreach",
"(",
"body",
",",
"data",
",",
"init_states",
")",
":",
"def",
"check_input",
"(",
"inputs",
",",
"in_type",
",",
"msg",
")",
":",
"is_NDArray_or_list",
"=",
"True",
"if",
"isinstance",
"(",
"inputs",
",",
"list",
")",
":",
"for",
"i"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | while_loop | Run a while loop with user-defined computation and loop condition.
This operator simulates a while loop which iterately does customized computation
as long as the condition is satisfied.
`loop_vars` is a list of NDArrays on which the computation uses.
`cond` is a user-defined function, used as the lo... | python/mxnet/ndarray/contrib.py | def while_loop(cond, func, loop_vars, max_iterations=None):
"""Run a while loop with user-defined computation and loop condition.
This operator simulates a while loop which iterately does customized computation
as long as the condition is satisfied.
`loop_vars` is a list of NDArrays on which the compu... | def while_loop(cond, func, loop_vars, max_iterations=None):
"""Run a while loop with user-defined computation and loop condition.
This operator simulates a while loop which iterately does customized computation
as long as the condition is satisfied.
`loop_vars` is a list of NDArrays on which the compu... | [
"Run",
"a",
"while",
"loop",
"with",
"user",
"-",
"defined",
"computation",
"and",
"loop",
"condition",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/contrib.py#L232-L398 | [
"def",
"while_loop",
"(",
"cond",
",",
"func",
",",
"loop_vars",
",",
"max_iterations",
"=",
"None",
")",
":",
"def",
"_to_python_scalar",
"(",
"inputs",
",",
"type_",
",",
"name",
")",
":",
"\"\"\"Converts \"inputs\", possibly typed mxnet NDArray, a numpy ndarray, ot... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | cond | Run an if-then-else using user-defined condition and computation
This operator simulates a if-like branch which chooses to do one of
the two customized computations according to the specified condition.
`pred` is a scalar MXNet NDArray,
indicating which branch of computation should be used.
`then... | python/mxnet/ndarray/contrib.py | def cond(pred, then_func, else_func):
"""Run an if-then-else using user-defined condition and computation
This operator simulates a if-like branch which chooses to do one of
the two customized computations according to the specified condition.
`pred` is a scalar MXNet NDArray,
indicating which bra... | def cond(pred, then_func, else_func):
"""Run an if-then-else using user-defined condition and computation
This operator simulates a if-like branch which chooses to do one of
the two customized computations according to the specified condition.
`pred` is a scalar MXNet NDArray,
indicating which bra... | [
"Run",
"an",
"if",
"-",
"then",
"-",
"else",
"using",
"user",
"-",
"defined",
"condition",
"and",
"computation"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/contrib.py#L400-L464 | [
"def",
"cond",
"(",
"pred",
",",
"then_func",
",",
"else_func",
")",
":",
"def",
"_to_python_scalar",
"(",
"inputs",
",",
"type_",
",",
"name",
")",
":",
"\"\"\"Converts \"inputs\", possibly typed mxnet NDArray, a numpy ndarray, other python types,\n to the given type\... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | isfinite | Performs an element-wise check to determine if the NDArray contains an infinite element
or not.
Parameters
----------
input : NDArray
An N-D NDArray.
Returns
-------
output: NDArray
The output NDarray, with same shape as input, where 1 indicates the array element is
... | python/mxnet/ndarray/contrib.py | def isfinite(data):
"""Performs an element-wise check to determine if the NDArray contains an infinite element
or not.
Parameters
----------
input : NDArray
An N-D NDArray.
Returns
-------
output: NDArray
The output NDarray, with same shape as input, where 1 indicates ... | def isfinite(data):
"""Performs an element-wise check to determine if the NDArray contains an infinite element
or not.
Parameters
----------
input : NDArray
An N-D NDArray.
Returns
-------
output: NDArray
The output NDarray, with same shape as input, where 1 indicates ... | [
"Performs",
"an",
"element",
"-",
"wise",
"check",
"to",
"determine",
"if",
"the",
"NDArray",
"contains",
"an",
"infinite",
"element",
"or",
"not",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/contrib.py#L492-L519 | [
"def",
"isfinite",
"(",
"data",
")",
":",
"is_data_not_nan",
"=",
"data",
"==",
"data",
"is_data_not_infinite",
"=",
"data",
".",
"abs",
"(",
")",
"!=",
"np",
".",
"inf",
"return",
"ndarray",
".",
"logical_and",
"(",
"is_data_not_infinite",
",",
"is_data_not... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | vanilla_lstm | LSTM Cell symbol | example/speech_recognition/stt_layer_lstm.py | def vanilla_lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, is_batchnorm=False, gamma=None, beta=None, name=None):
"""LSTM Cell symbol"""
i2h = mx.sym.FullyConnected(data=indata,
weight=param.i2h_weight,
bias=param.i2h_bias,
... | def vanilla_lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, is_batchnorm=False, gamma=None, beta=None, name=None):
"""LSTM Cell symbol"""
i2h = mx.sym.FullyConnected(data=indata,
weight=param.i2h_weight,
bias=param.i2h_bias,
... | [
"LSTM",
"Cell",
"symbol"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_layer_lstm.py#L36-L62 | [
"def",
"vanilla_lstm",
"(",
"num_hidden",
",",
"indata",
",",
"prev_state",
",",
"param",
",",
"seqidx",
",",
"layeridx",
",",
"is_batchnorm",
"=",
"False",
",",
"gamma",
"=",
"None",
",",
"beta",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"i2h",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | lstm | LSTM Cell symbol | example/speech_recognition/stt_layer_lstm.py | def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., num_hidden_proj=0, is_batchnorm=False,
gamma=None, beta=None, name=None):
"""LSTM Cell symbol"""
# dropout input
if dropout > 0.:
indata = mx.sym.Dropout(data=indata, p=dropout)
i2h = mx.sym.FullyConnected(da... | def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., num_hidden_proj=0, is_batchnorm=False,
gamma=None, beta=None, name=None):
"""LSTM Cell symbol"""
# dropout input
if dropout > 0.:
indata = mx.sym.Dropout(data=indata, p=dropout)
i2h = mx.sym.FullyConnected(da... | [
"LSTM",
"Cell",
"symbol"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_layer_lstm.py#L65-L118 | [
"def",
"lstm",
"(",
"num_hidden",
",",
"indata",
",",
"prev_state",
",",
"param",
",",
"seqidx",
",",
"layeridx",
",",
"dropout",
"=",
"0.",
",",
"num_hidden_proj",
"=",
"0",
",",
"is_batchnorm",
"=",
"False",
",",
"gamma",
"=",
"None",
",",
"beta",
"=... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_image | read, resize, transform image, return im_tensor, im_info, gt_boxes
roi_rec should have keys: ["image", "boxes", "gt_classes", "flipped"]
0 --- x (width, second dim of im)
|
y (height, first dim of im) | example/rcnn/symdata/image.py | def get_image(roi_rec, short, max_size, mean, std):
"""
read, resize, transform image, return im_tensor, im_info, gt_boxes
roi_rec should have keys: ["image", "boxes", "gt_classes", "flipped"]
0 --- x (width, second dim of im)
|
y (height, first dim of im)
"""
im = imdecode(roi_rec['imag... | def get_image(roi_rec, short, max_size, mean, std):
"""
read, resize, transform image, return im_tensor, im_info, gt_boxes
roi_rec should have keys: ["image", "boxes", "gt_classes", "flipped"]
0 --- x (width, second dim of im)
|
y (height, first dim of im)
"""
im = imdecode(roi_rec['imag... | [
"read",
"resize",
"transform",
"image",
"return",
"im_tensor",
"im_info",
"gt_boxes",
"roi_rec",
"should",
"have",
"keys",
":",
"[",
"image",
"boxes",
"gt_classes",
"flipped",
"]",
"0",
"---",
"x",
"(",
"width",
"second",
"dim",
"of",
"im",
")",
"|",
"y",
... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/image.py#L22-L49 | [
"def",
"get_image",
"(",
"roi_rec",
",",
"short",
",",
"max_size",
",",
"mean",
",",
"std",
")",
":",
"im",
"=",
"imdecode",
"(",
"roi_rec",
"[",
"'image'",
"]",
")",
"if",
"roi_rec",
"[",
"\"flipped\"",
"]",
":",
"im",
"=",
"im",
"[",
":",
",",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | imdecode | Return BGR image read by opencv | example/rcnn/symdata/image.py | def imdecode(image_path):
"""Return BGR image read by opencv"""
import os
assert os.path.exists(image_path), image_path + ' not found'
im = cv2.imread(image_path)
return im | def imdecode(image_path):
"""Return BGR image read by opencv"""
import os
assert os.path.exists(image_path), image_path + ' not found'
im = cv2.imread(image_path)
return im | [
"Return",
"BGR",
"image",
"read",
"by",
"opencv"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/image.py#L52-L57 | [
"def",
"imdecode",
"(",
"image_path",
")",
":",
"import",
"os",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"image_path",
")",
",",
"image_path",
"+",
"' not found'",
"im",
"=",
"cv2",
".",
"imread",
"(",
"image_path",
")",
"return",
"im"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | resize | only resize input image to target size and return scale
:param im: BGR image input by opencv
:param short: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
:return: resized image (NDArray) and scale (float) | example/rcnn/symdata/image.py | def resize(im, short, max_size):
"""
only resize input image to target size and return scale
:param im: BGR image input by opencv
:param short: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
:return: resized image (NDArray) and scale (float)
"... | def resize(im, short, max_size):
"""
only resize input image to target size and return scale
:param im: BGR image input by opencv
:param short: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
:return: resized image (NDArray) and scale (float)
"... | [
"only",
"resize",
"input",
"image",
"to",
"target",
"size",
"and",
"return",
"scale",
":",
"param",
"im",
":",
"BGR",
"image",
"input",
"by",
"opencv",
":",
"param",
"short",
":",
"one",
"dimensional",
"size",
"(",
"the",
"short",
"side",
")",
":",
"pa... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/image.py#L60-L76 | [
"def",
"resize",
"(",
"im",
",",
"short",
",",
"max_size",
")",
":",
"im_shape",
"=",
"im",
".",
"shape",
"im_size_min",
"=",
"np",
".",
"min",
"(",
"im_shape",
"[",
"0",
":",
"2",
"]",
")",
"im_size_max",
"=",
"np",
".",
"max",
"(",
"im_shape",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | transform | transform into mxnet tensor,
subtract pixel size and transform to correct format
:param im: [height, width, channel] in BGR
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: [batch, channel, height, width] | example/rcnn/symdata/image.py | def transform(im, mean, std):
"""
transform into mxnet tensor,
subtract pixel size and transform to correct format
:param im: [height, width, channel] in BGR
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: [batch, channel, height, width]
"""
im_tensor = np.zero... | def transform(im, mean, std):
"""
transform into mxnet tensor,
subtract pixel size and transform to correct format
:param im: [height, width, channel] in BGR
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: [batch, channel, height, width]
"""
im_tensor = np.zero... | [
"transform",
"into",
"mxnet",
"tensor",
"subtract",
"pixel",
"size",
"and",
"transform",
"to",
"correct",
"format",
":",
"param",
"im",
":",
"[",
"height",
"width",
"channel",
"]",
"in",
"BGR",
":",
"param",
"mean",
":",
"[",
"RGB",
"pixel",
"mean",
"]",... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/image.py#L79-L91 | [
"def",
"transform",
"(",
"im",
",",
"mean",
",",
"std",
")",
":",
"im_tensor",
"=",
"np",
".",
"zeros",
"(",
"(",
"3",
",",
"im",
".",
"shape",
"[",
"0",
"]",
",",
"im",
".",
"shape",
"[",
"1",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | transform_inverse | transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: im [height, width, channel(RGB)] | example/rcnn/symdata/image.py | def transform_inverse(im_tensor, mean, std):
"""
transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: im [height, width, channel(RGB)]
... | def transform_inverse(im_tensor, mean, std):
"""
transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: im [height, width, channel(RGB)]
... | [
"transform",
"from",
"mxnet",
"im_tensor",
"to",
"ordinary",
"RGB",
"image",
"im_tensor",
"is",
"limited",
"to",
"one",
"image",
":",
"param",
"im_tensor",
":",
"[",
"batch",
"channel",
"height",
"width",
"]",
":",
"param",
"mean",
":",
"[",
"RGB",
"pixel"... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/image.py#L94-L107 | [
"def",
"transform_inverse",
"(",
"im_tensor",
",",
"mean",
",",
"std",
")",
":",
"assert",
"im_tensor",
".",
"shape",
"[",
"0",
"]",
"==",
"3",
"im",
"=",
"im_tensor",
".",
"transpose",
"(",
"(",
"1",
",",
"2",
",",
"0",
")",
")",
"im",
"=",
"im"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | tensor_vstack | vertically stack tensors by adding a new axis
expand dims if only 1 tensor
:param tensor_list: list of tensor to be stacked vertically
:param pad: label to pad with
:return: tensor with max shape | example/rcnn/symdata/image.py | def tensor_vstack(tensor_list, pad=0):
"""
vertically stack tensors by adding a new axis
expand dims if only 1 tensor
:param tensor_list: list of tensor to be stacked vertically
:param pad: label to pad with
:return: tensor with max shape
"""
if len(tensor_list) == 1:
return tens... | def tensor_vstack(tensor_list, pad=0):
"""
vertically stack tensors by adding a new axis
expand dims if only 1 tensor
:param tensor_list: list of tensor to be stacked vertically
:param pad: label to pad with
:return: tensor with max shape
"""
if len(tensor_list) == 1:
return tens... | [
"vertically",
"stack",
"tensors",
"by",
"adding",
"a",
"new",
"axis",
"expand",
"dims",
"if",
"only",
"1",
"tensor",
":",
"param",
"tensor_list",
":",
"list",
"of",
"tensor",
"to",
"be",
"stacked",
"vertically",
":",
"param",
"pad",
":",
"label",
"to",
"... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/image.py#L110-L144 | [
"def",
"tensor_vstack",
"(",
"tensor_list",
",",
"pad",
"=",
"0",
")",
":",
"if",
"len",
"(",
"tensor_list",
")",
"==",
"1",
":",
"return",
"tensor_list",
"[",
"0",
"]",
"[",
"np",
".",
"newaxis",
",",
":",
"]",
"ndim",
"=",
"len",
"(",
"tensor_lis... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_distance_matrix | Get distance matrix given a matrix. Used in testing. | example/gluon/embedding_learning/train.py | def get_distance_matrix(x):
"""Get distance matrix given a matrix. Used in testing."""
square = nd.sum(x ** 2.0, axis=1, keepdims=True)
distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))
return nd.sqrt(distance_square) | def get_distance_matrix(x):
"""Get distance matrix given a matrix. Used in testing."""
square = nd.sum(x ** 2.0, axis=1, keepdims=True)
distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))
return nd.sqrt(distance_square) | [
"Get",
"distance",
"matrix",
"given",
"a",
"matrix",
".",
"Used",
"in",
"testing",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L116-L120 | [
"def",
"get_distance_matrix",
"(",
"x",
")",
":",
"square",
"=",
"nd",
".",
"sum",
"(",
"x",
"**",
"2.0",
",",
"axis",
"=",
"1",
",",
"keepdims",
"=",
"True",
")",
"distance_square",
"=",
"square",
"+",
"square",
".",
"transpose",
"(",
")",
"-",
"(... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | evaluate_emb | Evaluate embeddings based on Recall@k. | example/gluon/embedding_learning/train.py | def evaluate_emb(emb, labels):
"""Evaluate embeddings based on Recall@k."""
d_mat = get_distance_matrix(emb)
d_mat = d_mat.asnumpy()
labels = labels.asnumpy()
names = []
accs = []
for k in [1, 2, 4, 8, 16]:
names.append('Recall@%d' % k)
correct, cnt = 0.0, 0.0
for i ... | def evaluate_emb(emb, labels):
"""Evaluate embeddings based on Recall@k."""
d_mat = get_distance_matrix(emb)
d_mat = d_mat.asnumpy()
labels = labels.asnumpy()
names = []
accs = []
for k in [1, 2, 4, 8, 16]:
names.append('Recall@%d' % k)
correct, cnt = 0.0, 0.0
for i ... | [
"Evaluate",
"embeddings",
"based",
"on",
"Recall"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L123-L141 | [
"def",
"evaluate_emb",
"(",
"emb",
",",
"labels",
")",
":",
"d_mat",
"=",
"get_distance_matrix",
"(",
"emb",
")",
"d_mat",
"=",
"d_mat",
".",
"asnumpy",
"(",
")",
"labels",
"=",
"labels",
".",
"asnumpy",
"(",
")",
"names",
"=",
"[",
"]",
"accs",
"=",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_lr | Get learning rate based on schedule. | example/gluon/embedding_learning/train.py | def get_lr(lr, epoch, steps, factor):
"""Get learning rate based on schedule."""
for s in steps:
if epoch >= s:
lr *= factor
return lr | def get_lr(lr, epoch, steps, factor):
"""Get learning rate based on schedule."""
for s in steps:
if epoch >= s:
lr *= factor
return lr | [
"Get",
"learning",
"rate",
"based",
"on",
"schedule",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L161-L166 | [
"def",
"get_lr",
"(",
"lr",
",",
"epoch",
",",
"steps",
",",
"factor",
")",
":",
"for",
"s",
"in",
"steps",
":",
"if",
"epoch",
">=",
"s",
":",
"lr",
"*=",
"factor",
"return",
"lr"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | train | Training function. | example/gluon/embedding_learning/train.py | def train(epochs, ctx):
"""Training function."""
if isinstance(ctx, mx.Context):
ctx = [ctx]
net.initialize(mx.init.Xavier(magnitude=2), ctx=ctx)
opt_options = {'learning_rate': opt.lr, 'wd': opt.wd}
if opt.optimizer == 'sgd':
opt_options['momentum'] = 0.9
if opt.optimizer == 'a... | def train(epochs, ctx):
"""Training function."""
if isinstance(ctx, mx.Context):
ctx = [ctx]
net.initialize(mx.init.Xavier(magnitude=2), ctx=ctx)
opt_options = {'learning_rate': opt.lr, 'wd': opt.wd}
if opt.optimizer == 'sgd':
opt_options['momentum'] = 0.9
if opt.optimizer == 'a... | [
"Training",
"function",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L169-L250 | [
"def",
"train",
"(",
"epochs",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"ctx",
",",
"mx",
".",
"Context",
")",
":",
"ctx",
"=",
"[",
"ctx",
"]",
"net",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
"magnitude",
"=",
"2",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _lstm_unroll_base | Returns symbol for LSTM model up to loss/softmax | example/ctc/lstm.py | def _lstm_unroll_base(num_lstm_layer, seq_len, num_hidden):
""" Returns symbol for LSTM model up to loss/softmax"""
param_cells = []
last_states = []
for i in range(num_lstm_layer):
param_cells.append(LSTMParam(i2h_weight=mx.sym.Variable("l%d_i2h_weight" % i),
... | def _lstm_unroll_base(num_lstm_layer, seq_len, num_hidden):
""" Returns symbol for LSTM model up to loss/softmax"""
param_cells = []
last_states = []
for i in range(num_lstm_layer):
param_cells.append(LSTMParam(i2h_weight=mx.sym.Variable("l%d_i2h_weight" % i),
... | [
"Returns",
"symbol",
"for",
"LSTM",
"model",
"up",
"to",
"loss",
"/",
"softmax"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L58-L93 | [
"def",
"_lstm_unroll_base",
"(",
"num_lstm_layer",
",",
"seq_len",
",",
"num_hidden",
")",
":",
"param_cells",
"=",
"[",
"]",
"last_states",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_lstm_layer",
")",
":",
"param_cells",
".",
"append",
"(",
"LSTM... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _add_warp_ctc_loss | Adds Symbol.contrib.ctc_loss on top of pred symbol and returns the resulting symbol | example/ctc/lstm.py | def _add_warp_ctc_loss(pred, seq_len, num_label, label):
""" Adds Symbol.contrib.ctc_loss on top of pred symbol and returns the resulting symbol """
label = mx.sym.Reshape(data=label, shape=(-1,))
label = mx.sym.Cast(data=label, dtype='int32')
return mx.sym.WarpCTC(data=pred, label=label, label_length=n... | def _add_warp_ctc_loss(pred, seq_len, num_label, label):
""" Adds Symbol.contrib.ctc_loss on top of pred symbol and returns the resulting symbol """
label = mx.sym.Reshape(data=label, shape=(-1,))
label = mx.sym.Cast(data=label, dtype='int32')
return mx.sym.WarpCTC(data=pred, label=label, label_length=n... | [
"Adds",
"Symbol",
".",
"contrib",
".",
"ctc_loss",
"on",
"top",
"of",
"pred",
"symbol",
"and",
"returns",
"the",
"resulting",
"symbol"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L96-L100 | [
"def",
"_add_warp_ctc_loss",
"(",
"pred",
",",
"seq_len",
",",
"num_label",
",",
"label",
")",
":",
"label",
"=",
"mx",
".",
"sym",
".",
"Reshape",
"(",
"data",
"=",
"label",
",",
"shape",
"=",
"(",
"-",
"1",
",",
")",
")",
"label",
"=",
"mx",
".... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _add_mxnet_ctc_loss | Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol | example/ctc/lstm.py | def _add_mxnet_ctc_loss(pred, seq_len, label):
""" Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol """
pred_ctc = mx.sym.Reshape(data=pred, shape=(-4, seq_len, -1, 0))
loss = mx.sym.contrib.ctc_loss(data=pred_ctc, label=label)
ctc_loss = mx.sym.MakeLoss(loss)
softmax_clas... | def _add_mxnet_ctc_loss(pred, seq_len, label):
""" Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol """
pred_ctc = mx.sym.Reshape(data=pred, shape=(-4, seq_len, -1, 0))
loss = mx.sym.contrib.ctc_loss(data=pred_ctc, label=label)
ctc_loss = mx.sym.MakeLoss(loss)
softmax_clas... | [
"Adds",
"Symbol",
".",
"WapCTC",
"on",
"top",
"of",
"pred",
"symbol",
"and",
"returns",
"the",
"resulting",
"symbol"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L103-L113 | [
"def",
"_add_mxnet_ctc_loss",
"(",
"pred",
",",
"seq_len",
",",
"label",
")",
":",
"pred_ctc",
"=",
"mx",
".",
"sym",
".",
"Reshape",
"(",
"data",
"=",
"pred",
",",
"shape",
"=",
"(",
"-",
"4",
",",
"seq_len",
",",
"-",
"1",
",",
"0",
")",
")",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _add_ctc_loss | Adds CTC loss on top of pred symbol and returns the resulting symbol | example/ctc/lstm.py | def _add_ctc_loss(pred, seq_len, num_label, loss_type):
""" Adds CTC loss on top of pred symbol and returns the resulting symbol """
label = mx.sym.Variable('label')
if loss_type == 'warpctc':
print("Using WarpCTC Loss")
sm = _add_warp_ctc_loss(pred, seq_len, num_label, label)
else:
... | def _add_ctc_loss(pred, seq_len, num_label, loss_type):
""" Adds CTC loss on top of pred symbol and returns the resulting symbol """
label = mx.sym.Variable('label')
if loss_type == 'warpctc':
print("Using WarpCTC Loss")
sm = _add_warp_ctc_loss(pred, seq_len, num_label, label)
else:
... | [
"Adds",
"CTC",
"loss",
"on",
"top",
"of",
"pred",
"symbol",
"and",
"returns",
"the",
"resulting",
"symbol"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L116-L126 | [
"def",
"_add_ctc_loss",
"(",
"pred",
",",
"seq_len",
",",
"num_label",
",",
"loss_type",
")",
":",
"label",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"'label'",
")",
"if",
"loss_type",
"==",
"'warpctc'",
":",
"print",
"(",
"\"Using WarpCTC Loss\"",
")",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | lstm_unroll | Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training
if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc'
Parameters
----------
num_lstm_layer: int
seq_len: int
num_hidden: int
num_label: int
loss_type: str
'ctc' or 'war... | example/ctc/lstm.py | def lstm_unroll(num_lstm_layer, seq_len, num_hidden, num_label, loss_type=None):
"""
Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training
if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc'
Parameters
----------
num_lstm_layer: int
... | def lstm_unroll(num_lstm_layer, seq_len, num_hidden, num_label, loss_type=None):
"""
Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training
if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc'
Parameters
----------
num_lstm_layer: int
... | [
"Creates",
"an",
"unrolled",
"LSTM",
"symbol",
"for",
"inference",
"if",
"loss_type",
"is",
"not",
"specified",
"and",
"for",
"training",
"if",
"loss_type",
"is",
"specified",
".",
"loss_type",
"must",
"be",
"one",
"of",
"ctc",
"or",
"warpctc"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L129-L155 | [
"def",
"lstm_unroll",
"(",
"num_lstm_layer",
",",
"seq_len",
",",
"num_hidden",
",",
"num_label",
",",
"loss_type",
"=",
"None",
")",
":",
"# Create the base (shared between training and inference) and add loss to the end",
"pred",
"=",
"_lstm_unroll_base",
"(",
"num_lstm_l... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | init_states | Returns name and shape of init states of LSTM network
Parameters
----------
batch_size: list of tuple of str and tuple of int and int
num_lstm_layer: int
num_hidden: int
Returns
-------
list of tuple of str and tuple of int and int | example/ctc/lstm.py | def init_states(batch_size, num_lstm_layer, num_hidden):
"""
Returns name and shape of init states of LSTM network
Parameters
----------
batch_size: list of tuple of str and tuple of int and int
num_lstm_layer: int
num_hidden: int
Returns
-------
list of tuple of str and tuple ... | def init_states(batch_size, num_lstm_layer, num_hidden):
"""
Returns name and shape of init states of LSTM network
Parameters
----------
batch_size: list of tuple of str and tuple of int and int
num_lstm_layer: int
num_hidden: int
Returns
-------
list of tuple of str and tuple ... | [
"Returns",
"name",
"and",
"shape",
"of",
"init",
"states",
"of",
"LSTM",
"network"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L158-L174 | [
"def",
"init_states",
"(",
"batch_size",
",",
"num_lstm_layer",
",",
"num_hidden",
")",
":",
"init_c",
"=",
"[",
"(",
"'l%d_init_c'",
"%",
"l",
",",
"(",
"batch_size",
",",
"num_hidden",
")",
")",
"for",
"l",
"in",
"range",
"(",
"num_lstm_layer",
")",
"]... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _imperative_invoke | ctypes implementation of imperative invoke wrapper | python/mxnet/_ctypes/ndarray.py | def _imperative_invoke(handle, ndargs, keys, vals, out):
"""ctypes implementation of imperative invoke wrapper"""
if out is not None:
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(o... | def _imperative_invoke(handle, ndargs, keys, vals, out):
"""ctypes implementation of imperative invoke wrapper"""
if out is not None:
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(o... | [
"ctypes",
"implementation",
"of",
"imperative",
"invoke",
"wrapper"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/_ctypes/ndarray.py#L65-L102 | [
"def",
"_imperative_invoke",
"(",
"handle",
",",
"ndargs",
",",
"keys",
",",
"vals",
",",
"out",
")",
":",
"if",
"out",
"is",
"not",
"None",
":",
"original_output",
"=",
"out",
"if",
"isinstance",
"(",
"out",
",",
"NDArrayBase",
")",
":",
"out",
"=",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | set_is_training | Set status to training/not training. When training, graph will be constructed
for gradient computation. Operators will also run with ctx.is_train=True. For example,
Dropout will drop inputs randomly when is_train=True while simply passing through
if is_train=False.
Parameters
----------
is_trai... | python/mxnet/contrib/autograd.py | def set_is_training(is_train):
"""Set status to training/not training. When training, graph will be constructed
for gradient computation. Operators will also run with ctx.is_train=True. For example,
Dropout will drop inputs randomly when is_train=True while simply passing through
if is_train=False.
... | def set_is_training(is_train):
"""Set status to training/not training. When training, graph will be constructed
for gradient computation. Operators will also run with ctx.is_train=True. For example,
Dropout will drop inputs randomly when is_train=True while simply passing through
if is_train=False.
... | [
"Set",
"status",
"to",
"training",
"/",
"not",
"training",
".",
"When",
"training",
"graph",
"will",
"be",
"constructed",
"for",
"gradient",
"computation",
".",
"Operators",
"will",
"also",
"run",
"with",
"ctx",
".",
"is_train",
"=",
"True",
".",
"For",
"e... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/autograd.py#L32-L51 | [
"def",
"set_is_training",
"(",
"is_train",
")",
":",
"prev",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXAutogradSetIsTraining",
"(",
"ctypes",
".",
"c_int",
"(",
"is_train",
")",
",",
"ctypes",
".",
"byref",
"(",
"prev",
")... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | backward | Compute the gradients of outputs w.r.t variables.
Parameters
----------
outputs: list of NDArray
out_grads: list of NDArray or None | python/mxnet/contrib/autograd.py | def backward(outputs, out_grads=None, retain_graph=False):
"""Compute the gradients of outputs w.r.t variables.
Parameters
----------
outputs: list of NDArray
out_grads: list of NDArray or None
"""
assert isinstance(outputs, (list, tuple)), \
"outputs must be a list or tuple of NDAr... | def backward(outputs, out_grads=None, retain_graph=False):
"""Compute the gradients of outputs w.r.t variables.
Parameters
----------
outputs: list of NDArray
out_grads: list of NDArray or None
"""
assert isinstance(outputs, (list, tuple)), \
"outputs must be a list or tuple of NDAr... | [
"Compute",
"the",
"gradients",
"of",
"outputs",
"w",
".",
"r",
".",
"t",
"variables",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/autograd.py#L123-L155 | [
"def",
"backward",
"(",
"outputs",
",",
"out_grads",
"=",
"None",
",",
"retain_graph",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"outputs",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"\"outputs must be a list or tuple of NDArrays\"",
"if",
"out_... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | grad_and_loss | Return function that computes both gradient of arguments and loss value.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
-------
grad_and_loss_func: a python ... | python/mxnet/contrib/autograd.py | def grad_and_loss(func, argnum=None):
"""Return function that computes both gradient of arguments and loss value.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
... | def grad_and_loss(func, argnum=None):
"""Return function that computes both gradient of arguments and loss value.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
... | [
"Return",
"function",
"that",
"computes",
"both",
"gradient",
"of",
"arguments",
"and",
"loss",
"value",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/autograd.py#L163-L193 | [
"def",
"grad_and_loss",
"(",
"func",
",",
"argnum",
"=",
"None",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"\"\"\"Wrapped function.\"\"\"",
"variables",
"=",
"args",
"if",
"argnum",
"is",
"n... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | grad | Return function that computes gradient of arguments.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
-------
grad_func: a python function
A function t... | python/mxnet/contrib/autograd.py | def grad(func, argnum=None):
"""Return function that computes gradient of arguments.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
-------
grad_func: a ... | def grad(func, argnum=None):
"""Return function that computes gradient of arguments.
Parameters
----------
func: a python function
The forward (loss) function.
argnum: an int or a list of int
The index of argument to calculate gradient for.
Returns
-------
grad_func: a ... | [
"Return",
"function",
"that",
"computes",
"gradient",
"of",
"arguments",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/autograd.py#L195-L230 | [
"def",
"grad",
"(",
"func",
",",
"argnum",
"=",
"None",
")",
":",
"grad_with_loss_func",
"=",
"grad_and_loss",
"(",
"func",
",",
"argnum",
")",
"@",
"functools",
".",
"wraps",
"(",
"grad_with_loss_func",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | split_data | Splits an NDArray into `num_slice` slices along `batch_axis`.
Usually used for data parallelism where each slices is sent
to one device (i.e. GPU).
Parameters
----------
data : NDArray
A batch of data.
num_slice : int
Number of desired slices.
batch_axis : int, default 0
... | python/mxnet/gluon/utils.py | def split_data(data, num_slice, batch_axis=0, even_split=True):
"""Splits an NDArray into `num_slice` slices along `batch_axis`.
Usually used for data parallelism where each slices is sent
to one device (i.e. GPU).
Parameters
----------
data : NDArray
A batch of data.
num_slice : in... | def split_data(data, num_slice, batch_axis=0, even_split=True):
"""Splits an NDArray into `num_slice` slices along `batch_axis`.
Usually used for data parallelism where each slices is sent
to one device (i.e. GPU).
Parameters
----------
data : NDArray
A batch of data.
num_slice : in... | [
"Splits",
"an",
"NDArray",
"into",
"num_slice",
"slices",
"along",
"batch_axis",
".",
"Usually",
"used",
"for",
"data",
"parallelism",
"where",
"each",
"slices",
"is",
"sent",
"to",
"one",
"device",
"(",
"i",
".",
"e",
".",
"GPU",
")",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L42-L90 | [
"def",
"split_data",
"(",
"data",
",",
"num_slice",
",",
"batch_axis",
"=",
"0",
",",
"even_split",
"=",
"True",
")",
":",
"size",
"=",
"data",
".",
"shape",
"[",
"batch_axis",
"]",
"if",
"even_split",
"and",
"size",
"%",
"num_slice",
"!=",
"0",
":",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | split_and_load | Splits an NDArray into `len(ctx_list)` slices along `batch_axis` and loads
each slice to one context in `ctx_list`.
Parameters
----------
data : NDArray
A batch of data.
ctx_list : list of Context
A list of Contexts.
batch_axis : int, default 0
The axis along which to sl... | python/mxnet/gluon/utils.py | def split_and_load(data, ctx_list, batch_axis=0, even_split=True):
"""Splits an NDArray into `len(ctx_list)` slices along `batch_axis` and loads
each slice to one context in `ctx_list`.
Parameters
----------
data : NDArray
A batch of data.
ctx_list : list of Context
A list of Co... | def split_and_load(data, ctx_list, batch_axis=0, even_split=True):
"""Splits an NDArray into `len(ctx_list)` slices along `batch_axis` and loads
each slice to one context in `ctx_list`.
Parameters
----------
data : NDArray
A batch of data.
ctx_list : list of Context
A list of Co... | [
"Splits",
"an",
"NDArray",
"into",
"len",
"(",
"ctx_list",
")",
"slices",
"along",
"batch_axis",
"and",
"loads",
"each",
"slice",
"to",
"one",
"context",
"in",
"ctx_list",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L93-L119 | [
"def",
"split_and_load",
"(",
"data",
",",
"ctx_list",
",",
"batch_axis",
"=",
"0",
",",
"even_split",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"ndarray",
".",
"NDArray",
")",
":",
"data",
"=",
"ndarray",
".",
"array",
"(",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | clip_global_norm | Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`.
Parameters
----------
arrays : list of NDArray
max_norm : float
check_isfinite : bool, default True
If True, check that the total_norm is finite (not nan or inf). This
requires a blocking .asscalar() cal... | python/mxnet/gluon/utils.py | def clip_global_norm(arrays, max_norm, check_isfinite=True):
"""Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`.
Parameters
----------
arrays : list of NDArray
max_norm : float
check_isfinite : bool, default True
If True, check that the total_norm is finite... | def clip_global_norm(arrays, max_norm, check_isfinite=True):
"""Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`.
Parameters
----------
arrays : list of NDArray
max_norm : float
check_isfinite : bool, default True
If True, check that the total_norm is finite... | [
"Rescales",
"NDArrays",
"so",
"that",
"the",
"sum",
"of",
"their",
"2",
"-",
"norm",
"is",
"smaller",
"than",
"max_norm",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L122-L161 | [
"def",
"clip_global_norm",
"(",
"arrays",
",",
"max_norm",
",",
"check_isfinite",
"=",
"True",
")",
":",
"def",
"_norm",
"(",
"array",
")",
":",
"if",
"array",
".",
"stype",
"==",
"'default'",
":",
"x",
"=",
"array",
".",
"reshape",
"(",
"(",
"-",
"1... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _indent | Indent string | python/mxnet/gluon/utils.py | def _indent(s_, numSpaces):
"""Indent string
"""
s = s_.split('\n')
if len(s) == 1:
return s_
first = s.pop(0)
s = [first] + [(numSpaces * ' ') + line for line in s]
s = '\n'.join(s)
return s | def _indent(s_, numSpaces):
"""Indent string
"""
s = s_.split('\n')
if len(s) == 1:
return s_
first = s.pop(0)
s = [first] + [(numSpaces * ' ') + line for line in s]
s = '\n'.join(s)
return s | [
"Indent",
"string"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L164-L173 | [
"def",
"_indent",
"(",
"s_",
",",
"numSpaces",
")",
":",
"s",
"=",
"s_",
".",
"split",
"(",
"'\\n'",
")",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"return",
"s_",
"first",
"=",
"s",
".",
"pop",
"(",
"0",
")",
"s",
"=",
"[",
"first",
"]",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | check_sha1 | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash. | python/mxnet/gluon/utils.py | def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the f... | def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the f... | [
"Check",
"whether",
"the",
"sha1",
"hash",
"of",
"the",
"file",
"content",
"matches",
"the",
"expected",
"hash",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L176-L199 | [
"def",
"check_sha1",
"(",
"filename",
",",
"sha1_hash",
")",
":",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"while",
"True",
":",
"data",
"=",
"f",
".",
"read",
"(",
"1048576",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | download | Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
overwrite : bool, optional
Whether to overwrite destination file... | python/mxnet/gluon/utils.py | def download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True):
"""Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with... | def download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True):
"""Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with... | [
"Download",
"an",
"given",
"URL"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L258-L349 | [
"def",
"download",
"(",
"url",
",",
"path",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"sha1_hash",
"=",
"None",
",",
"retries",
"=",
"5",
",",
"verify_ssl",
"=",
"True",
")",
":",
"if",
"path",
"is",
"None",
":",
"fname",
"=",
"url",
".",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _get_repo_url | Return the base URL for Gluon dataset and model repository. | python/mxnet/gluon/utils.py | def _get_repo_url():
"""Return the base URL for Gluon dataset and model repository."""
default_repo = 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/'
repo_url = os.environ.get('MXNET_GLUON_REPO', default_repo)
if repo_url[-1] != '/':
repo_url = repo_url+'/'
return repo_url | def _get_repo_url():
"""Return the base URL for Gluon dataset and model repository."""
default_repo = 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/'
repo_url = os.environ.get('MXNET_GLUON_REPO', default_repo)
if repo_url[-1] != '/':
repo_url = repo_url+'/'
return repo_url | [
"Return",
"the",
"base",
"URL",
"for",
"Gluon",
"dataset",
"and",
"model",
"repository",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L351-L357 | [
"def",
"_get_repo_url",
"(",
")",
":",
"default_repo",
"=",
"'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/'",
"repo_url",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'MXNET_GLUON_REPO'",
",",
"default_repo",
")",
"if",
"repo_url",
"[",
"-",
"1",
"]",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _get_repo_file_url | Return the URL for hosted file in Gluon repository.
Parameters
----------
namespace : str
Namespace of the file.
filename : str
Name of the file | python/mxnet/gluon/utils.py | def _get_repo_file_url(namespace, filename):
"""Return the URL for hosted file in Gluon repository.
Parameters
----------
namespace : str
Namespace of the file.
filename : str
Name of the file
"""
return '{base_url}{namespace}/{filename}'.format(base_url=_get_repo_url(),
... | def _get_repo_file_url(namespace, filename):
"""Return the URL for hosted file in Gluon repository.
Parameters
----------
namespace : str
Namespace of the file.
filename : str
Name of the file
"""
return '{base_url}{namespace}/{filename}'.format(base_url=_get_repo_url(),
... | [
"Return",
"the",
"URL",
"for",
"hosted",
"file",
"in",
"Gluon",
"repository",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L359-L371 | [
"def",
"_get_repo_file_url",
"(",
"namespace",
",",
"filename",
")",
":",
"return",
"'{base_url}{namespace}/{filename}'",
".",
"format",
"(",
"base_url",
"=",
"_get_repo_url",
"(",
")",
",",
"namespace",
"=",
"namespace",
",",
"filename",
"=",
"filename",
")"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _brief_print_list | Print at most `limit` elements of list. | python/mxnet/gluon/utils.py | def _brief_print_list(lst, limit=7):
"""Print at most `limit` elements of list."""
lst = list(lst)
if len(lst) > limit:
return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \
_brief_print_list(lst[-limit//2:], limit)
return ', '.join(["'%s'"%str(i) for i in lst]) | def _brief_print_list(lst, limit=7):
"""Print at most `limit` elements of list."""
lst = list(lst)
if len(lst) > limit:
return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \
_brief_print_list(lst[-limit//2:], limit)
return ', '.join(["'%s'"%str(i) for i in lst]) | [
"Print",
"at",
"most",
"limit",
"elements",
"of",
"list",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L373-L379 | [
"def",
"_brief_print_list",
"(",
"lst",
",",
"limit",
"=",
"7",
")",
":",
"lst",
"=",
"list",
"(",
"lst",
")",
"if",
"len",
"(",
"lst",
")",
">",
"limit",
":",
"return",
"_brief_print_list",
"(",
"lst",
"[",
":",
"limit",
"//",
"2",
"]",
",",
"li... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _make_symbol_function | Create a symbol function by handle and function name. | python/mxnet/symbol/register.py | def _make_symbol_function(handle, name, func_name):
"""Create a symbol function by handle and function name."""
code, doc_str = _generate_symbol_function_code(handle, name, func_name)
local = {}
exec(code, None, local) # pylint: disable=exec-used
symbol_function = local[func_name]
symbol_funct... | def _make_symbol_function(handle, name, func_name):
"""Create a symbol function by handle and function name."""
code, doc_str = _generate_symbol_function_code(handle, name, func_name)
local = {}
exec(code, None, local) # pylint: disable=exec-used
symbol_function = local[func_name]
symbol_funct... | [
"Create",
"a",
"symbol",
"function",
"by",
"handle",
"and",
"function",
"name",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/register.py#L199-L209 | [
"def",
"_make_symbol_function",
"(",
"handle",
",",
"name",
",",
"func_name",
")",
":",
"code",
",",
"doc_str",
"=",
"_generate_symbol_function_code",
"(",
"handle",
",",
"name",
",",
"func_name",
")",
"local",
"=",
"{",
"}",
"exec",
"(",
"code",
",",
"Non... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | batch_row_ids | Generate row ids based on the current mini-batch | example/sparse/matrix_factorization/train.py | def batch_row_ids(data_batch):
""" Generate row ids based on the current mini-batch """
item = data_batch.data[0]
user = data_batch.data[1]
return {'user_weight': user.astype(np.int64),
'item_weight': item.astype(np.int64)} | def batch_row_ids(data_batch):
""" Generate row ids based on the current mini-batch """
item = data_batch.data[0]
user = data_batch.data[1]
return {'user_weight': user.astype(np.int64),
'item_weight': item.astype(np.int64)} | [
"Generate",
"row",
"ids",
"based",
"on",
"the",
"current",
"mini",
"-",
"batch"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/sparse/matrix_factorization/train.py#L52-L57 | [
"def",
"batch_row_ids",
"(",
"data_batch",
")",
":",
"item",
"=",
"data_batch",
".",
"data",
"[",
"0",
"]",
"user",
"=",
"data_batch",
".",
"data",
"[",
"1",
"]",
"return",
"{",
"'user_weight'",
":",
"user",
".",
"astype",
"(",
"np",
".",
"int64",
")... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | all_row_ids | Generate row ids for all rows | example/sparse/matrix_factorization/train.py | def all_row_ids(data_batch):
""" Generate row ids for all rows """
all_users = mx.nd.arange(0, MOVIELENS['max_user'], dtype='int64')
all_movies = mx.nd.arange(0, MOVIELENS['max_movie'], dtype='int64')
return {'user_weight': all_users, 'item_weight': all_movies} | def all_row_ids(data_batch):
""" Generate row ids for all rows """
all_users = mx.nd.arange(0, MOVIELENS['max_user'], dtype='int64')
all_movies = mx.nd.arange(0, MOVIELENS['max_movie'], dtype='int64')
return {'user_weight': all_users, 'item_weight': all_movies} | [
"Generate",
"row",
"ids",
"for",
"all",
"rows"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/sparse/matrix_factorization/train.py#L59-L63 | [
"def",
"all_row_ids",
"(",
"data_batch",
")",
":",
"all_users",
"=",
"mx",
".",
"nd",
".",
"arange",
"(",
"0",
",",
"MOVIELENS",
"[",
"'max_user'",
"]",
",",
"dtype",
"=",
"'int64'",
")",
"all_movies",
"=",
"mx",
".",
"nd",
".",
"arange",
"(",
"0",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | convert_model | Convert caffe model
Parameters
----------
prototxt_fname : str
Filename of the prototxt model definition
caffemodel_fname : str
Filename of the binary caffe model
output_prefix : str, optinoal
If given, then save the converted MXNet into output_prefx+'.json' and
... | example/ssd/tools/caffe_converter/convert_model.py | def convert_model(prototxt_fname, caffemodel_fname, output_prefix=None):
"""Convert caffe model
Parameters
----------
prototxt_fname : str
Filename of the prototxt model definition
caffemodel_fname : str
Filename of the binary caffe model
output_prefix : str, optinoal
... | def convert_model(prototxt_fname, caffemodel_fname, output_prefix=None):
"""Convert caffe model
Parameters
----------
prototxt_fname : str
Filename of the prototxt model definition
caffemodel_fname : str
Filename of the binary caffe model
output_prefix : str, optinoal
... | [
"Convert",
"caffe",
"model"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_model.py#L26-L210 | [
"def",
"convert_model",
"(",
"prototxt_fname",
",",
"caffemodel_fname",
",",
"output_prefix",
"=",
"None",
")",
":",
"sym",
",",
"input_dim",
"=",
"convert_symbol",
"(",
"prototxt_fname",
")",
"arg_shapes",
",",
"_",
",",
"aux_shapes",
"=",
"sym",
".",
"infer_... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _parse_proto | Parse Caffe prototxt into symbol string | tools/caffe_converter/convert_symbol.py | def _parse_proto(prototxt_fname):
"""Parse Caffe prototxt into symbol string
"""
proto = caffe_parser.read_prototxt(prototxt_fname)
# process data layer
input_name, input_dim, layers = _get_input(proto)
# only support single input, so always use `data` as the input data
mapping = {input_nam... | def _parse_proto(prototxt_fname):
"""Parse Caffe prototxt into symbol string
"""
proto = caffe_parser.read_prototxt(prototxt_fname)
# process data layer
input_name, input_dim, layers = _get_input(proto)
# only support single input, so always use `data` as the input data
mapping = {input_nam... | [
"Parse",
"Caffe",
"prototxt",
"into",
"symbol",
"string"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/convert_symbol.py#L127-L295 | [
"def",
"_parse_proto",
"(",
"prototxt_fname",
")",
":",
"proto",
"=",
"caffe_parser",
".",
"read_prototxt",
"(",
"prototxt_fname",
")",
"# process data layer",
"input_name",
",",
"input_dim",
",",
"layers",
"=",
"_get_input",
"(",
"proto",
")",
"# only support singl... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | convert_symbol | Convert caffe model definition into Symbol
Parameters
----------
prototxt_fname : str
Filename of the prototxt file
Returns
-------
Symbol
Converted Symbol
tuple
Input shape | tools/caffe_converter/convert_symbol.py | def convert_symbol(prototxt_fname):
"""Convert caffe model definition into Symbol
Parameters
----------
prototxt_fname : str
Filename of the prototxt file
Returns
-------
Symbol
Converted Symbol
tuple
Input shape
"""
sym, output_name, input_dim = _parse_... | def convert_symbol(prototxt_fname):
"""Convert caffe model definition into Symbol
Parameters
----------
prototxt_fname : str
Filename of the prototxt file
Returns
-------
Symbol
Converted Symbol
tuple
Input shape
"""
sym, output_name, input_dim = _parse_... | [
"Convert",
"caffe",
"model",
"definition",
"into",
"Symbol"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/convert_symbol.py#L297-L320 | [
"def",
"convert_symbol",
"(",
"prototxt_fname",
")",
":",
"sym",
",",
"output_name",
",",
"input_dim",
"=",
"_parse_proto",
"(",
"prototxt_fname",
")",
"exec",
"(",
"sym",
")",
"# pylint: disable=exec-used",
"_locals",
"=",
"locals",
"(",
")",
"ret",
"=",
"[",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_vgg | r"""VGG model from the `"Very Deep Convolutional Networks for Large-Scale Image Recognition"
<https://arxiv.org/abs/1409.1556>`_ paper.
Parameters
----------
num_layers : int
Number of layers for the variant of densenet. Options are 11, 13, 16, 19.
pretrained : bool, default False
W... | python/mxnet/gluon/model_zoo/vision/vgg.py | def get_vgg(num_layers, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""VGG model from the `"Very Deep Convolutional Networks for Large-Scale Image Recognition"
<https://arxiv.org/abs/1409.1556>`_ paper.
Parameters
----------
num_layers : int
... | def get_vgg(num_layers, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""VGG model from the `"Very Deep Convolutional Networks for Large-Scale Image Recognition"
<https://arxiv.org/abs/1409.1556>`_ paper.
Parameters
----------
num_layers : int
... | [
"r",
"VGG",
"model",
"from",
"the",
"Very",
"Deep",
"Convolutional",
"Networks",
"for",
"Large",
"-",
"Scale",
"Image",
"Recognition",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1409",
".",
"1556",
">",
"_",
"paper",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/vision/vgg.py#L97-L120 | [
"def",
"get_vgg",
"(",
"num_layers",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
".",
"data_dir",
"(",
")",
",",
"'models'",
")",
",",
"*",
"*",
"kwargs",
")",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | check_with_uniform | check function consistency with uniform random numbers | example/profiler/profiler_ndarray.py | def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]):
"""check function consistency with uniform random numbers"""
if isinstance(arg_shapes, int):
assert dim
shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim))
arg_shapes = [shape] ... | def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]):
"""check function consistency with uniform random numbers"""
if isinstance(arg_shapes, int):
assert dim
shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim))
arg_shapes = [shape] ... | [
"check",
"function",
"consistency",
"with",
"uniform",
"random",
"numbers"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/profiler/profiler_ndarray.py#L51-L77 | [
"def",
"check_with_uniform",
"(",
"uf",
",",
"arg_shapes",
",",
"dim",
"=",
"None",
",",
"npuf",
"=",
"None",
",",
"rmin",
"=",
"-",
"10",
",",
"type_list",
"=",
"[",
"np",
".",
"float32",
"]",
")",
":",
"if",
"isinstance",
"(",
"arg_shapes",
",",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | IMDB.filter_roidb | Remove images without usable rois | example/rcnn/symimdb/imdb.py | def filter_roidb(self):
"""Remove images without usable rois"""
num_roidb = len(self._roidb)
self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])]
num_after = len(self._roidb)
logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after)) | def filter_roidb(self):
"""Remove images without usable rois"""
num_roidb = len(self._roidb)
self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])]
num_after = len(self._roidb)
logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after)) | [
"Remove",
"images",
"without",
"usable",
"rois"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symimdb/imdb.py#L76-L81 | [
"def",
"filter_roidb",
"(",
"self",
")",
":",
"num_roidb",
"=",
"len",
"(",
"self",
".",
"_roidb",
")",
"self",
".",
"_roidb",
"=",
"[",
"roi_rec",
"for",
"roi_rec",
"in",
"self",
".",
"_roidb",
"if",
"len",
"(",
"roi_rec",
"[",
"'gt_classes'",
"]",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | IMDB.append_flipped_images | Only flip boxes coordinates, images will be flipped when loading into network | example/rcnn/symimdb/imdb.py | def append_flipped_images(self):
"""Only flip boxes coordinates, images will be flipped when loading into network"""
logger.info('%s append flipped images to roidb' % self._name)
roidb_flipped = []
for roi_rec in self._roidb:
boxes = roi_rec['boxes'].copy()
oldx1 ... | def append_flipped_images(self):
"""Only flip boxes coordinates, images will be flipped when loading into network"""
logger.info('%s append flipped images to roidb' % self._name)
roidb_flipped = []
for roi_rec in self._roidb:
boxes = roi_rec['boxes'].copy()
oldx1 ... | [
"Only",
"flip",
"boxes",
"coordinates",
"images",
"will",
"be",
"flipped",
"when",
"loading",
"into",
"network"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symimdb/imdb.py#L83-L98 | [
"def",
"append_flipped_images",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'%s append flipped images to roidb'",
"%",
"self",
".",
"_name",
")",
"roidb_flipped",
"=",
"[",
"]",
"for",
"roi_rec",
"in",
"self",
".",
"_roidb",
":",
"boxes",
"=",
"roi_r... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_model_file | r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----------
name : str
Name of the model.
root : str, default $MX... | python/mxnet/gluon/model_zoo/model_store.py | def get_model_file(name, root=os.path.join(base.data_dir(), 'models')):
r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----... | def get_model_file(name, root=os.path.join(base.data_dir(), 'models')):
r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----... | [
"r",
"Return",
"location",
"for",
"the",
"pretrained",
"on",
"local",
"file",
"system",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/model_store.py#L73-L120 | [
"def",
"get_model_file",
"(",
"name",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
".",
"data_dir",
"(",
")",
",",
"'models'",
")",
")",
":",
"file_name",
"=",
"'{name}-{short_hash}'",
".",
"format",
"(",
"name",
"=",
"name",
",",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | purge | r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters. | python/mxnet/gluon/model_zoo/model_store.py | def purge(root=os.path.join(base.data_dir(), 'models')):
r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
"""
root = os.path.expanduser(root)
files = os.listdir(root)
... | def purge(root=os.path.join(base.data_dir(), 'models')):
r"""Purge all pretrained model files in local file store.
Parameters
----------
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
"""
root = os.path.expanduser(root)
files = os.listdir(root)
... | [
"r",
"Purge",
"all",
"pretrained",
"model",
"files",
"in",
"local",
"file",
"store",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/model_store.py#L122-L134 | [
"def",
"purge",
"(",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
".",
"data_dir",
"(",
")",
",",
"'models'",
")",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"root",
")",
"files",
"=",
"os",
".",
"listdir",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | Coco.image_path_from_index | given image index, find out full path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of this image | example/ssd/dataset/mscoco.py | def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of this image
"""
assert self.image_set_index is not No... | def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of this image
"""
assert self.image_set_index is not No... | [
"given",
"image",
"index",
"find",
"out",
"full",
"path"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/mscoco.py#L52-L68 | [
"def",
"image_path_from_index",
"(",
"self",
",",
"index",
")",
":",
"assert",
"self",
".",
"image_set_index",
"is",
"not",
"None",
",",
"\"Dataset not initialized\"",
"name",
"=",
"self",
".",
"image_set_index",
"[",
"index",
"]",
"image_file",
"=",
"os",
"."... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | Coco._load_all | initialize all entries given annotation json file
Parameters:
----------
anno_file: str
annotation json file
shuffle: bool
whether to shuffle image list | example/ssd/dataset/mscoco.py | def _load_all(self, anno_file, shuffle):
"""
initialize all entries given annotation json file
Parameters:
----------
anno_file: str
annotation json file
shuffle: bool
whether to shuffle image list
"""
image_set_index = []
... | def _load_all(self, anno_file, shuffle):
"""
initialize all entries given annotation json file
Parameters:
----------
anno_file: str
annotation json file
shuffle: bool
whether to shuffle image list
"""
image_set_index = []
... | [
"initialize",
"all",
"entries",
"given",
"annotation",
"json",
"file"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/mscoco.py#L85-L138 | [
"def",
"_load_all",
"(",
"self",
",",
"anno_file",
",",
"shuffle",
")",
":",
"image_set_index",
"=",
"[",
"]",
"labels",
"=",
"[",
"]",
"coco",
"=",
"COCO",
"(",
"anno_file",
")",
"img_ids",
"=",
"coco",
".",
"getImgIds",
"(",
")",
"# deal with class nam... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | CustomStatefulModule.init_params | Initializes the parameters and auxiliary states. | example/rnn/word_lm/module.py | def init_params(self, initializer=mx.init.Uniform(0.01), **kwargs):
"""Initializes the parameters and auxiliary states.
"""
self._module.init_params(initializer=initializer, **kwargs) | def init_params(self, initializer=mx.init.Uniform(0.01), **kwargs):
"""Initializes the parameters and auxiliary states.
"""
self._module.init_params(initializer=initializer, **kwargs) | [
"Initializes",
"the",
"parameters",
"and",
"auxiliary",
"states",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/module.py#L61-L64 | [
"def",
"init_params",
"(",
"self",
",",
"initializer",
"=",
"mx",
".",
"init",
".",
"Uniform",
"(",
"0.01",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_module",
".",
"init_params",
"(",
"initializer",
"=",
"initializer",
",",
"*",
"*",
"kw... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | CustomStatefulModule.forward | Forward computation. States from previous forward computation are carried
to the current iteration if `carry_state` is set to `True`. | example/rnn/word_lm/module.py | def forward(self, data_batch, is_train=None, carry_state=True):
"""Forward computation. States from previous forward computation are carried
to the current iteration if `carry_state` is set to `True`.
"""
# propagate states from the previous iteration
if carry_state:
... | def forward(self, data_batch, is_train=None, carry_state=True):
"""Forward computation. States from previous forward computation are carried
to the current iteration if `carry_state` is set to `True`.
"""
# propagate states from the previous iteration
if carry_state:
... | [
"Forward",
"computation",
".",
"States",
"from",
"previous",
"forward",
"computation",
"are",
"carried",
"to",
"the",
"current",
"iteration",
"if",
"carry_state",
"is",
"set",
"to",
"True",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/module.py#L78-L90 | [
"def",
"forward",
"(",
"self",
",",
"data_batch",
",",
"is_train",
"=",
"None",
",",
"carry_state",
"=",
"True",
")",
":",
"# propagate states from the previous iteration",
"if",
"carry_state",
":",
"if",
"isinstance",
"(",
"self",
".",
"_next_states",
",",
"(",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | CustomStatefulModule.update | Updates parameters according to the installed optimizer and the gradients computed
in the previous forward-backward batch. Gradients are clipped by their global norm
if `max_norm` is set.
Parameters
----------
max_norm: float, optional
If set, clip values of all grad... | example/rnn/word_lm/module.py | def update(self, max_norm=None):
"""Updates parameters according to the installed optimizer and the gradients computed
in the previous forward-backward batch. Gradients are clipped by their global norm
if `max_norm` is set.
Parameters
----------
max_norm: float, optional... | def update(self, max_norm=None):
"""Updates parameters according to the installed optimizer and the gradients computed
in the previous forward-backward batch. Gradients are clipped by their global norm
if `max_norm` is set.
Parameters
----------
max_norm: float, optional... | [
"Updates",
"parameters",
"according",
"to",
"the",
"installed",
"optimizer",
"and",
"the",
"gradients",
"computed",
"in",
"the",
"previous",
"forward",
"-",
"backward",
"batch",
".",
"Gradients",
"are",
"clipped",
"by",
"their",
"global",
"norm",
"if",
"max_norm... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/module.py#L92-L104 | [
"def",
"update",
"(",
"self",
",",
"max_norm",
"=",
"None",
")",
":",
"if",
"max_norm",
"is",
"not",
"None",
":",
"self",
".",
"_clip_by_global_norm",
"(",
"max_norm",
")",
"self",
".",
"_module",
".",
"update",
"(",
")"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | CustomStatefulModule._clip_by_global_norm | Clips gradient norm.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
The method is first used in
`[ICML2013] On the difficulty of training recurrent neural networks`
Parameters
------... | example/rnn/word_lm/module.py | def _clip_by_global_norm(self, max_norm):
"""Clips gradient norm.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
The method is first used in
`[ICML2013] On the difficulty of training recurren... | def _clip_by_global_norm(self, max_norm):
"""Clips gradient norm.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
The method is first used in
`[ICML2013] On the difficulty of training recurren... | [
"Clips",
"gradient",
"norm",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/module.py#L106-L129 | [
"def",
"_clip_by_global_norm",
"(",
"self",
",",
"max_norm",
")",
":",
"assert",
"self",
".",
"_module",
".",
"binded",
"and",
"self",
".",
"_module",
".",
"params_initialized",
"and",
"self",
".",
"_module",
".",
"optimizer_initialized",
"grad_array",
"=",
"[... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | visual | Image visualization and preservation
:param title: title
:param X: images to visualized
:param name: saved picture`s name
:return: | example/gluon/dc_gan/dcgan.py | def visual(title, X, name):
"""Image visualization and preservation
:param title: title
:param X: images to visualized
:param name: saved picture`s name
:return:
"""
assert len(X.shape) == 4
X = X.transpose((0, 2, 3, 1))
X = np.clip((X - np.min(X))*(255.0/(np.max(X) - np.min(X))), 0,... | def visual(title, X, name):
"""Image visualization and preservation
:param title: title
:param X: images to visualized
:param name: saved picture`s name
:return:
"""
assert len(X.shape) == 4
X = X.transpose((0, 2, 3, 1))
X = np.clip((X - np.min(X))*(255.0/(np.max(X) - np.min(X))), 0,... | [
"Image",
"visualization",
"and",
"preservation",
":",
"param",
"title",
":",
"title",
":",
"param",
"X",
":",
"images",
"to",
"visualized",
":",
"param",
"name",
":",
"saved",
"picture",
"s",
"name",
":",
"return",
":"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L52-L69 | [
"def",
"visual",
"(",
"title",
",",
"X",
",",
"name",
")",
":",
"assert",
"len",
"(",
"X",
".",
"shape",
")",
"==",
"4",
"X",
"=",
"X",
".",
"transpose",
"(",
"(",
"0",
",",
"2",
",",
"3",
",",
"1",
")",
")",
"X",
"=",
"np",
".",
"clip",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | transformer | Get the translation of images | example/gluon/dc_gan/dcgan.py | def transformer(data, label):
"""Get the translation of images"""
# resize to 64x64
data = mx.image.imresize(data, 64, 64)
# transpose from (64, 64, 3) to (3, 64, 64)
data = mx.nd.transpose(data, (2, 0, 1))
# normalize to [-1, 1]
data = data.astype(np.float32)/128 - 1
# if image is greys... | def transformer(data, label):
"""Get the translation of images"""
# resize to 64x64
data = mx.image.imresize(data, 64, 64)
# transpose from (64, 64, 3) to (3, 64, 64)
data = mx.nd.transpose(data, (2, 0, 1))
# normalize to [-1, 1]
data = data.astype(np.float32)/128 - 1
# if image is greys... | [
"Get",
"the",
"translation",
"of",
"images"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L117-L128 | [
"def",
"transformer",
"(",
"data",
",",
"label",
")",
":",
"# resize to 64x64",
"data",
"=",
"mx",
".",
"image",
".",
"imresize",
"(",
"data",
",",
"64",
",",
"64",
")",
"# transpose from (64, 64, 3) to (3, 64, 64)",
"data",
"=",
"mx",
".",
"nd",
".",
"tra... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_dataset | Load the dataset and split it to train/valid data
:param dataset_name: string
Returns:
train_data: int array
training dataset
val_data: int array
valid dataset | example/gluon/dc_gan/dcgan.py | def get_dataset(dataset_name):
"""Load the dataset and split it to train/valid data
:param dataset_name: string
Returns:
train_data: int array
training dataset
val_data: int array
valid dataset
"""
# mnist
if dataset == "mnist":
train_data = gluon.data.DataLoade... | def get_dataset(dataset_name):
"""Load the dataset and split it to train/valid data
:param dataset_name: string
Returns:
train_data: int array
training dataset
val_data: int array
valid dataset
"""
# mnist
if dataset == "mnist":
train_data = gluon.data.DataLoade... | [
"Load",
"the",
"dataset",
"and",
"split",
"it",
"to",
"train",
"/",
"valid",
"data"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L132-L162 | [
"def",
"get_dataset",
"(",
"dataset_name",
")",
":",
"# mnist",
"if",
"dataset",
"==",
"\"mnist\"",
":",
"train_data",
"=",
"gluon",
".",
"data",
".",
"DataLoader",
"(",
"gluon",
".",
"data",
".",
"vision",
".",
"MNIST",
"(",
"'./data'",
",",
"train",
"=... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_netG | Get net G | example/gluon/dc_gan/dcgan.py | def get_netG():
"""Get net G"""
# build the generator
netG = nn.Sequential()
with netG.name_scope():
# input is Z, going into a convolution
netG.add(nn.Conv2DTranspose(ngf * 8, 4, 1, 0, use_bias=False))
netG.add(nn.BatchNorm())
netG.add(nn.Activation('relu'))
# st... | def get_netG():
"""Get net G"""
# build the generator
netG = nn.Sequential()
with netG.name_scope():
# input is Z, going into a convolution
netG.add(nn.Conv2DTranspose(ngf * 8, 4, 1, 0, use_bias=False))
netG.add(nn.BatchNorm())
netG.add(nn.Activation('relu'))
# st... | [
"Get",
"net",
"G"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L165-L191 | [
"def",
"get_netG",
"(",
")",
":",
"# build the generator",
"netG",
"=",
"nn",
".",
"Sequential",
"(",
")",
"with",
"netG",
".",
"name_scope",
"(",
")",
":",
"# input is Z, going into a convolution",
"netG",
".",
"add",
"(",
"nn",
".",
"Conv2DTranspose",
"(",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_netD | Get the netD | example/gluon/dc_gan/dcgan.py | def get_netD():
"""Get the netD"""
# build the discriminator
netD = nn.Sequential()
with netD.name_scope():
# input is (nc) x 64 x 64
netD.add(nn.Conv2D(ndf, 4, 2, 1, use_bias=False))
netD.add(nn.LeakyReLU(0.2))
# state size. (ndf) x 32 x 32
netD.add(nn.Conv2D(ndf... | def get_netD():
"""Get the netD"""
# build the discriminator
netD = nn.Sequential()
with netD.name_scope():
# input is (nc) x 64 x 64
netD.add(nn.Conv2D(ndf, 4, 2, 1, use_bias=False))
netD.add(nn.LeakyReLU(0.2))
# state size. (ndf) x 32 x 32
netD.add(nn.Conv2D(ndf... | [
"Get",
"the",
"netD"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L194-L218 | [
"def",
"get_netD",
"(",
")",
":",
"# build the discriminator",
"netD",
"=",
"nn",
".",
"Sequential",
"(",
")",
"with",
"netD",
".",
"name_scope",
"(",
")",
":",
"# input is (nc) x 64 x 64",
"netD",
".",
"add",
"(",
"nn",
".",
"Conv2D",
"(",
"ndf",
",",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_configurations | Get configurations for net | example/gluon/dc_gan/dcgan.py | def get_configurations(netG, netD):
"""Get configurations for net"""
# loss
loss = gluon.loss.SoftmaxCrossEntropyLoss()
# initialize the generator and the discriminator
netG.initialize(mx.init.Normal(0.02), ctx=ctx)
netD.initialize(mx.init.Normal(0.02), ctx=ctx)
# trainer for the generator... | def get_configurations(netG, netD):
"""Get configurations for net"""
# loss
loss = gluon.loss.SoftmaxCrossEntropyLoss()
# initialize the generator and the discriminator
netG.initialize(mx.init.Normal(0.02), ctx=ctx)
netD.initialize(mx.init.Normal(0.02), ctx=ctx)
# trainer for the generator... | [
"Get",
"configurations",
"for",
"net"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L221-L234 | [
"def",
"get_configurations",
"(",
"netG",
",",
"netD",
")",
":",
"# loss",
"loss",
"=",
"gluon",
".",
"loss",
".",
"SoftmaxCrossEntropyLoss",
"(",
")",
"# initialize the generator and the discriminator",
"netG",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"N... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | main | Entry point to dcgan | example/gluon/dc_gan/dcgan.py | def main():
"""Entry point to dcgan"""
print("|------- new changes!!!!!!!!!")
# to get the dataset and net configuration
train_data, val_data = get_dataset(dataset)
netG = get_netG()
netD = get_netD()
loss, trainerG, trainerD = get_configurations(netG, netD)
# set labels
real_label ... | def main():
"""Entry point to dcgan"""
print("|------- new changes!!!!!!!!!")
# to get the dataset and net configuration
train_data, val_data = get_dataset(dataset)
netG = get_netG()
netD = get_netD()
loss, trainerG, trainerD = get_configurations(netG, netD)
# set labels
real_label ... | [
"Entry",
"point",
"to",
"dcgan"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L249-L348 | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"\"|------- new changes!!!!!!!!!\"",
")",
"# to get the dataset and net configuration",
"train_data",
",",
"val_data",
"=",
"get_dataset",
"(",
"dataset",
")",
"netG",
"=",
"get_netG",
"(",
")",
"netD",
"=",
"get_netD",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | getLogger | Gets a customized logger.
.. note:: `getLogger` is deprecated. Use `get_logger` instead. | python/mxnet/log.py | def getLogger(name=None, filename=None, filemode=None, level=WARNING):
"""Gets a customized logger.
.. note:: `getLogger` is deprecated. Use `get_logger` instead.
"""
warnings.warn("getLogger is deprecated, Use get_logger instead.",
DeprecationWarning, stacklevel=2)
return get_lo... | def getLogger(name=None, filename=None, filemode=None, level=WARNING):
"""Gets a customized logger.
.. note:: `getLogger` is deprecated. Use `get_logger` instead.
"""
warnings.warn("getLogger is deprecated, Use get_logger instead.",
DeprecationWarning, stacklevel=2)
return get_lo... | [
"Gets",
"a",
"customized",
"logger",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/log.py#L80-L88 | [
"def",
"getLogger",
"(",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"filemode",
"=",
"None",
",",
"level",
"=",
"WARNING",
")",
":",
"warnings",
".",
"warn",
"(",
"\"getLogger is deprecated, Use get_logger instead.\"",
",",
"DeprecationWarning",
","... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_logger | Gets a customized logger.
Parameters
----------
name: str, optional
Name of the logger.
filename: str, optional
The filename to which the logger's output will be sent.
filemode: str, optional
The file mode to open the file (corresponding to `filename`),
default is 'a... | python/mxnet/log.py | def get_logger(name=None, filename=None, filemode=None, level=WARNING):
"""Gets a customized logger.
Parameters
----------
name: str, optional
Name of the logger.
filename: str, optional
The filename to which the logger's output will be sent.
filemode: str, optional
The ... | def get_logger(name=None, filename=None, filemode=None, level=WARNING):
"""Gets a customized logger.
Parameters
----------
name: str, optional
Name of the logger.
filename: str, optional
The filename to which the logger's output will be sent.
filemode: str, optional
The ... | [
"Gets",
"a",
"customized",
"logger",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/log.py#L90-L145 | [
"def",
"get_logger",
"(",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"filemode",
"=",
"None",
",",
"level",
"=",
"WARNING",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"if",
"name",
"is",
"not",
"None",
"and",... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | transformer | data preparation | example/gluon/sn_gan/data.py | def transformer(data, label):
""" data preparation """
data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE)
data = mx.nd.transpose(data, (2, 0, 1))
data = data.astype(np.float32) / 128.0 - 1
return data, label | def transformer(data, label):
""" data preparation """
data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE)
data = mx.nd.transpose(data, (2, 0, 1))
data = data.astype(np.float32) / 128.0 - 1
return data, label | [
"data",
"preparation"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/data.py#L30-L35 | [
"def",
"transformer",
"(",
"data",
",",
"label",
")",
":",
"data",
"=",
"mx",
".",
"image",
".",
"imresize",
"(",
"data",
",",
"IMAGE_SIZE",
",",
"IMAGE_SIZE",
")",
"data",
"=",
"mx",
".",
"nd",
".",
"transpose",
"(",
"data",
",",
"(",
"2",
",",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_training_data | helper function to get dataloader | example/gluon/sn_gan/data.py | def get_training_data(batch_size):
""" helper function to get dataloader"""
return gluon.data.DataLoader(
CIFAR10(train=True, transform=transformer),
batch_size=batch_size, shuffle=True, last_batch='discard') | def get_training_data(batch_size):
""" helper function to get dataloader"""
return gluon.data.DataLoader(
CIFAR10(train=True, transform=transformer),
batch_size=batch_size, shuffle=True, last_batch='discard') | [
"helper",
"function",
"to",
"get",
"dataloader"
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/data.py#L38-L42 | [
"def",
"get_training_data",
"(",
"batch_size",
")",
":",
"return",
"gluon",
".",
"data",
".",
"DataLoader",
"(",
"CIFAR10",
"(",
"train",
"=",
"True",
",",
"transform",
"=",
"transformer",
")",
",",
"batch_size",
"=",
"batch_size",
",",
"shuffle",
"=",
"Tr... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_resnet | r"""ResNet V1 model from `"Deep Residual Learning for Image Recognition"
<http://arxiv.org/abs/1512.03385>`_ paper.
ResNet V2 model from `"Identity Mappings in Deep Residual Networks"
<https://arxiv.org/abs/1603.05027>`_ paper.
Parameters
----------
version : int
Version of ResNet. Opti... | python/mxnet/gluon/model_zoo/vision/resnet.py | def get_resnet(version, num_layers, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""ResNet V1 model from `"Deep Residual Learning for Image Recognition"
<http://arxiv.org/abs/1512.03385>`_ paper.
ResNet V2 model from `"Identity Mappings in Deep Residu... | def get_resnet(version, num_layers, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""ResNet V1 model from `"Deep Residual Learning for Image Recognition"
<http://arxiv.org/abs/1512.03385>`_ paper.
ResNet V2 model from `"Identity Mappings in Deep Residu... | [
"r",
"ResNet",
"V1",
"model",
"from",
"Deep",
"Residual",
"Learning",
"for",
"Image",
"Recognition",
"<http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1512",
".",
"03385",
">",
"_",
"paper",
".",
"ResNet",
"V2",
"model",
"from",
"Identity",
"M... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/vision/resnet.py#L359-L392 | [
"def",
"get_resnet",
"(",
"version",
",",
"num_layers",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
".",
"data_dir",
"(",
")",
",",
"'models'",
")",
",",
"*",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | _random_helper | Helper function for random generators. | python/mxnet/symbol/random.py | def _random_helper(random, sampler, params, shape, dtype, kwargs):
"""Helper function for random generators."""
if isinstance(params[0], Symbol):
for i in params[1:]:
assert isinstance(i, Symbol), \
"Distribution parameters must all have the same type, but got " \
... | def _random_helper(random, sampler, params, shape, dtype, kwargs):
"""Helper function for random generators."""
if isinstance(params[0], Symbol):
for i in params[1:]:
assert isinstance(i, Symbol), \
"Distribution parameters must all have the same type, but got " \
... | [
"Helper",
"function",
"for",
"random",
"generators",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/random.py#L29-L45 | [
"def",
"_random_helper",
"(",
"random",
",",
"sampler",
",",
"params",
",",
"shape",
",",
"dtype",
",",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"params",
"[",
"0",
"]",
",",
"Symbol",
")",
":",
"for",
"i",
"in",
"params",
"[",
"1",
":",
"]",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | poisson | Draw random samples from a Poisson distribution.
Samples are distributed according to a Poisson distribution parametrized
by *lambda* (rate). Samples will always be returned as a floating point data type.
Parameters
----------
lam : float or Symbol, optional
Expectation of interval, should... | python/mxnet/symbol/random.py | def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs):
"""Draw random samples from a Poisson distribution.
Samples are distributed according to a Poisson distribution parametrized
by *lambda* (rate). Samples will always be returned as a floating point data type.
Parameters
----------
lam : fl... | def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs):
"""Draw random samples from a Poisson distribution.
Samples are distributed according to a Poisson distribution parametrized
by *lambda* (rate). Samples will always be returned as a floating point data type.
Parameters
----------
lam : fl... | [
"Draw",
"random",
"samples",
"from",
"a",
"Poisson",
"distribution",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/random.py#L116-L143 | [
"def",
"poisson",
"(",
"lam",
"=",
"1",
",",
"shape",
"=",
"_Null",
",",
"dtype",
"=",
"_Null",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_random_helper",
"(",
"_internal",
".",
"_random_poisson",
",",
"_internal",
".",
"_sample_poisson",
",",
"[",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | generalized_negative_binomial | Draw random samples from a generalized negative binomial distribution.
Samples are distributed according to a generalized negative binomial
distribution parametrized by *mu* (mean) and *alpha* (dispersion).
*alpha* is defined as *1/k* where *k* is the failure limit of the
number of unsuccessful experim... | python/mxnet/symbol/random.py | def generalized_negative_binomial(mu=1, alpha=1, shape=_Null, dtype=_Null, **kwargs):
"""Draw random samples from a generalized negative binomial distribution.
Samples are distributed according to a generalized negative binomial
distribution parametrized by *mu* (mean) and *alpha* (dispersion).
*alpha*... | def generalized_negative_binomial(mu=1, alpha=1, shape=_Null, dtype=_Null, **kwargs):
"""Draw random samples from a generalized negative binomial distribution.
Samples are distributed according to a generalized negative binomial
distribution parametrized by *mu* (mean) and *alpha* (dispersion).
*alpha*... | [
"Draw",
"random",
"samples",
"from",
"a",
"generalized",
"negative",
"binomial",
"distribution",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/random.py#L248-L281 | [
"def",
"generalized_negative_binomial",
"(",
"mu",
"=",
"1",
",",
"alpha",
"=",
"1",
",",
"shape",
"=",
"_Null",
",",
"dtype",
"=",
"_Null",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_random_helper",
"(",
"_internal",
".",
"_random_generalized_negative_b... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | multinomial | Concurrent sampling from multiple multinomial distributions.
.. note:: The input distribution must be normalized, i.e. `data` must sum to
1 along its last dimension.
Parameters
----------
data : Symbol
An *n* dimensional array whose last dimension has length `k`, where
`k... | python/mxnet/symbol/random.py | def multinomial(data, shape=_Null, get_prob=True, dtype='int32', **kwargs):
"""Concurrent sampling from multiple multinomial distributions.
.. note:: The input distribution must be normalized, i.e. `data` must sum to
1 along its last dimension.
Parameters
----------
data : Symbol
... | def multinomial(data, shape=_Null, get_prob=True, dtype='int32', **kwargs):
"""Concurrent sampling from multiple multinomial distributions.
.. note:: The input distribution must be normalized, i.e. `data` must sum to
1 along its last dimension.
Parameters
----------
data : Symbol
... | [
"Concurrent",
"sampling",
"from",
"multiple",
"multinomial",
"distributions",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/random.py#L284-L325 | [
"def",
"multinomial",
"(",
"data",
",",
"shape",
"=",
"_Null",
",",
"get_prob",
"=",
"True",
",",
"dtype",
"=",
"'int32'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_internal",
".",
"_sample_multinomial",
"(",
"data",
",",
"shape",
",",
"get_prob",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_symbol_train | Single-shot multi-box detection with VGG 16 layers ConvNet
This is a modified version, with fc6/fc7 layers replaced by conv layers
And the network is slightly smaller than original VGG 16 network
This is a training network with losses
Parameters:
----------
num_classes: int
number of ob... | example/ssd/symbol/legacy_vgg16_ssd_300.py | def get_symbol_train(num_classes=20, nms_thresh=0.5, force_suppress=False,
nms_topk=400, **kwargs):
"""
Single-shot multi-box detection with VGG 16 layers ConvNet
This is a modified version, with fc6/fc7 layers replaced by conv layers
And the network is slightly smaller than origina... | def get_symbol_train(num_classes=20, nms_thresh=0.5, force_suppress=False,
nms_topk=400, **kwargs):
"""
Single-shot multi-box detection with VGG 16 layers ConvNet
This is a modified version, with fc6/fc7 layers replaced by conv layers
And the network is slightly smaller than origina... | [
"Single",
"-",
"shot",
"multi",
"-",
"box",
"detection",
"with",
"VGG",
"16",
"layers",
"ConvNet",
"This",
"is",
"a",
"modified",
"version",
"with",
"fc6",
"/",
"fc7",
"layers",
"replaced",
"by",
"conv",
"layers",
"And",
"the",
"network",
"is",
"slightly",... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/legacy_vgg16_ssd_300.py#L22-L173 | [
"def",
"get_symbol_train",
"(",
"num_classes",
"=",
"20",
",",
"nms_thresh",
"=",
"0.5",
",",
"force_suppress",
"=",
"False",
",",
"nms_topk",
"=",
"400",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"name"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | get_symbol | Single-shot multi-box detection with VGG 16 layers ConvNet
This is a modified version, with fc6/fc7 layers replaced by conv layers
And the network is slightly smaller than original VGG 16 network
This is the detection network
Parameters:
----------
num_classes: int
number of object clas... | example/ssd/symbol/legacy_vgg16_ssd_300.py | def get_symbol(num_classes=20, nms_thresh=0.5, force_suppress=False,
nms_topk=400, **kwargs):
"""
Single-shot multi-box detection with VGG 16 layers ConvNet
This is a modified version, with fc6/fc7 layers replaced by conv layers
And the network is slightly smaller than original VGG 16 net... | def get_symbol(num_classes=20, nms_thresh=0.5, force_suppress=False,
nms_topk=400, **kwargs):
"""
Single-shot multi-box detection with VGG 16 layers ConvNet
This is a modified version, with fc6/fc7 layers replaced by conv layers
And the network is slightly smaller than original VGG 16 net... | [
"Single",
"-",
"shot",
"multi",
"-",
"box",
"detection",
"with",
"VGG",
"16",
"layers",
"ConvNet",
"This",
"is",
"a",
"modified",
"version",
"with",
"fc6",
"/",
"fc7",
"layers",
"replaced",
"by",
"conv",
"layers",
"And",
"the",
"network",
"is",
"slightly",... | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/legacy_vgg16_ssd_300.py#L175-L207 | [
"def",
"get_symbol",
"(",
"num_classes",
"=",
"20",
",",
"nms_thresh",
"=",
"0.5",
",",
"force_suppress",
"=",
"False",
",",
"nms_topk",
"=",
"400",
",",
"*",
"*",
"kwargs",
")",
":",
"net",
"=",
"get_symbol_train",
"(",
"num_classes",
")",
"cls_preds",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
train | Module.load | Creates a model from previously saved checkpoint.
Parameters
----------
prefix : str
path prefix of saved model files. You should have
"prefix-symbol.json", "prefix-xxxx.params", and
optionally "prefix-xxxx.states", where xxxx is the
epoch number.... | python/mxnet/module/module.py | def load(prefix, epoch, load_optimizer_states=False, **kwargs):
"""Creates a model from previously saved checkpoint.
Parameters
----------
prefix : str
path prefix of saved model files. You should have
"prefix-symbol.json", "prefix-xxxx.params", and
o... | def load(prefix, epoch, load_optimizer_states=False, **kwargs):
"""Creates a model from previously saved checkpoint.
Parameters
----------
prefix : str
path prefix of saved model files. You should have
"prefix-symbol.json", "prefix-xxxx.params", and
o... | [
"Creates",
"a",
"model",
"from",
"previously",
"saved",
"checkpoint",
"."
] | apache/incubator-mxnet | python | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L127-L163 | [
"def",
"load",
"(",
"prefix",
",",
"epoch",
",",
"load_optimizer_states",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"sym",
",",
"args",
",",
"auxs",
"=",
"load_checkpoint",
"(",
"prefix",
",",
"epoch",
")",
"mod",
"=",
"Module",
"(",
"symbol",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.