repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_proposal_recall | def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes):
"""
Draw top3 proposals for each gt.
Args:
proposals: NPx4
proposal_scores: NP
gt_boxes: NG
"""
box_ious = np_iou(gt_boxes, proposals) # ng x np
box_ious_argsort = np.argsort(-box_ious, axis=1)
go... | python | def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes):
"""
Draw top3 proposals for each gt.
Args:
proposals: NPx4
proposal_scores: NP
gt_boxes: NG
"""
box_ious = np_iou(gt_boxes, proposals) # ng x np
box_ious_argsort = np.argsort(-box_ious, axis=1)
go... | [
"def",
"draw_proposal_recall",
"(",
"img",
",",
"proposals",
",",
"proposal_scores",
",",
"gt_boxes",
")",
":",
"box_ious",
"=",
"np_iou",
"(",
"gt_boxes",
",",
"proposals",
")",
"# ng x np",
"box_ious_argsort",
"=",
"np",
".",
"argsort",
"(",
"-",
"box_ious",... | Draw top3 proposals for each gt.
Args:
proposals: NPx4
proposal_scores: NP
gt_boxes: NG | [
"Draw",
"top3",
"proposals",
"for",
"each",
"gt",
".",
"Args",
":",
"proposals",
":",
"NPx4",
"proposal_scores",
":",
"NP",
"gt_boxes",
":",
"NG"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L33-L49 | train |
tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_predictions | def draw_predictions(img, boxes, scores):
"""
Args:
boxes: kx4
scores: kxC
"""
if len(boxes) == 0:
return img
labels = scores.argmax(axis=1)
scores = scores.max(axis=1)
tags = ["{},{:.2f}".format(cfg.DATA.CLASS_NAMES[lb], score) for lb, score in zip(labels, scores)]
... | python | def draw_predictions(img, boxes, scores):
"""
Args:
boxes: kx4
scores: kxC
"""
if len(boxes) == 0:
return img
labels = scores.argmax(axis=1)
scores = scores.max(axis=1)
tags = ["{},{:.2f}".format(cfg.DATA.CLASS_NAMES[lb], score) for lb, score in zip(labels, scores)]
... | [
"def",
"draw_predictions",
"(",
"img",
",",
"boxes",
",",
"scores",
")",
":",
"if",
"len",
"(",
"boxes",
")",
"==",
"0",
":",
"return",
"img",
"labels",
"=",
"scores",
".",
"argmax",
"(",
"axis",
"=",
"1",
")",
"scores",
"=",
"scores",
".",
"max",
... | Args:
boxes: kx4
scores: kxC | [
"Args",
":",
"boxes",
":",
"kx4",
"scores",
":",
"kxC"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L52-L63 | train |
tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_final_outputs | def draw_final_outputs(img, results):
"""
Args:
results: [DetectionResult]
"""
if len(results) == 0:
return img
# Display in largest to smallest order to reduce occlusion
boxes = np.asarray([r.box for r in results])
areas = np_area(boxes)
sorted_inds = np.argsort(-areas)... | python | def draw_final_outputs(img, results):
"""
Args:
results: [DetectionResult]
"""
if len(results) == 0:
return img
# Display in largest to smallest order to reduce occlusion
boxes = np.asarray([r.box for r in results])
areas = np_area(boxes)
sorted_inds = np.argsort(-areas)... | [
"def",
"draw_final_outputs",
"(",
"img",
",",
"results",
")",
":",
"if",
"len",
"(",
"results",
")",
"==",
"0",
":",
"return",
"img",
"# Display in largest to smallest order to reduce occlusion",
"boxes",
"=",
"np",
".",
"asarray",
"(",
"[",
"r",
".",
"box",
... | Args:
results: [DetectionResult] | [
"Args",
":",
"results",
":",
"[",
"DetectionResult",
"]"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L66-L91 | train |
tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_mask | def draw_mask(im, mask, alpha=0.5, color=None):
"""
Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically
"""
if color is None:
color = PALETTE_RGB[np.ran... | python | def draw_mask(im, mask, alpha=0.5, color=None):
"""
Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically
"""
if color is None:
color = PALETTE_RGB[np.ran... | [
"def",
"draw_mask",
"(",
"im",
",",
"mask",
",",
"alpha",
"=",
"0.5",
",",
"color",
"=",
"None",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"PALETTE_RGB",
"[",
"np",
".",
"random",
".",
"choice",
"(",
"len",
"(",
"PALETTE_RGB",
")",
... | Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically | [
"Overlay",
"a",
"mask",
"on",
"top",
"of",
"the",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L94-L108 | train |
tensorpack/tensorpack | tensorpack/dataflow/remote.py | send_dataflow_zmq | def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
"""
Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
... | python | def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
"""
Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
... | [
"def",
"send_dataflow_zmq",
"(",
"df",
",",
"addr",
",",
"hwm",
"=",
"50",
",",
"format",
"=",
"None",
",",
"bind",
"=",
"False",
")",
":",
"assert",
"format",
"in",
"[",
"None",
",",
"'zmq_op'",
",",
"'zmq_ops'",
"]",
"if",
"format",
"is",
"None",
... | Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
addr: a ZMQ socket endpoint.
hwm (int): ZMQ high-water mark (buffe... | [
"Run",
"DataFlow",
"and",
"send",
"data",
"to",
"a",
"ZMQ",
"socket",
"addr",
".",
"It",
"will",
"serialize",
"and",
"send",
"each",
"datapoint",
"to",
"this",
"address",
"with",
"a",
"PUSH",
"socket",
".",
"This",
"function",
"never",
"returns",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/remote.py#L26-L85 | train |
tensorpack/tensorpack | tensorpack/dataflow/remote.py | dump_dataflow_to_process_queue | def dump_dataflow_to_process_queue(df, size, nr_consumer):
"""
Convert a DataFlow to a :class:`multiprocessing.Queue`.
The DataFlow will only be reset in the spawned process.
Args:
df (DataFlow): the DataFlow to dump.
size (int): size of the queue
nr_consumer (int): number of co... | python | def dump_dataflow_to_process_queue(df, size, nr_consumer):
"""
Convert a DataFlow to a :class:`multiprocessing.Queue`.
The DataFlow will only be reset in the spawned process.
Args:
df (DataFlow): the DataFlow to dump.
size (int): size of the queue
nr_consumer (int): number of co... | [
"def",
"dump_dataflow_to_process_queue",
"(",
"df",
",",
"size",
",",
"nr_consumer",
")",
":",
"q",
"=",
"mp",
".",
"Queue",
"(",
"size",
")",
"class",
"EnqueProc",
"(",
"mp",
".",
"Process",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"df",
",",
... | Convert a DataFlow to a :class:`multiprocessing.Queue`.
The DataFlow will only be reset in the spawned process.
Args:
df (DataFlow): the DataFlow to dump.
size (int): size of the queue
nr_consumer (int): number of consumer of the queue.
The producer will add this many of ``D... | [
"Convert",
"a",
"DataFlow",
"to",
"a",
":",
"class",
":",
"multiprocessing",
".",
"Queue",
".",
"The",
"DataFlow",
"will",
"only",
"be",
"reset",
"in",
"the",
"spawned",
"process",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/remote.py#L164-L200 | train |
tensorpack/tensorpack | examples/DeepQNetwork/atari.py | AtariPlayer._grab_raw_image | def _grab_raw_image(self):
"""
:returns: the current 3-channel image
"""
m = self.ale.getScreenRGB()
return m.reshape((self.height, self.width, 3)) | python | def _grab_raw_image(self):
"""
:returns: the current 3-channel image
"""
m = self.ale.getScreenRGB()
return m.reshape((self.height, self.width, 3)) | [
"def",
"_grab_raw_image",
"(",
"self",
")",
":",
"m",
"=",
"self",
".",
"ale",
".",
"getScreenRGB",
"(",
")",
"return",
"m",
".",
"reshape",
"(",
"(",
"self",
".",
"height",
",",
"self",
".",
"width",
",",
"3",
")",
")"
] | :returns: the current 3-channel image | [
":",
"returns",
":",
"the",
"current",
"3",
"-",
"channel",
"image"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/atari.py#L103-L108 | train |
tensorpack/tensorpack | examples/DeepQNetwork/atari.py | AtariPlayer._current_state | def _current_state(self):
"""
:returns: a gray-scale (h, w) uint8 image
"""
ret = self._grab_raw_image()
# max-pooled over the last screen
ret = np.maximum(ret, self.last_raw_screen)
if self.viz:
if isinstance(self.viz, float):
cv2.imsh... | python | def _current_state(self):
"""
:returns: a gray-scale (h, w) uint8 image
"""
ret = self._grab_raw_image()
# max-pooled over the last screen
ret = np.maximum(ret, self.last_raw_screen)
if self.viz:
if isinstance(self.viz, float):
cv2.imsh... | [
"def",
"_current_state",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_grab_raw_image",
"(",
")",
"# max-pooled over the last screen",
"ret",
"=",
"np",
".",
"maximum",
"(",
"ret",
",",
"self",
".",
"last_raw_screen",
")",
"if",
"self",
".",
"viz",
":"... | :returns: a gray-scale (h, w) uint8 image | [
":",
"returns",
":",
"a",
"gray",
"-",
"scale",
"(",
"h",
"w",
")",
"uint8",
"image"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/atari.py#L110-L124 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_box.py | clip_boxes | def clip_boxes(boxes, window, name=None):
"""
Args:
boxes: nx4, xyxy
window: [h, w]
"""
boxes = tf.maximum(boxes, 0.0)
m = tf.tile(tf.reverse(window, [0]), [2]) # (4,)
boxes = tf.minimum(boxes, tf.cast(m, tf.float32), name=name)
return boxes | python | def clip_boxes(boxes, window, name=None):
"""
Args:
boxes: nx4, xyxy
window: [h, w]
"""
boxes = tf.maximum(boxes, 0.0)
m = tf.tile(tf.reverse(window, [0]), [2]) # (4,)
boxes = tf.minimum(boxes, tf.cast(m, tf.float32), name=name)
return boxes | [
"def",
"clip_boxes",
"(",
"boxes",
",",
"window",
",",
"name",
"=",
"None",
")",
":",
"boxes",
"=",
"tf",
".",
"maximum",
"(",
"boxes",
",",
"0.0",
")",
"m",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"reverse",
"(",
"window",
",",
"[",
"0",
"]",
... | Args:
boxes: nx4, xyxy
window: [h, w] | [
"Args",
":",
"boxes",
":",
"nx4",
"xyxy",
"window",
":",
"[",
"h",
"w",
"]"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L14-L23 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_box.py | decode_bbox_target | def decode_bbox_target(box_predictions, anchors):
"""
Args:
box_predictions: (..., 4), logits
anchors: (..., 4), floatbox. Must have the same shape
Returns:
box_decoded: (..., 4), float32. With the same shape.
"""
orig_shape = tf.shape(anchors)
box_pred_txtytwth = tf.res... | python | def decode_bbox_target(box_predictions, anchors):
"""
Args:
box_predictions: (..., 4), logits
anchors: (..., 4), floatbox. Must have the same shape
Returns:
box_decoded: (..., 4), float32. With the same shape.
"""
orig_shape = tf.shape(anchors)
box_pred_txtytwth = tf.res... | [
"def",
"decode_bbox_target",
"(",
"box_predictions",
",",
"anchors",
")",
":",
"orig_shape",
"=",
"tf",
".",
"shape",
"(",
"anchors",
")",
"box_pred_txtytwth",
"=",
"tf",
".",
"reshape",
"(",
"box_predictions",
",",
"(",
"-",
"1",
",",
"2",
",",
"2",
")"... | Args:
box_predictions: (..., 4), logits
anchors: (..., 4), floatbox. Must have the same shape
Returns:
box_decoded: (..., 4), float32. With the same shape. | [
"Args",
":",
"box_predictions",
":",
"(",
"...",
"4",
")",
"logits",
"anchors",
":",
"(",
"...",
"4",
")",
"floatbox",
".",
"Must",
"have",
"the",
"same",
"shape"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L27-L52 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_box.py | encode_bbox_target | def encode_bbox_target(boxes, anchors):
"""
Args:
boxes: (..., 4), float32
anchors: (..., 4), float32
Returns:
box_encoded: (..., 4), float32 with the same shape.
"""
anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2))
anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y... | python | def encode_bbox_target(boxes, anchors):
"""
Args:
boxes: (..., 4), float32
anchors: (..., 4), float32
Returns:
box_encoded: (..., 4), float32 with the same shape.
"""
anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2))
anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y... | [
"def",
"encode_bbox_target",
"(",
"boxes",
",",
"anchors",
")",
":",
"anchors_x1y1x2y2",
"=",
"tf",
".",
"reshape",
"(",
"anchors",
",",
"(",
"-",
"1",
",",
"2",
",",
"2",
")",
")",
"anchors_x1y1",
",",
"anchors_x2y2",
"=",
"tf",
".",
"split",
"(",
"... | Args:
boxes: (..., 4), float32
anchors: (..., 4), float32
Returns:
box_encoded: (..., 4), float32 with the same shape. | [
"Args",
":",
"boxes",
":",
"(",
"...",
"4",
")",
"float32",
"anchors",
":",
"(",
"...",
"4",
")",
"float32"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L56-L79 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_box.py | crop_and_resize | def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size... | python | def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size... | [
"def",
"crop_and_resize",
"(",
"image",
",",
"boxes",
",",
"box_ind",
",",
"crop_size",
",",
"pad_border",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"crop_size",
",",
"int",
")",
",",
"crop_size",
"boxes",
"=",
"tf",
".",
"stop_gradient",
"(",
... | Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size | [
"Aligned",
"version",
"of",
"tf",
".",
"image",
".",
"crop_and_resize",
"following",
"our",
"definition",
"of",
"floating",
"point",
"boxes",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L83-L153 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_box.py | roi_align | def roi_align(featuremap, boxes, resolution):
"""
Args:
featuremap: 1xCxHxW
boxes: Nx4 floatbox
resolution: output spatial resolution
Returns:
NxCx res x res
"""
# sample 4 locations per roi bin
ret = crop_and_resize(
featuremap, boxes,
tf.zeros([... | python | def roi_align(featuremap, boxes, resolution):
"""
Args:
featuremap: 1xCxHxW
boxes: Nx4 floatbox
resolution: output spatial resolution
Returns:
NxCx res x res
"""
# sample 4 locations per roi bin
ret = crop_and_resize(
featuremap, boxes,
tf.zeros([... | [
"def",
"roi_align",
"(",
"featuremap",
",",
"boxes",
",",
"resolution",
")",
":",
"# sample 4 locations per roi bin",
"ret",
"=",
"crop_and_resize",
"(",
"featuremap",
",",
"boxes",
",",
"tf",
".",
"zeros",
"(",
"[",
"tf",
".",
"shape",
"(",
"boxes",
")",
... | Args:
featuremap: 1xCxHxW
boxes: Nx4 floatbox
resolution: output spatial resolution
Returns:
NxCx res x res | [
"Args",
":",
"featuremap",
":",
"1xCxHxW",
"boxes",
":",
"Nx4",
"floatbox",
"resolution",
":",
"output",
"spatial",
"resolution"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L157-L173 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_box.py | RPNAnchors.narrow_to | def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, ... | python | def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, ... | [
"def",
"narrow_to",
"(",
"self",
",",
"featuremap",
")",
":",
"shape2d",
"=",
"tf",
".",
"shape",
"(",
"featuremap",
")",
"[",
"2",
":",
"]",
"# h,w",
"slice3d",
"=",
"tf",
".",
"concat",
"(",
"[",
"shape2d",
",",
"[",
"-",
"1",
"]",
"]",
",",
... | Slice anchors to the spatial size of this featuremap. | [
"Slice",
"anchors",
"to",
"the",
"spatial",
"size",
"of",
"this",
"featuremap",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L189-L199 | train |
tensorpack/tensorpack | examples/CaffeModels/load-cpm.py | colorize | def colorize(img, heatmap):
""" img: bgr, [0,255]
heatmap: [0,1]
"""
heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1]
return img * 0.5 + heatmap * 0.5 | python | def colorize(img, heatmap):
""" img: bgr, [0,255]
heatmap: [0,1]
"""
heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1]
return img * 0.5 + heatmap * 0.5 | [
"def",
"colorize",
"(",
"img",
",",
"heatmap",
")",
":",
"heatmap",
"=",
"viz",
".",
"intensity_to_rgb",
"(",
"heatmap",
",",
"cmap",
"=",
"'jet'",
")",
"[",
":",
",",
":",
",",
":",
":",
"-",
"1",
"]",
"return",
"img",
"*",
"0.5",
"+",
"heatmap"... | img: bgr, [0,255]
heatmap: [0,1] | [
"img",
":",
"bgr",
"[",
"0",
"255",
"]",
"heatmap",
":",
"[",
"0",
"1",
"]"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/CaffeModels/load-cpm.py#L27-L32 | train |
tensorpack/tensorpack | tensorpack/dataflow/imgaug/geometry.py | Rotation._get_augment_params | def _get_augment_params(self, img):
center = img.shape[1::-1] * self._rand_range(
self.center_range[0], self.center_range[1], (2,))
deg = self._rand_range(-self.max_deg, self.max_deg)
if self.step_deg:
deg = deg // self.step_deg * self.step_deg
"""
The cor... | python | def _get_augment_params(self, img):
center = img.shape[1::-1] * self._rand_range(
self.center_range[0], self.center_range[1], (2,))
deg = self._rand_range(-self.max_deg, self.max_deg)
if self.step_deg:
deg = deg // self.step_deg * self.step_deg
"""
The cor... | [
"def",
"_get_augment_params",
"(",
"self",
",",
"img",
")",
":",
"center",
"=",
"img",
".",
"shape",
"[",
"1",
":",
":",
"-",
"1",
"]",
"*",
"self",
".",
"_rand_range",
"(",
"self",
".",
"center_range",
"[",
"0",
"]",
",",
"self",
".",
"center_rang... | The correct center is shape*0.5-0.5. This can be verified by:
SHAPE = 7
arr = np.random.rand(SHAPE, SHAPE)
orig = arr
c = SHAPE * 0.5 - 0.5
c = (c, c)
for k in range(4):
mat = cv2.getRotationMatrix2D(c, 90, 1)
arr = cv2.warpAffine(arr, mat, arr.sh... | [
"The",
"correct",
"center",
"is",
"shape",
"*",
"0",
".",
"5",
"-",
"0",
".",
"5",
".",
"This",
"can",
"be",
"verified",
"by",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/geometry.py#L64-L86 | train |
tensorpack/tensorpack | tensorpack/dataflow/imgaug/geometry.py | RotationAndCropValid.largest_rotated_rect | def largest_rotated_rect(w, h, angle):
"""
Get largest rectangle after rotation.
http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders
"""
angle = angle / 180.0 * math.pi
if w <= 0 or h <= 0:
return 0, 0
width_is_longer =... | python | def largest_rotated_rect(w, h, angle):
"""
Get largest rectangle after rotation.
http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders
"""
angle = angle / 180.0 * math.pi
if w <= 0 or h <= 0:
return 0, 0
width_is_longer =... | [
"def",
"largest_rotated_rect",
"(",
"w",
",",
"h",
",",
"angle",
")",
":",
"angle",
"=",
"angle",
"/",
"180.0",
"*",
"math",
".",
"pi",
"if",
"w",
"<=",
"0",
"or",
"h",
"<=",
"0",
":",
"return",
"0",
",",
"0",
"width_is_longer",
"=",
"w",
">=",
... | Get largest rectangle after rotation.
http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders | [
"Get",
"largest",
"rectangle",
"after",
"rotation",
".",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"16702966",
"/",
"rotate",
"-",
"image",
"-",
"and",
"-",
"crop",
"-",
"out",
"-",
"black",
"-",
"borders"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/geometry.py#L128-L152 | train |
tensorpack/tensorpack | tensorpack/utils/argtools.py | map_arg | def map_arg(**maps):
"""
Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if six.PY2:
argmap = inspect.g... | python | def map_arg(**maps):
"""
Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if six.PY2:
argmap = inspect.g... | [
"def",
"map_arg",
"(",
"*",
"*",
"maps",
")",
":",
"def",
"deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"a... | Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func} | [
"Apply",
"a",
"mapping",
"on",
"certain",
"argument",
"before",
"calling",
"the",
"original",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L19-L40 | train |
tensorpack/tensorpack | tensorpack/utils/argtools.py | graph_memoized | def graph_memoized(func):
"""
Like memoized, but keep one cache per default graph.
"""
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
... | python | def graph_memoized(func):
"""
Like memoized, but keep one cache per default graph.
"""
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
... | [
"def",
"graph_memoized",
"(",
"func",
")",
":",
"# TODO it keeps the graph alive",
"from",
".",
".",
"compat",
"import",
"tfv1",
"GRAPH_ARG_NAME",
"=",
"'__IMPOSSIBLE_NAME_FOR_YOU__'",
"@",
"memoized",
"def",
"func_with_graph_arg",
"(",
"*",
"args",
",",
"*",
"*",
... | Like memoized, but keep one cache per default graph. | [
"Like",
"memoized",
"but",
"keep",
"one",
"cache",
"per",
"default",
"graph",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L49-L69 | train |
tensorpack/tensorpack | tensorpack/utils/argtools.py | memoized_ignoreargs | def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
def wrapper(*args, **kwargs):
if func not in _MEMOIZED_NOARGS:
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res... | python | def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
def wrapper(*args, **kwargs):
if func not in _MEMOIZED_NOARGS:
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res... | [
"def",
"memoized_ignoreargs",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"func",
"not",
"in",
"_MEMOIZED_NOARGS",
":",
"res",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_ME... | A decorator. It performs memoization ignoring the arguments used to call
the function. | [
"A",
"decorator",
".",
"It",
"performs",
"memoization",
"ignoring",
"the",
"arguments",
"used",
"to",
"call",
"the",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L75-L86 | train |
tensorpack/tensorpack | tensorpack/utils/argtools.py | shape2d | def shape2d(a):
"""
Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``.
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
... | python | def shape2d(a):
"""
Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``.
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
... | [
"def",
"shape2d",
"(",
"a",
")",
":",
"if",
"type",
"(",
"a",
")",
"==",
"int",
":",
"return",
"[",
"a",
",",
"a",
"]",
"if",
"isinstance",
"(",
"a",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"assert",
"len",
"(",
"a",
")",
"==",
"2",
... | Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``. | [
"Ensure",
"a",
"2D",
"shape",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L89-L104 | train |
tensorpack/tensorpack | tensorpack/utils/argtools.py | shape4d | def shape4d(a, data_format='NHWC'):
"""
Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format.
"""
s2d = shap... | python | def shape4d(a, data_format='NHWC'):
"""
Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format.
"""
s2d = shap... | [
"def",
"shape4d",
"(",
"a",
",",
"data_format",
"=",
"'NHWC'",
")",
":",
"s2d",
"=",
"shape2d",
"(",
"a",
")",
"if",
"get_data_format",
"(",
"data_format",
",",
"False",
")",
"==",
"'NHWC'",
":",
"return",
"[",
"1",
"]",
"+",
"s2d",
"+",
"[",
"1",
... | Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format. | [
"Ensuer",
"a",
"4D",
"shape",
"to",
"use",
"with",
"4D",
"symbolic",
"functions",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L118-L133 | train |
tensorpack/tensorpack | tensorpack/utils/argtools.py | call_only_once | def call_only_once(func):
"""
Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
# cannot use has... | python | def call_only_once(func):
"""
Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
# cannot use has... | [
"def",
"call_only_once",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"# cannot use hasattr here, because hasattr tries t... | Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception. | [
"Decorate",
"a",
"method",
"or",
"property",
"of",
"a",
"class",
"so",
"that",
"this",
"method",
"can",
"only",
"be",
"called",
"once",
"for",
"every",
"instance",
".",
"Calling",
"it",
"more",
"than",
"once",
"will",
"result",
"in",
"exception",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L149-L178 | train |
tensorpack/tensorpack | tensorpack/utils/argtools.py | memoized_method | def memoized_method(func):
"""
A decorator that performs memoization on methods. It stores the cache on the object instance itself.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
assert func.__name__ in dir(self), "memoized_method can only be used on method!... | python | def memoized_method(func):
"""
A decorator that performs memoization on methods. It stores the cache on the object instance itself.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
assert func.__name__ in dir(self), "memoized_method can only be used on method!... | [
"def",
"memoized_method",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"assert",
"func",
".",
"__name__",
"in",
... | A decorator that performs memoization on methods. It stores the cache on the object instance itself. | [
"A",
"decorator",
"that",
"performs",
"memoization",
"on",
"methods",
".",
"It",
"stores",
"the",
"cache",
"on",
"the",
"object",
"instance",
"itself",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L181-L204 | train |
tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | auto_reuse_variable_scope | def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.co... | python | def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.co... | [
"def",
"auto_reuse_variable_scope",
"(",
"func",
")",
":",
"used_scope",
"=",
"set",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scope",
"=",
"tf",
".",
"get_vari... | A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.conv2d(x, 128, 3)
myfunc(x1) # will inher... | [
"A",
"decorator",
"which",
"automatically",
"reuses",
"the",
"current",
"variable",
"scope",
"if",
"the",
"function",
"has",
"been",
"called",
"with",
"the",
"same",
"variable",
"scope",
"before",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L15-L54 | train |
tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | under_name_scope | def under_name_scope(name_scope=None):
"""
Args:
name_scope(str): the default scope to use. If None, will use the name of the function.
Returns:
A decorator which makes the function run under a name scope.
The name scope is obtained by the following:
1. The 'name_scope' keyw... | python | def under_name_scope(name_scope=None):
"""
Args:
name_scope(str): the default scope to use. If None, will use the name of the function.
Returns:
A decorator which makes the function run under a name scope.
The name scope is obtained by the following:
1. The 'name_scope' keyw... | [
"def",
"under_name_scope",
"(",
"name_scope",
"=",
"None",
")",
":",
"def",
"_impl",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scopename",
"=",
"... | Args:
name_scope(str): the default scope to use. If None, will use the name of the function.
Returns:
A decorator which makes the function run under a name scope.
The name scope is obtained by the following:
1. The 'name_scope' keyword argument when the decorated function is called.... | [
"Args",
":",
"name_scope",
"(",
"str",
")",
":",
"the",
"default",
"scope",
"to",
"use",
".",
"If",
"None",
"will",
"use",
"the",
"name",
"of",
"the",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L57-L96 | train |
tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | under_variable_scope | def under_variable_scope():
"""
Returns:
A decorator which makes the function happen under a variable scope,
which is named by the function itself.
Example:
.. code-block:: python
@under_variable_scope()
def mid_level(x):
with argscope(Conv2D, kernel_shape=... | python | def under_variable_scope():
"""
Returns:
A decorator which makes the function happen under a variable scope,
which is named by the function itself.
Example:
.. code-block:: python
@under_variable_scope()
def mid_level(x):
with argscope(Conv2D, kernel_shape=... | [
"def",
"under_variable_scope",
"(",
")",
":",
"def",
"_impl",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"wit... | Returns:
A decorator which makes the function happen under a variable scope,
which is named by the function itself.
Example:
.. code-block:: python
@under_variable_scope()
def mid_level(x):
with argscope(Conv2D, kernel_shape=3, nl=BNReLU):
x = Conv2... | [
"Returns",
":",
"A",
"decorator",
"which",
"makes",
"the",
"function",
"happen",
"under",
"a",
"variable",
"scope",
"which",
"is",
"named",
"by",
"the",
"function",
"itself",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L99-L125 | train |
tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | cached_name_scope | def cached_name_scope(name, top_level=True):
"""
Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller.
... | python | def cached_name_scope(name, top_level=True):
"""
Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller.
... | [
"def",
"cached_name_scope",
"(",
"name",
",",
"top_level",
"=",
"True",
")",
":",
"if",
"not",
"top_level",
":",
"current_ns",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"get_name_scope",
"(",
")",
"if",
"current_ns",
":",
"name",
"=",
"current_ns... | Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller. | [
"Return",
"a",
"context",
"which",
"either",
"opens",
"and",
"caches",
"a",
"new",
"name",
"scope",
"or",
"reenter",
"an",
"existing",
"one",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L136-L151 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | DataParallelBuilder._check_grad_list | def _check_grad_list(grad_list):
"""
Args:
grad_list: list of list of tuples, shape is Ngpu x Nvar x 2
"""
nvars = [len(k) for k in grad_list]
def basename(x):
return re.sub('tower[0-9]+/', '', x.op.name)
if len(set(nvars)) != 1:
name... | python | def _check_grad_list(grad_list):
"""
Args:
grad_list: list of list of tuples, shape is Ngpu x Nvar x 2
"""
nvars = [len(k) for k in grad_list]
def basename(x):
return re.sub('tower[0-9]+/', '', x.op.name)
if len(set(nvars)) != 1:
name... | [
"def",
"_check_grad_list",
"(",
"grad_list",
")",
":",
"nvars",
"=",
"[",
"len",
"(",
"k",
")",
"for",
"k",
"in",
"grad_list",
"]",
"def",
"basename",
"(",
"x",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'tower[0-9]+/'",
",",
"''",
",",
"x",
".",
... | Args:
grad_list: list of list of tuples, shape is Ngpu x Nvar x 2 | [
"Args",
":",
"grad_list",
":",
"list",
"of",
"list",
"of",
"tuples",
"shape",
"is",
"Ngpu",
"x",
"Nvar",
"x",
"2"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L57-L75 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | DataParallelBuilder.call_for_each_tower | def call_for_each_tower(
towers, func, devices=None, use_vs=None):
"""
Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to ... | python | def call_for_each_tower(
towers, func, devices=None, use_vs=None):
"""
Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to ... | [
"def",
"call_for_each_tower",
"(",
"towers",
",",
"func",
",",
"devices",
"=",
"None",
",",
"use_vs",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"devices",
"is",
"not",
"None",
":",
"assert",
"len",
"(",
"devices",
")",
"==",
"len",
"(",
"t... | Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to be used. By default will use '/gpu:{tower}'
use_vs (list[bool]): list of use_vs to pass... | [
"Run",
"func",
"on",
"all",
"GPUs",
"(",
"towers",
")",
"and",
"return",
"the",
"results",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L78-L118 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | SyncMultiGPUParameterServerBuilder.build | def build(self, grad_list, get_opt_fn):
"""
Reduce the gradients, apply them with the optimizer,
and set self.grads to a list of (g, v), containing the averaged gradients.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed o... | python | def build(self, grad_list, get_opt_fn):
"""
Reduce the gradients, apply them with the optimizer,
and set self.grads to a list of (g, v), containing the averaged gradients.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed o... | [
"def",
"build",
"(",
"self",
",",
"grad_list",
",",
"get_opt_fn",
")",
":",
"assert",
"len",
"(",
"grad_list",
")",
"==",
"len",
"(",
"self",
".",
"towers",
")",
"DataParallelBuilder",
".",
"_check_grad_list",
"(",
"grad_list",
")",
"# debug tower performance ... | Reduce the gradients, apply them with the optimizer,
and set self.grads to a list of (g, v), containing the averaged gradients.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.
get_opt_fn (-> tf.train.Optimizer): ... | [
"Reduce",
"the",
"gradients",
"apply",
"them",
"with",
"the",
"optimizer",
"and",
"set",
"self",
".",
"grads",
"to",
"a",
"list",
"of",
"(",
"g",
"v",
")",
"containing",
"the",
"averaged",
"gradients",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L161-L190 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | SyncMultiGPUReplicatedBuilder.call_for_each_tower | def call_for_each_tower(self, tower_fn):
"""
Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower.
"""
# if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2
... | python | def call_for_each_tower(self, tower_fn):
"""
Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower.
"""
# if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2
... | [
"def",
"call_for_each_tower",
"(",
"self",
",",
"tower_fn",
")",
":",
"# if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2",
"return",
"DataParallelBuilder",
".",
"build_on_towers",
"(",
"self",
".",
"towers",
",",
"tower_fn",
",",
"# use no variable scope ... | Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower. | [
"Call",
"the",
"function",
"tower_fn",
"under",
":",
"class",
":",
"TowerContext",
"for",
"each",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L214-L226 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | SyncMultiGPUReplicatedBuilder.build | def build(self, grad_list, get_opt_fn):
"""
Reduce the gradients, apply them with the optimizer,
and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. ... | python | def build(self, grad_list, get_opt_fn):
"""
Reduce the gradients, apply them with the optimizer,
and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. ... | [
"def",
"build",
"(",
"self",
",",
"grad_list",
",",
"get_opt_fn",
")",
":",
"assert",
"len",
"(",
"grad_list",
")",
"==",
"len",
"(",
"self",
".",
"towers",
")",
"raw_devices",
"=",
"[",
"'/gpu:{}'",
".",
"format",
"(",
"k",
")",
"for",
"k",
"in",
... | Reduce the gradients, apply them with the optimizer,
and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.
get_... | [
"Reduce",
"the",
"gradients",
"apply",
"them",
"with",
"the",
"optimizer",
"and",
"set",
"self",
".",
"grads",
"to",
"#GPU",
"number",
"of",
"lists",
"of",
"(",
"g",
"v",
")",
"containing",
"the",
"all",
"-",
"reduced",
"gradients",
"on",
"each",
"device... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L228-L305 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | SyncMultiGPUReplicatedBuilder.get_post_init_ops | def get_post_init_ops():
"""
Copy values of variables on GPU 0 to other GPUs.
"""
# literally all variables, because it's better to sync optimizer-internal variables as well
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = dict([(v.name, v) for v in a... | python | def get_post_init_ops():
"""
Copy values of variables on GPU 0 to other GPUs.
"""
# literally all variables, because it's better to sync optimizer-internal variables as well
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = dict([(v.name, v) for v in a... | [
"def",
"get_post_init_ops",
"(",
")",
":",
"# literally all variables, because it's better to sync optimizer-internal variables as well",
"all_vars",
"=",
"tf",
".",
"global_variables",
"(",
")",
"+",
"tf",
".",
"local_variables",
"(",
")",
"var_by_name",
"=",
"dict",
"("... | Copy values of variables on GPU 0 to other GPUs. | [
"Copy",
"values",
"of",
"variables",
"on",
"GPU",
"0",
"to",
"other",
"GPUs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L309-L349 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | AsyncMultiGPUBuilder.call_for_each_tower | def call_for_each_tower(self, tower_fn):
"""
Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower.
"""
ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu'
raw_devic... | python | def call_for_each_tower(self, tower_fn):
"""
Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower.
"""
ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu'
raw_devic... | [
"def",
"call_for_each_tower",
"(",
"self",
",",
"tower_fn",
")",
":",
"ps_device",
"=",
"'cpu'",
"if",
"len",
"(",
"self",
".",
"towers",
")",
">=",
"4",
"else",
"'gpu'",
"raw_devices",
"=",
"[",
"'/gpu:{}'",
".",
"format",
"(",
"k",
")",
"for",
"k",
... | Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower. | [
"Call",
"the",
"function",
"tower_fn",
"under",
":",
"class",
":",
"TowerContext",
"for",
"each",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L369-L385 | train |
tensorpack/tensorpack | tensorpack/graph_builder/training.py | AsyncMultiGPUBuilder.build | def build(self, grad_list, get_opt_fn):
"""
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
tf.Operation: the t... | python | def build(self, grad_list, get_opt_fn):
"""
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
tf.Operation: the t... | [
"def",
"build",
"(",
"self",
",",
"grad_list",
",",
"get_opt_fn",
")",
":",
"assert",
"len",
"(",
"grad_list",
")",
"==",
"len",
"(",
"self",
".",
"towers",
")",
"DataParallelBuilder",
".",
"_check_grad_list",
"(",
"grad_list",
")",
"if",
"self",
".",
"_... | Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
tf.Operation: the training op | [
"Args",
":",
"grad_list",
"(",
"[[",
"(",
"grad",
"var",
")",
"...",
"]",
"...",
"]",
")",
":",
"#GPU",
"lists",
"to",
"be",
"reduced",
".",
"Each",
"is",
"the",
"gradients",
"computed",
"on",
"each",
"GPU",
".",
"get_opt_fn",
"(",
"-",
">",
"tf",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L387-L416 | train |
tensorpack/tensorpack | tensorpack/utils/utils.py | humanize_time_delta | def humanize_time_delta(sec):
"""Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) ... | python | def humanize_time_delta(sec):
"""Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) ... | [
"def",
"humanize_time_delta",
"(",
"sec",
")",
":",
"if",
"sec",
"<",
"0",
":",
"logger",
".",
"warn",
"(",
"\"humanize_time_delta() obtains negative seconds!\"",
")",
"return",
"\"{:.3g} seconds\"",
".",
"format",
"(",
"sec",
")",
"if",
"sec",
"==",
"0",
":",... | Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) # 1 second
print(h... | [
"Humanize",
"timedelta",
"given",
"in",
"seconds"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L26-L65 | train |
tensorpack/tensorpack | tensorpack/utils/utils.py | change_env | def change_env(name, val):
"""
Args:
name(str), val(str):
Returns:
a context where the environment variable ``name`` being set to
``val``. It will be set back after the context exits.
"""
oldval = os.environ.get(name, None)
os.environ[name] = val
yield
if oldval ... | python | def change_env(name, val):
"""
Args:
name(str), val(str):
Returns:
a context where the environment variable ``name`` being set to
``val``. It will be set back after the context exits.
"""
oldval = os.environ.get(name, None)
os.environ[name] = val
yield
if oldval ... | [
"def",
"change_env",
"(",
"name",
",",
"val",
")",
":",
"oldval",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"None",
")",
"os",
".",
"environ",
"[",
"name",
"]",
"=",
"val",
"yield",
"if",
"oldval",
"is",
"None",
":",
"del",
"os",
... | Args:
name(str), val(str):
Returns:
a context where the environment variable ``name`` being set to
``val``. It will be set back after the context exits. | [
"Args",
":",
"name",
"(",
"str",
")",
"val",
"(",
"str",
")",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L69-L84 | train |
tensorpack/tensorpack | tensorpack/utils/utils.py | get_rng | def get_rng(obj=None):
"""
Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG.
"""
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 42949... | python | def get_rng(obj=None):
"""
Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG.
"""
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 42949... | [
"def",
"get_rng",
"(",
"obj",
"=",
"None",
")",
":",
"seed",
"=",
"(",
"id",
"(",
"obj",
")",
"+",
"os",
".",
"getpid",
"(",
")",
"+",
"int",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S%f\"",
")",
")",
")",
"%",... | Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG. | [
"Get",
"a",
"good",
"RNG",
"seeded",
"with",
"time",
"pid",
"and",
"the",
"object",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L117-L130 | train |
tensorpack/tensorpack | tensorpack/utils/utils.py | execute_only_once | def execute_only_once():
"""
Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if ex... | python | def execute_only_once():
"""
Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if ex... | [
"def",
"execute_only_once",
"(",
")",
":",
"f",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"ident",
"=",
"(",
"f",
".",
"f_code",
".",
"co_filename",
",",
"f",
".",
"f_lineno",
")",
"if",
"ident",
"in",
"_EXECUTE_HISTORY",
":",
"retu... | Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if execute_only_once():
# ... | [
"Each",
"called",
"in",
"the",
"code",
"to",
"this",
"function",
"is",
"guaranteed",
"to",
"return",
"True",
"the",
"first",
"time",
"and",
"False",
"afterwards",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L136-L155 | train |
tensorpack/tensorpack | tensorpack/utils/utils.py | get_tqdm_kwargs | def get_tqdm_kwargs(**kwargs):
"""
Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict:
"""
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_f... | python | def get_tqdm_kwargs(**kwargs):
"""
Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict:
"""
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_f... | [
"def",
"get_tqdm_kwargs",
"(",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"dict",
"(",
"smoothing",
"=",
"0.5",
",",
"dynamic_ncols",
"=",
"True",
",",
"ascii",
"=",
"True",
",",
"bar_format",
"=",
"'{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_... | Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict: | [
"Return",
"default",
"arguments",
"to",
"be",
"used",
"with",
"tqdm",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L190-L214 | train |
tensorpack/tensorpack | tensorpack/utils/utils.py | find_library_full_path | def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_l... | python | def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_l... | [
"def",
"find_library_full_path",
"(",
"name",
")",
":",
"from",
"ctypes",
".",
"util",
"import",
"find_library",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
"and",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"# on Mac, ctypes already returns full path",
"retu... | Similar to `from ctypes.util import find_library`, but try
to return full path if possible. | [
"Similar",
"to",
"from",
"ctypes",
".",
"util",
"import",
"find_library",
"but",
"try",
"to",
"return",
"full",
"path",
"if",
"possible",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L223-L293 | train |
tensorpack/tensorpack | tensorpack/dataflow/serialize.py | LMDBSerializer.save | def save(df, path, write_frequency=5000):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output path. Either a directory or an lmdb file.
write_frequency (int): the frequency to write back data to disk.
"""
assert isinstance(df, DataFl... | python | def save(df, path, write_frequency=5000):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output path. Either a directory or an lmdb file.
write_frequency (int): the frequency to write back data to disk.
"""
assert isinstance(df, DataFl... | [
"def",
"save",
"(",
"df",
",",
"path",
",",
"write_frequency",
"=",
"5000",
")",
":",
"assert",
"isinstance",
"(",
"df",
",",
"DataFlow",
")",
",",
"type",
"(",
"df",
")",
"isdir",
"=",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"if",
"is... | Args:
df (DataFlow): the DataFlow to serialize.
path (str): output path. Either a directory or an lmdb file.
write_frequency (int): the frequency to write back data to disk. | [
"Args",
":",
"df",
"(",
"DataFlow",
")",
":",
"the",
"DataFlow",
"to",
"serialize",
".",
"path",
"(",
"str",
")",
":",
"output",
"path",
".",
"Either",
"a",
"directory",
"or",
"an",
"lmdb",
"file",
".",
"write_frequency",
"(",
"int",
")",
":",
"the",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L37-L74 | train |
tensorpack/tensorpack | tensorpack/dataflow/serialize.py | LMDBSerializer.load | def load(path, shuffle=True):
"""
Note:
If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader
and run deserialization as a mapper in parallel.
"""
df = LMDBData(path, shuffle=shuffle)
return MapData(df, lambda dp: l... | python | def load(path, shuffle=True):
"""
Note:
If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader
and run deserialization as a mapper in parallel.
"""
df = LMDBData(path, shuffle=shuffle)
return MapData(df, lambda dp: l... | [
"def",
"load",
"(",
"path",
",",
"shuffle",
"=",
"True",
")",
":",
"df",
"=",
"LMDBData",
"(",
"path",
",",
"shuffle",
"=",
"shuffle",
")",
"return",
"MapData",
"(",
"df",
",",
"lambda",
"dp",
":",
"loads",
"(",
"dp",
"[",
"1",
"]",
")",
")"
] | Note:
If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader
and run deserialization as a mapper in parallel. | [
"Note",
":",
"If",
"you",
"found",
"deserialization",
"being",
"the",
"bottleneck",
"you",
"can",
"use",
":",
"class",
":",
"LMDBData",
"as",
"the",
"reader",
"and",
"run",
"deserialization",
"as",
"a",
"mapper",
"in",
"parallel",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L77-L84 | train |
tensorpack/tensorpack | tensorpack/dataflow/serialize.py | NumpySerializer.save | def save(df, path):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output npz file.
"""
buffer = []
size = _reset_df_and_get_size(df)
with get_tqdm(total=size) as pbar:
for dp in df:
buffer.append(dp)
... | python | def save(df, path):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output npz file.
"""
buffer = []
size = _reset_df_and_get_size(df)
with get_tqdm(total=size) as pbar:
for dp in df:
buffer.append(dp)
... | [
"def",
"save",
"(",
"df",
",",
"path",
")",
":",
"buffer",
"=",
"[",
"]",
"size",
"=",
"_reset_df_and_get_size",
"(",
"df",
")",
"with",
"get_tqdm",
"(",
"total",
"=",
"size",
")",
"as",
"pbar",
":",
"for",
"dp",
"in",
"df",
":",
"buffer",
".",
"... | Args:
df (DataFlow): the DataFlow to serialize.
path (str): output npz file. | [
"Args",
":",
"df",
"(",
"DataFlow",
")",
":",
"the",
"DataFlow",
"to",
"serialize",
".",
"path",
"(",
"str",
")",
":",
"output",
"npz",
"file",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L95-L107 | train |
tensorpack/tensorpack | tensorpack/dataflow/serialize.py | TFRecordSerializer.save | def save(df, path):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output tfrecord file.
"""
if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack':
def _dumps(dp):
return dumps(dp)
else:
... | python | def save(df, path):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output tfrecord file.
"""
if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack':
def _dumps(dp):
return dumps(dp)
else:
... | [
"def",
"save",
"(",
"df",
",",
"path",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TENSORPACK_COMPATIBLE_SERIALIZE'",
",",
"'msgpack'",
")",
"==",
"'msgpack'",
":",
"def",
"_dumps",
"(",
"dp",
")",
":",
"return",
"dumps",
"(",
"dp",
")",
... | Args:
df (DataFlow): the DataFlow to serialize.
path (str): output tfrecord file. | [
"Args",
":",
"df",
"(",
"DataFlow",
")",
":",
"the",
"DataFlow",
"to",
"serialize",
".",
"path",
"(",
"str",
")",
":",
"output",
"tfrecord",
"file",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L125-L142 | train |
tensorpack/tensorpack | tensorpack/dataflow/serialize.py | TFRecordSerializer.load | def load(path, size=None):
"""
Args:
size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`.
It's needed because this metadata is not stored in the TFRecord file.
"""
gen = tf.python_io.tf_record_iterator(path)
... | python | def load(path, size=None):
"""
Args:
size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`.
It's needed because this metadata is not stored in the TFRecord file.
"""
gen = tf.python_io.tf_record_iterator(path)
... | [
"def",
"load",
"(",
"path",
",",
"size",
"=",
"None",
")",
":",
"gen",
"=",
"tf",
".",
"python_io",
".",
"tf_record_iterator",
"(",
"path",
")",
"ds",
"=",
"DataFromGenerator",
"(",
"gen",
")",
"ds",
"=",
"MapData",
"(",
"ds",
",",
"loads",
")",
"i... | Args:
size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`.
It's needed because this metadata is not stored in the TFRecord file. | [
"Args",
":",
"size",
"(",
"int",
")",
":",
"total",
"number",
"of",
"records",
".",
"If",
"not",
"provided",
"the",
"returned",
"dataflow",
"will",
"have",
"no",
"__len__",
"()",
".",
"It",
"s",
"needed",
"because",
"this",
"metadata",
"is",
"not",
"st... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L145-L156 | train |
tensorpack/tensorpack | tensorpack/dataflow/serialize.py | HDF5Serializer.save | def save(df, path, data_paths):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output hdf5 file.
data_paths (list[str]): list of h5 paths. It should have the same
length as each datapoint, and each path should correspond to one
... | python | def save(df, path, data_paths):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output hdf5 file.
data_paths (list[str]): list of h5 paths. It should have the same
length as each datapoint, and each path should correspond to one
... | [
"def",
"save",
"(",
"df",
",",
"path",
",",
"data_paths",
")",
":",
"size",
"=",
"_reset_df_and_get_size",
"(",
"df",
")",
"buffer",
"=",
"defaultdict",
"(",
"list",
")",
"with",
"get_tqdm",
"(",
"total",
"=",
"size",
")",
"as",
"pbar",
":",
"for",
"... | Args:
df (DataFlow): the DataFlow to serialize.
path (str): output hdf5 file.
data_paths (list[str]): list of h5 paths. It should have the same
length as each datapoint, and each path should correspond to one
component of the datapoint. | [
"Args",
":",
"df",
"(",
"DataFlow",
")",
":",
"the",
"DataFlow",
"to",
"serialize",
".",
"path",
"(",
"str",
")",
":",
"output",
"hdf5",
"file",
".",
"data_paths",
"(",
"list",
"[",
"str",
"]",
")",
":",
"list",
"of",
"h5",
"paths",
".",
"It",
"s... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/serialize.py#L167-L189 | train |
tensorpack/tensorpack | tensorpack/contrib/keras.py | setup_keras_trainer | def setup_keras_trainer(
trainer, get_model,
input_signature, target_signature,
input, optimizer, loss, metrics):
"""
Args:
trainer (SingleCostTrainer):
get_model (input1, input2, ... -> tf.keras.Model):
A function which takes tensors, builds and returns a Ker... | python | def setup_keras_trainer(
trainer, get_model,
input_signature, target_signature,
input, optimizer, loss, metrics):
"""
Args:
trainer (SingleCostTrainer):
get_model (input1, input2, ... -> tf.keras.Model):
A function which takes tensors, builds and returns a Ker... | [
"def",
"setup_keras_trainer",
"(",
"trainer",
",",
"get_model",
",",
"input_signature",
",",
"target_signature",
",",
"input",
",",
"optimizer",
",",
"loss",
",",
"metrics",
")",
":",
"assert",
"isinstance",
"(",
"optimizer",
",",
"tf",
".",
"train",
".",
"O... | Args:
trainer (SingleCostTrainer):
get_model (input1, input2, ... -> tf.keras.Model):
A function which takes tensors, builds and returns a Keras model.
It will be part of the tower function.
input (InputSource):
optimizer (tf.train.Optimizer):
loss, metric... | [
"Args",
":",
"trainer",
"(",
"SingleCostTrainer",
")",
":",
"get_model",
"(",
"input1",
"input2",
"...",
"-",
">",
"tf",
".",
"keras",
".",
"Model",
")",
":",
"A",
"function",
"which",
"takes",
"tensors",
"builds",
"and",
"returns",
"a",
"Keras",
"model"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/contrib/keras.py#L142-L220 | train |
tensorpack/tensorpack | tensorpack/contrib/keras.py | KerasModel.compile | def compile(self, optimizer, loss, metrics=None):
"""
Args:
optimizer (tf.train.Optimizer):
loss, metrics: string or list of strings
"""
if isinstance(loss, six.string_types):
loss = [loss]
if metrics is None:
metrics = []
i... | python | def compile(self, optimizer, loss, metrics=None):
"""
Args:
optimizer (tf.train.Optimizer):
loss, metrics: string or list of strings
"""
if isinstance(loss, six.string_types):
loss = [loss]
if metrics is None:
metrics = []
i... | [
"def",
"compile",
"(",
"self",
",",
"optimizer",
",",
"loss",
",",
"metrics",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"loss",
",",
"six",
".",
"string_types",
")",
":",
"loss",
"=",
"[",
"loss",
"]",
"if",
"metrics",
"is",
"None",
":",
"met... | Args:
optimizer (tf.train.Optimizer):
loss, metrics: string or list of strings | [
"Args",
":",
"optimizer",
"(",
"tf",
".",
"train",
".",
"Optimizer",
")",
":",
"loss",
"metrics",
":",
"string",
"or",
"list",
"of",
"strings"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/contrib/keras.py#L259-L280 | train |
tensorpack/tensorpack | tensorpack/contrib/keras.py | KerasModel.fit | def fit(self, validation_data=None, **kwargs):
"""
Args:
validation_data (DataFlow or InputSource): to be used for inference.
The inference callback is added as the first in the callback list.
If you need to use it in a different order, please write it in the ... | python | def fit(self, validation_data=None, **kwargs):
"""
Args:
validation_data (DataFlow or InputSource): to be used for inference.
The inference callback is added as the first in the callback list.
If you need to use it in a different order, please write it in the ... | [
"def",
"fit",
"(",
"self",
",",
"validation_data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"callbacks",
"=",
"kwargs",
".",
"pop",
"(",
"'callbacks'",
",",
"[",
"]",
")",
"if",
"validation_data",
"is",
"not",
"None",
":",
"# There is no way to gu... | Args:
validation_data (DataFlow or InputSource): to be used for inference.
The inference callback is added as the first in the callback list.
If you need to use it in a different order, please write it in the callback list manually.
kwargs: same arguments as :meth... | [
"Args",
":",
"validation_data",
"(",
"DataFlow",
"or",
"InputSource",
")",
":",
"to",
"be",
"used",
"for",
"inference",
".",
"The",
"inference",
"callback",
"is",
"added",
"as",
"the",
"first",
"in",
"the",
"callback",
"list",
".",
"If",
"you",
"need",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/contrib/keras.py#L282-L297 | train |
tensorpack/tensorpack | examples/DoReFa-Net/dorefa.py | get_dorefa | def get_dorefa(bitW, bitA, bitG):
"""
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
"""
def quantize(x, k):
n = float(2 ** k - 1)
@tf.custom_gradient
def _quantize(x):
return tf.round(x * n) / n, lambda dy: dy... | python | def get_dorefa(bitW, bitA, bitG):
"""
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
"""
def quantize(x, k):
n = float(2 ** k - 1)
@tf.custom_gradient
def _quantize(x):
return tf.round(x * n) / n, lambda dy: dy... | [
"def",
"get_dorefa",
"(",
"bitW",
",",
"bitA",
",",
"bitG",
")",
":",
"def",
"quantize",
"(",
"x",
",",
"k",
")",
":",
"n",
"=",
"float",
"(",
"2",
"**",
"k",
"-",
"1",
")",
"@",
"tf",
".",
"custom_gradient",
"def",
"_quantize",
"(",
"x",
")",
... | Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively | [
"Return",
"the",
"three",
"quantization",
"functions",
"fw",
"fa",
"fg",
"for",
"weights",
"activations",
"and",
"gradients",
"respectively"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DoReFa-Net/dorefa.py#L8-L64 | train |
tensorpack/tensorpack | examples/DoReFa-Net/dorefa.py | ternarize | def ternarize(x, thresh=0.05):
"""
Implemented Trained Ternary Quantization:
https://arxiv.org/abs/1612.01064
Code modified from the authors' at:
https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py
"""
shape = x.get_shape()
thre_x = tf.stop_gradient(tf.redu... | python | def ternarize(x, thresh=0.05):
"""
Implemented Trained Ternary Quantization:
https://arxiv.org/abs/1612.01064
Code modified from the authors' at:
https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py
"""
shape = x.get_shape()
thre_x = tf.stop_gradient(tf.redu... | [
"def",
"ternarize",
"(",
"x",
",",
"thresh",
"=",
"0.05",
")",
":",
"shape",
"=",
"x",
".",
"get_shape",
"(",
")",
"thre_x",
"=",
"tf",
".",
"stop_gradient",
"(",
"tf",
".",
"reduce_max",
"(",
"tf",
".",
"abs",
"(",
"x",
")",
")",
"*",
"thresh",
... | Implemented Trained Ternary Quantization:
https://arxiv.org/abs/1612.01064
Code modified from the authors' at:
https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py | [
"Implemented",
"Trained",
"Ternary",
"Quantization",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1612",
".",
"01064"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DoReFa-Net/dorefa.py#L67-L99 | train |
tensorpack/tensorpack | tensorpack/utils/viz.py | interactive_imshow | def interactive_imshow(img, lclick_cb=None, rclick_cb=None, **kwargs):
"""
Args:
img (np.ndarray): an image (expect BGR) to show.
lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event.
kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to
... | python | def interactive_imshow(img, lclick_cb=None, rclick_cb=None, **kwargs):
"""
Args:
img (np.ndarray): an image (expect BGR) to show.
lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event.
kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to
... | [
"def",
"interactive_imshow",
"(",
"img",
",",
"lclick_cb",
"=",
"None",
",",
"rclick_cb",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"'tensorpack_viz_window'",
"cv2",
".",
"imshow",
"(",
"name",
",",
"img",
")",
"def",
"mouse_cb",
"(",
... | Args:
img (np.ndarray): an image (expect BGR) to show.
lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event.
kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to
specify a callback ``func(img)`` for keypress.
Some existing keypress event... | [
"Args",
":",
"img",
"(",
"np",
".",
"ndarray",
")",
":",
"an",
"image",
"(",
"expect",
"BGR",
")",
"to",
"show",
".",
"lclick_cb",
"rclick_cb",
":",
"a",
"callback",
"func",
"(",
"img",
"x",
"y",
")",
"for",
"left",
"/",
"right",
"click",
"event",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L25-L66 | train |
tensorpack/tensorpack | tensorpack/utils/viz.py | stack_patches | def stack_patches(
patch_list, nr_row, nr_col, border=None,
pad=False, bgcolor=255, viz=False, lclick_cb=None):
"""
Stacked patches into grid, to produce visualizations like the following:
.. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.... | python | def stack_patches(
patch_list, nr_row, nr_col, border=None,
pad=False, bgcolor=255, viz=False, lclick_cb=None):
"""
Stacked patches into grid, to produce visualizations like the following:
.. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.... | [
"def",
"stack_patches",
"(",
"patch_list",
",",
"nr_row",
",",
"nr_col",
",",
"border",
"=",
"None",
",",
"pad",
"=",
"False",
",",
"bgcolor",
"=",
"255",
",",
"viz",
"=",
"False",
",",
"lclick_cb",
"=",
"None",
")",
":",
"if",
"pad",
":",
"patch_lis... | Stacked patches into grid, to produce visualizations like the following:
.. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.jpg
Args:
patch_list(list[ndarray] or ndarray): NHW or NHWC images in [0,255].
nr_row(int), nr_col(int): rows and cols ... | [
"Stacked",
"patches",
"into",
"grid",
"to",
"produce",
"visualizations",
"like",
"the",
"following",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L157-L203 | train |
tensorpack/tensorpack | tensorpack/utils/viz.py | gen_stack_patches | def gen_stack_patches(patch_list,
nr_row=None, nr_col=None, border=None,
max_width=1000, max_height=1000,
bgcolor=255, viz=False, lclick_cb=None):
"""
Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer lis... | python | def gen_stack_patches(patch_list,
nr_row=None, nr_col=None, border=None,
max_width=1000, max_height=1000,
bgcolor=255, viz=False, lclick_cb=None):
"""
Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer lis... | [
"def",
"gen_stack_patches",
"(",
"patch_list",
",",
"nr_row",
"=",
"None",
",",
"nr_col",
"=",
"None",
",",
"border",
"=",
"None",
",",
"max_width",
"=",
"1000",
",",
"max_height",
"=",
"1000",
",",
"bgcolor",
"=",
"255",
",",
"viz",
"=",
"False",
",",... | Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer list and yields stacked results one by one.
For example, if ``patch_list`` contains 1000 images and ``nr_row==nr_col==10``,
this generator yields 10 stacked images.
Args:
nr_row(int), nr_col(int): rows and c... | [
"Similar",
"to",
":",
"func",
":",
"stack_patches",
"but",
"with",
"a",
"generator",
"interface",
".",
"It",
"takes",
"a",
"much",
"-",
"longer",
"list",
"and",
"yields",
"stacked",
"results",
"one",
"by",
"one",
".",
"For",
"example",
"if",
"patch_list",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L206-L262 | train |
tensorpack/tensorpack | tensorpack/utils/viz.py | dump_dataflow_images | def dump_dataflow_images(df, index=0, batched=True,
number=1000, output_dir=None,
scale=1, resize=None, viz=None,
flipRGB=False):
"""
Dump or visualize images of a :class:`DataFlow`.
Args:
df (DataFlow): the DataFlow.
... | python | def dump_dataflow_images(df, index=0, batched=True,
number=1000, output_dir=None,
scale=1, resize=None, viz=None,
flipRGB=False):
"""
Dump or visualize images of a :class:`DataFlow`.
Args:
df (DataFlow): the DataFlow.
... | [
"def",
"dump_dataflow_images",
"(",
"df",
",",
"index",
"=",
"0",
",",
"batched",
"=",
"True",
",",
"number",
"=",
"1000",
",",
"output_dir",
"=",
"None",
",",
"scale",
"=",
"1",
",",
"resize",
"=",
"None",
",",
"viz",
"=",
"None",
",",
"flipRGB",
... | Dump or visualize images of a :class:`DataFlow`.
Args:
df (DataFlow): the DataFlow.
index (int): the index of the image component.
batched (bool): whether the component contains batched images (NHW or
NHWC) or not (HW or HWC).
number (int): how many datapoint to take fro... | [
"Dump",
"or",
"visualize",
"images",
"of",
"a",
":",
"class",
":",
"DataFlow",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L265-L322 | train |
tensorpack/tensorpack | tensorpack/utils/viz.py | intensity_to_rgb | def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False):
"""
Convert a 1-channel matrix of intensities to an RGB image employing a colormap.
This function requires matplotlib. See `matplotlib colormaps
<http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a
list of availab... | python | def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False):
"""
Convert a 1-channel matrix of intensities to an RGB image employing a colormap.
This function requires matplotlib. See `matplotlib colormaps
<http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a
list of availab... | [
"def",
"intensity_to_rgb",
"(",
"intensity",
",",
"cmap",
"=",
"'cubehelix'",
",",
"normalize",
"=",
"False",
")",
":",
"assert",
"intensity",
".",
"ndim",
"==",
"2",
",",
"intensity",
".",
"shape",
"intensity",
"=",
"intensity",
".",
"astype",
"(",
"\"flo... | Convert a 1-channel matrix of intensities to an RGB image employing a colormap.
This function requires matplotlib. See `matplotlib colormaps
<http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a
list of available colormap.
Args:
intensity (np.ndarray): array of intensities suc... | [
"Convert",
"a",
"1",
"-",
"channel",
"matrix",
"of",
"intensities",
"to",
"an",
"RGB",
"image",
"employing",
"a",
"colormap",
".",
"This",
"function",
"requires",
"matplotlib",
".",
"See",
"matplotlib",
"colormaps",
"<http",
":",
"//",
"matplotlib",
".",
"or... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L325-L350 | train |
tensorpack/tensorpack | tensorpack/utils/viz.py | draw_text | def draw_text(img, pos, text, color, font_scale=0.4):
"""
Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255]
"""
img = img.astype(np.uint8)
x0, y0 = int(pos[0]), ... | python | def draw_text(img, pos, text, color, font_scale=0.4):
"""
Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255]
"""
img = img.astype(np.uint8)
x0, y0 = int(pos[0]), ... | [
"def",
"draw_text",
"(",
"img",
",",
"pos",
",",
"text",
",",
"color",
",",
"font_scale",
"=",
"0.4",
")",
":",
"img",
"=",
"img",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"x0",
",",
"y0",
"=",
"int",
"(",
"pos",
"[",
"0",
"]",
")",
",",
... | Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255] | [
"Draw",
"text",
"on",
"an",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L353-L379 | train |
tensorpack/tensorpack | tensorpack/utils/viz.py | draw_boxes | def draw_boxes(im, boxes, labels=None, color=None):
"""
Args:
im (np.ndarray): a BGR image in range [0,255]. It will not be modified.
boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2].
labels: (list[str] or None)
color: a 3-tuple BGR color (in rang... | python | def draw_boxes(im, boxes, labels=None, color=None):
"""
Args:
im (np.ndarray): a BGR image in range [0,255]. It will not be modified.
boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2].
labels: (list[str] or None)
color: a 3-tuple BGR color (in rang... | [
"def",
"draw_boxes",
"(",
"im",
",",
"boxes",
",",
"labels",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"boxes",
"=",
"np",
".",
"asarray",
"(",
"boxes",
",",
"dtype",
"=",
"'int32'",
")",
"if",
"labels",
"is",
"not",
"None",
":",
"assert",
... | Args:
im (np.ndarray): a BGR image in range [0,255]. It will not be modified.
boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2].
labels: (list[str] or None)
color: a 3-tuple BGR color (in range [0, 255])
Returns:
np.ndarray: a new image. | [
"Args",
":",
"im",
"(",
"np",
".",
"ndarray",
")",
":",
"a",
"BGR",
"image",
"in",
"range",
"[",
"0",
"255",
"]",
".",
"It",
"will",
"not",
"be",
"modified",
".",
"boxes",
"(",
"np",
".",
"ndarray",
")",
":",
"a",
"numpy",
"array",
"of",
"shape... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L382-L415 | train |
tensorpack/tensorpack | tensorpack/models/shapes.py | ConcatWith | def ConcatWith(x, tensor, dim):
"""
A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`.
Args:
x (tf.Tensor): input
tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x.
x will be at the beginning
dim (int): the dimension along whi... | python | def ConcatWith(x, tensor, dim):
"""
A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`.
Args:
x (tf.Tensor): input
tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x.
x will be at the beginning
dim (int): the dimension along whi... | [
"def",
"ConcatWith",
"(",
"x",
",",
"tensor",
",",
"dim",
")",
":",
"if",
"type",
"(",
"tensor",
")",
"!=",
"list",
":",
"tensor",
"=",
"[",
"tensor",
"]",
"return",
"tf",
".",
"concat",
"(",
"[",
"x",
"]",
"+",
"tensor",
",",
"dim",
")"
] | A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`.
Args:
x (tf.Tensor): input
tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x.
x will be at the beginning
dim (int): the dimension along which to concatenate
Returns:
tf.T... | [
"A",
"wrapper",
"around",
"tf",
".",
"concat",
"to",
"cooperate",
"with",
":",
"class",
":",
"LinearWrap",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/shapes.py#L13-L28 | train |
tensorpack/tensorpack | examples/FasterRCNN/common.py | point8_to_box | def point8_to_box(points):
"""
Args:
points: (nx4)x2
Returns:
nx4 boxes (x1y1x2y2)
"""
p = points.reshape((-1, 4, 2))
minxy = p.min(axis=1) # nx2
maxxy = p.max(axis=1) # nx2
return np.concatenate((minxy, maxxy), axis=1) | python | def point8_to_box(points):
"""
Args:
points: (nx4)x2
Returns:
nx4 boxes (x1y1x2y2)
"""
p = points.reshape((-1, 4, 2))
minxy = p.min(axis=1) # nx2
maxxy = p.max(axis=1) # nx2
return np.concatenate((minxy, maxxy), axis=1) | [
"def",
"point8_to_box",
"(",
"points",
")",
":",
"p",
"=",
"points",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"4",
",",
"2",
")",
")",
"minxy",
"=",
"p",
".",
"min",
"(",
"axis",
"=",
"1",
")",
"# nx2",
"maxxy",
"=",
"p",
".",
"max",
"(",
"... | Args:
points: (nx4)x2
Returns:
nx4 boxes (x1y1x2y2) | [
"Args",
":",
"points",
":",
"(",
"nx4",
")",
"x2",
"Returns",
":",
"nx4",
"boxes",
"(",
"x1y1x2y2",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L78-L88 | train |
tensorpack/tensorpack | examples/FasterRCNN/common.py | segmentation_to_mask | def segmentation_to_mask(polys, height, width):
"""
Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width)
"""
polys = [p.flatten().tolist() for p in polys]
assert le... | python | def segmentation_to_mask(polys, height, width):
"""
Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width)
"""
polys = [p.flatten().tolist() for p in polys]
assert le... | [
"def",
"segmentation_to_mask",
"(",
"polys",
",",
"height",
",",
"width",
")",
":",
"polys",
"=",
"[",
"p",
".",
"flatten",
"(",
")",
".",
"tolist",
"(",
")",
"for",
"p",
"in",
"polys",
"]",
"assert",
"len",
"(",
"polys",
")",
">",
"0",
",",
"\"P... | Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width) | [
"Convert",
"polygons",
"to",
"binary",
"masks",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L91-L107 | train |
tensorpack/tensorpack | examples/FasterRCNN/common.py | clip_boxes | def clip_boxes(boxes, shape):
"""
Args:
boxes: (...)x4, float
shape: h, w
"""
orig_shape = boxes.shape
boxes = boxes.reshape([-1, 4])
h, w = shape
boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0)
boxes[:, 2] = np.minimum(boxes[:, 2], w)
boxes[:, 3] = np.minimum(boxe... | python | def clip_boxes(boxes, shape):
"""
Args:
boxes: (...)x4, float
shape: h, w
"""
orig_shape = boxes.shape
boxes = boxes.reshape([-1, 4])
h, w = shape
boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0)
boxes[:, 2] = np.minimum(boxes[:, 2], w)
boxes[:, 3] = np.minimum(boxe... | [
"def",
"clip_boxes",
"(",
"boxes",
",",
"shape",
")",
":",
"orig_shape",
"=",
"boxes",
".",
"shape",
"boxes",
"=",
"boxes",
".",
"reshape",
"(",
"[",
"-",
"1",
",",
"4",
"]",
")",
"h",
",",
"w",
"=",
"shape",
"boxes",
"[",
":",
",",
"[",
"0",
... | Args:
boxes: (...)x4, float
shape: h, w | [
"Args",
":",
"boxes",
":",
"(",
"...",
")",
"x4",
"float",
"shape",
":",
"h",
"w"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L110-L122 | train |
tensorpack/tensorpack | examples/FasterRCNN/common.py | filter_boxes_inside_shape | def filter_boxes_inside_shape(boxes, shape):
"""
Args:
boxes: (nx4), float
shape: (h, w)
Returns:
indices: (k, )
selection: (kx4)
"""
assert boxes.ndim == 2, boxes.shape
assert len(shape) == 2, shape
h, w = shape
indices = np.where(
(boxes[:, 0] >... | python | def filter_boxes_inside_shape(boxes, shape):
"""
Args:
boxes: (nx4), float
shape: (h, w)
Returns:
indices: (k, )
selection: (kx4)
"""
assert boxes.ndim == 2, boxes.shape
assert len(shape) == 2, shape
h, w = shape
indices = np.where(
(boxes[:, 0] >... | [
"def",
"filter_boxes_inside_shape",
"(",
"boxes",
",",
"shape",
")",
":",
"assert",
"boxes",
".",
"ndim",
"==",
"2",
",",
"boxes",
".",
"shape",
"assert",
"len",
"(",
"shape",
")",
"==",
"2",
",",
"shape",
"h",
",",
"w",
"=",
"shape",
"indices",
"=",... | Args:
boxes: (nx4), float
shape: (h, w)
Returns:
indices: (k, )
selection: (kx4) | [
"Args",
":",
"boxes",
":",
"(",
"nx4",
")",
"float",
"shape",
":",
"(",
"h",
"w",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L125-L143 | train |
tensorpack/tensorpack | tensorpack/models/pool.py | MaxPooling | def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool... | python | def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool... | [
"def",
"MaxPooling",
"(",
"inputs",
",",
"pool_size",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'valid'",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"pool_size",
"layer",
"=",
"tf",
... | Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"MaxPooling2D",
".",
"Default",
"strides",
"is",
"equal",
"to",
"pool_size",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L21-L34 | train |
tensorpack/tensorpack | tensorpack/models/pool.py | AvgPooling | def AvgPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.AveragePoolin... | python | def AvgPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.AveragePoolin... | [
"def",
"AvgPooling",
"(",
"inputs",
",",
"pool_size",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'valid'",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"pool_size",
"layer",
"=",
"tf",
... | Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"AveragePooling2D",
".",
"Default",
"strides",
"is",
"equal",
"to",
"pool_size",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L41-L54 | train |
tensorpack/tensorpack | tensorpack/models/pool.py | GlobalAvgPooling | def GlobalAvgPooling(x, data_format='channels_last'):
"""
Global average pooling as in the paper `Network In Network
<http://arxiv.org/abs/1312.4400>`_.
Args:
x (tf.Tensor): a 4D tensor.
Returns:
tf.Tensor: a NC tensor named ``output``.
"""
assert x.shape.ndims == 4
dat... | python | def GlobalAvgPooling(x, data_format='channels_last'):
"""
Global average pooling as in the paper `Network In Network
<http://arxiv.org/abs/1312.4400>`_.
Args:
x (tf.Tensor): a 4D tensor.
Returns:
tf.Tensor: a NC tensor named ``output``.
"""
assert x.shape.ndims == 4
dat... | [
"def",
"GlobalAvgPooling",
"(",
"x",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"assert",
"x",
".",
"shape",
".",
"ndims",
"==",
"4",
"data_format",
"=",
"get_data_format",
"(",
"data_format",
")",
"axis",
"=",
"[",
"1",
",",
"2",
"]",
"if",
... | Global average pooling as in the paper `Network In Network
<http://arxiv.org/abs/1312.4400>`_.
Args:
x (tf.Tensor): a 4D tensor.
Returns:
tf.Tensor: a NC tensor named ``output``. | [
"Global",
"average",
"pooling",
"as",
"in",
"the",
"paper",
"Network",
"In",
"Network",
"<http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1312",
".",
"4400",
">",
"_",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L58-L72 | train |
tensorpack/tensorpack | tensorpack/models/pool.py | FixedUnPooling | def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'):
"""
Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
... | python | def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'):
"""
Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
... | [
"def",
"FixedUnPooling",
"(",
"x",
",",
"shape",
",",
"unpool_mat",
"=",
"None",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"data_format",
",",
"keras_mode",
"=",
"False",
")",
"shape",
"=",
"shape2d",
"... | Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
If is None, will use a matrix with 1 at top-left corner.
Returns:
... | [
"Unpool",
"the",
"input",
"with",
"a",
"fixed",
"matrix",
"to",
"perform",
"kronecker",
"product",
"with",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L91-L140 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | get_savename_from_varname | def get_savename_from_varname(
varname, varname_prefix=None,
savename_prefix=None):
"""
Args:
varname(str): a variable name in the graph
varname_prefix(str): an optional prefix that may need to be removed in varname
savename_prefix(str): an optional prefix to append to al... | python | def get_savename_from_varname(
varname, varname_prefix=None,
savename_prefix=None):
"""
Args:
varname(str): a variable name in the graph
varname_prefix(str): an optional prefix that may need to be removed in varname
savename_prefix(str): an optional prefix to append to al... | [
"def",
"get_savename_from_varname",
"(",
"varname",
",",
"varname_prefix",
"=",
"None",
",",
"savename_prefix",
"=",
"None",
")",
":",
"name",
"=",
"varname",
"if",
"varname_prefix",
"is",
"not",
"None",
"and",
"name",
".",
"startswith",
"(",
"varname_prefix",
... | Args:
varname(str): a variable name in the graph
varname_prefix(str): an optional prefix that may need to be removed in varname
savename_prefix(str): an optional prefix to append to all savename
Returns:
str: the name used to save the variable | [
"Args",
":",
"varname",
"(",
"str",
")",
":",
"a",
"variable",
"name",
"in",
"the",
"graph",
"varname_prefix",
"(",
"str",
")",
":",
"an",
"optional",
"prefix",
"that",
"may",
"need",
"to",
"be",
"removed",
"in",
"varname",
"savename_prefix",
"(",
"str",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L18-L35 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | dump_session_params | def dump_session_params(path):
"""
Dump value of all TRAINABLE + MODEL variables to a dict, and save as
npz format (loadable by :func:`sessinit.get_model_loader`).
Args:
path(str): the file name to save the parameters. Must ends with npz.
"""
# save variables that are GLOBAL, and either... | python | def dump_session_params(path):
"""
Dump value of all TRAINABLE + MODEL variables to a dict, and save as
npz format (loadable by :func:`sessinit.get_model_loader`).
Args:
path(str): the file name to save the parameters. Must ends with npz.
"""
# save variables that are GLOBAL, and either... | [
"def",
"dump_session_params",
"(",
"path",
")",
":",
"# save variables that are GLOBAL, and either TRAINABLE or MODEL",
"var",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
"var",
".",
"extend",
"(",
"tf",
".",
"get_... | Dump value of all TRAINABLE + MODEL variables to a dict, and save as
npz format (loadable by :func:`sessinit.get_model_loader`).
Args:
path(str): the file name to save the parameters. Must ends with npz. | [
"Dump",
"value",
"of",
"all",
"TRAINABLE",
"+",
"MODEL",
"variables",
"to",
"a",
"dict",
"and",
"save",
"as",
"npz",
"format",
"(",
"loadable",
"by",
":",
"func",
":",
"sessinit",
".",
"get_model_loader",
")",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L119-L137 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | save_chkpt_vars | def save_chkpt_vars(dic, path):
"""
Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
"""
logger.info("Variables to save to {}:".format(path))
keys = sorted(list(dic.keys()))
logger.info(pp... | python | def save_chkpt_vars(dic, path):
"""
Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
"""
logger.info("Variables to save to {}:".format(path))
keys = sorted(list(dic.keys()))
logger.info(pp... | [
"def",
"save_chkpt_vars",
"(",
"dic",
",",
"path",
")",
":",
"logger",
".",
"info",
"(",
"\"Variables to save to {}:\"",
".",
"format",
"(",
"path",
")",
")",
"keys",
"=",
"sorted",
"(",
"list",
"(",
"dic",
".",
"keys",
"(",
")",
")",
")",
"logger",
... | Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. | [
"Save",
"variables",
"in",
"dic",
"to",
"path",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L140-L163 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | get_checkpoint_path | def get_checkpoint_path(model_path):
"""
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
"""
if os.path.basename(model_path) == model_path:
model_path = os.path.... | python | def get_checkpoint_path(model_path):
"""
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
"""
if os.path.basename(model_path) == model_path:
model_path = os.path.... | [
"def",
"get_checkpoint_path",
"(",
"model_path",
")",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"model_path",
")",
"==",
"model_path",
":",
"model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'.'",
",",
"model_path",
")",
"# avoid #4921 and ... | Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader | [
"Work",
"around",
"TF",
"problems",
"in",
"checkpoint",
"path",
"handling",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L166-L193 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | load_chkpt_vars | def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
"""
model_path = get_checkpoint_path(model_path)
reader = tfv1.train.NewCheckpointReader(model_path)
var_names ... | python | def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
"""
model_path = get_checkpoint_path(model_path)
reader = tfv1.train.NewCheckpointReader(model_path)
var_names ... | [
"def",
"load_chkpt_vars",
"(",
"model_path",
")",
":",
"model_path",
"=",
"get_checkpoint_path",
"(",
"model_path",
")",
"reader",
"=",
"tfv1",
".",
"train",
".",
"NewCheckpointReader",
"(",
"model_path",
")",
"var_names",
"=",
"reader",
".",
"get_variable_to_shap... | Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict | [
"Load",
"all",
"variables",
"from",
"a",
"checkpoint",
"to",
"a",
"dict",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L196-L211 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | is_training_name | def is_training_name(name):
"""
**Guess** if this variable is only used in training.
Only used internally to avoid too many logging. Do not use it.
"""
# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?
# TODO or use get_slot_names()
name = get_op_tensor_name(name)[0... | python | def is_training_name(name):
"""
**Guess** if this variable is only used in training.
Only used internally to avoid too many logging. Do not use it.
"""
# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?
# TODO or use get_slot_names()
name = get_op_tensor_name(name)[0... | [
"def",
"is_training_name",
"(",
"name",
")",
":",
"# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?",
"# TODO or use get_slot_names()",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"0",
"]",
"if",
"name",
".",
"endswith",
"(",
"'/Ad... | **Guess** if this variable is only used in training.
Only used internally to avoid too many logging. Do not use it. | [
"**",
"Guess",
"**",
"if",
"this",
"variable",
"is",
"only",
"used",
"in",
"training",
".",
"Only",
"used",
"internally",
"to",
"avoid",
"too",
"many",
"logging",
".",
"Do",
"not",
"use",
"it",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L214-L238 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | SessionUpdate.relaxed_value_for_var | def relaxed_value_for_var(value, var):
"""
Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Returns:
ndarray: a ... | python | def relaxed_value_for_var(value, var):
"""
Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Returns:
ndarray: a ... | [
"def",
"relaxed_value_for_var",
"(",
"value",
",",
"var",
")",
":",
"assert",
"isinstance",
"(",
"var",
",",
"tf",
".",
"Variable",
")",
"name",
"=",
"var",
".",
"op",
".",
"name",
"# check incompatible shape",
"varshape",
"=",
"tuple",
"(",
"var",
".",
... | Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Returns:
ndarray: a possibly reshaped or casted version of value | [
"Returns",
"a",
"relaxed",
"(",
"possibly",
"reshaped",
"/",
"upcast",
"-",
"ed",
")",
"version",
"of",
"value",
"to",
"be",
"loaded",
"to",
"the",
"given",
"variable",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L51-L99 | train |
tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | SessionUpdate.update | def update(self, prms):
"""
Args:
prms(dict): dict of {variable name: value}
Any name in prms must be in the graph and in vars_to_update.
"""
with self.sess.as_default():
fetches = []
feeds = {}
for name, value in six.iterit... | python | def update(self, prms):
"""
Args:
prms(dict): dict of {variable name: value}
Any name in prms must be in the graph and in vars_to_update.
"""
with self.sess.as_default():
fetches = []
feeds = {}
for name, value in six.iterit... | [
"def",
"update",
"(",
"self",
",",
"prms",
")",
":",
"with",
"self",
".",
"sess",
".",
"as_default",
"(",
")",
":",
"fetches",
"=",
"[",
"]",
"feeds",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"prms",
")",
... | Args:
prms(dict): dict of {variable name: value}
Any name in prms must be in the graph and in vars_to_update. | [
"Args",
":",
"prms",
"(",
"dict",
")",
":",
"dict",
"of",
"{",
"variable",
"name",
":",
"value",
"}",
"Any",
"name",
"in",
"prms",
"must",
"be",
"in",
"the",
"graph",
"and",
"in",
"vars_to_update",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L101-L116 | train |
tensorpack/tensorpack | tensorpack/tfutils/distributed.py | get_distributed_session_creator | def get_distributed_session_creator(server):
"""
Args:
server (tf.train.Server):
Returns:
tf.train.SessionCreator
"""
server_def = server.server_def
is_chief = (server_def.job_name == 'worker') and (server_def.task_index == 0)
init_op = tf.global_variables_initializer()
... | python | def get_distributed_session_creator(server):
"""
Args:
server (tf.train.Server):
Returns:
tf.train.SessionCreator
"""
server_def = server.server_def
is_chief = (server_def.job_name == 'worker') and (server_def.task_index == 0)
init_op = tf.global_variables_initializer()
... | [
"def",
"get_distributed_session_creator",
"(",
"server",
")",
":",
"server_def",
"=",
"server",
".",
"server_def",
"is_chief",
"=",
"(",
"server_def",
".",
"job_name",
"==",
"'worker'",
")",
"and",
"(",
"server_def",
".",
"task_index",
"==",
"0",
")",
"init_op... | Args:
server (tf.train.Server):
Returns:
tf.train.SessionCreator | [
"Args",
":",
"server",
"(",
"tf",
".",
"train",
".",
"Server",
")",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/distributed.py#L8-L47 | train |
tensorpack/tensorpack | tensorpack/utils/gpu.py | get_num_gpu | def get_num_gpu():
"""
Returns:
int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system.
"""
def warn_return(ret, message):
try:
import tensorflow as tf
except ImportError:
return ret
built_with_cuda = tf.test.is_built_with_cuda()
... | python | def get_num_gpu():
"""
Returns:
int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system.
"""
def warn_return(ret, message):
try:
import tensorflow as tf
except ImportError:
return ret
built_with_cuda = tf.test.is_built_with_cuda()
... | [
"def",
"get_num_gpu",
"(",
")",
":",
"def",
"warn_return",
"(",
"ret",
",",
"message",
")",
":",
"try",
":",
"import",
"tensorflow",
"as",
"tf",
"except",
"ImportError",
":",
"return",
"ret",
"built_with_cuda",
"=",
"tf",
".",
"test",
".",
"is_built_with_c... | Returns:
int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system. | [
"Returns",
":",
"int",
":",
"#available",
"GPUs",
"in",
"CUDA_VISIBLE_DEVICES",
"or",
"in",
"the",
"system",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/gpu.py#L29-L71 | train |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_summary | def put_summary(self, summary):
"""
Put a `tf.Summary`.
"""
if isinstance(summary, six.binary_type):
summary = tf.Summary.FromString(summary)
assert isinstance(summary, tf.Summary), type(summary)
# TODO other types
for val in summary.value:
... | python | def put_summary(self, summary):
"""
Put a `tf.Summary`.
"""
if isinstance(summary, six.binary_type):
summary = tf.Summary.FromString(summary)
assert isinstance(summary, tf.Summary), type(summary)
# TODO other types
for val in summary.value:
... | [
"def",
"put_summary",
"(",
"self",
",",
"summary",
")",
":",
"if",
"isinstance",
"(",
"summary",
",",
"six",
".",
"binary_type",
")",
":",
"summary",
"=",
"tf",
".",
"Summary",
".",
"FromString",
"(",
"summary",
")",
"assert",
"isinstance",
"(",
"summary... | Put a `tf.Summary`. | [
"Put",
"a",
"tf",
".",
"Summary",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L143-L164 | train |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_scalar | def put_scalar(self, name, val):
"""
Put a scalar.
"""
if isinstance(val, np.floating):
val = float(val)
if isinstance(val, np.integer):
val = int(val)
self._dispatch(lambda m: m.process_scalar(name, val))
s = create_scalar_summary(name, va... | python | def put_scalar(self, name, val):
"""
Put a scalar.
"""
if isinstance(val, np.floating):
val = float(val)
if isinstance(val, np.integer):
val = int(val)
self._dispatch(lambda m: m.process_scalar(name, val))
s = create_scalar_summary(name, va... | [
"def",
"put_scalar",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"floating",
")",
":",
"val",
"=",
"float",
"(",
"val",
")",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"integer",
")",
":",
... | Put a scalar. | [
"Put",
"a",
"scalar",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L166-L176 | train |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_image | def put_image(self, name, val):
"""
Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB.
"""
assert isinstance(val, np.ndarray)
arr ... | python | def put_image(self, name, val):
"""
Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB.
"""
assert isinstance(val, np.ndarray)
arr ... | [
"def",
"put_image",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"assert",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
"arr",
"=",
"image_to_nhwc",
"(",
"val",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"proc... | Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB. | [
"Put",
"an",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L178-L191 | train |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_event | def put_event(self, evt):
"""
Put an :class:`tf.Event`.
`step` and `wall_time` fields of :class:`tf.Event` will be filled automatically.
Args:
evt (tf.Event):
"""
evt.step = self.global_step
evt.wall_time = time.time()
self._dispatch(lambda m:... | python | def put_event(self, evt):
"""
Put an :class:`tf.Event`.
`step` and `wall_time` fields of :class:`tf.Event` will be filled automatically.
Args:
evt (tf.Event):
"""
evt.step = self.global_step
evt.wall_time = time.time()
self._dispatch(lambda m:... | [
"def",
"put_event",
"(",
"self",
",",
"evt",
")",
":",
"evt",
".",
"step",
"=",
"self",
".",
"global_step",
"evt",
".",
"wall_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_event",
"... | Put an :class:`tf.Event`.
`step` and `wall_time` fields of :class:`tf.Event` will be filled automatically.
Args:
evt (tf.Event): | [
"Put",
"an",
":",
"class",
":",
"tf",
".",
"Event",
".",
"step",
"and",
"wall_time",
"fields",
"of",
":",
"class",
":",
"tf",
".",
"Event",
"will",
"be",
"filled",
"automatically",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L193-L203 | train |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | JSONWriter.load_existing_json | def load_existing_json():
"""
Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json",
and return the loaded list of statistics if found. Returns None otherwise.
"""
dir = logger.get_logger_dir()
fname = os.path.join(dir, JSONWriter.FILENAME)
... | python | def load_existing_json():
"""
Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json",
and return the loaded list of statistics if found. Returns None otherwise.
"""
dir = logger.get_logger_dir()
fname = os.path.join(dir, JSONWriter.FILENAME)
... | [
"def",
"load_existing_json",
"(",
")",
":",
"dir",
"=",
"logger",
".",
"get_logger_dir",
"(",
")",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"JSONWriter",
".",
"FILENAME",
")",
"if",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"fname... | Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json",
and return the loaded list of statistics if found. Returns None otherwise. | [
"Look",
"for",
"an",
"existing",
"json",
"under",
":",
"meth",
":",
"logger",
".",
"get_logger_dir",
"()",
"named",
"stats",
".",
"json",
"and",
"return",
"the",
"loaded",
"list",
"of",
"statistics",
"if",
"found",
".",
"Returns",
"None",
"otherwise",
"."
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L302-L314 | train |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | JSONWriter._trigger | def _trigger(self):
"""
Add stats to json and dump to disk.
Note that this method is idempotent.
"""
if len(self._stat_now):
self._stat_now['epoch_num'] = self.epoch_num
self._stat_now['global_step'] = self.global_step
self._stats.append(self.... | python | def _trigger(self):
"""
Add stats to json and dump to disk.
Note that this method is idempotent.
"""
if len(self._stat_now):
self._stat_now['epoch_num'] = self.epoch_num
self._stat_now['global_step'] = self.global_step
self._stats.append(self.... | [
"def",
"_trigger",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_stat_now",
")",
":",
"self",
".",
"_stat_now",
"[",
"'epoch_num'",
"]",
"=",
"self",
".",
"epoch_num",
"self",
".",
"_stat_now",
"[",
"'global_step'",
"]",
"=",
"self",
".",
"... | Add stats to json and dump to disk.
Note that this method is idempotent. | [
"Add",
"stats",
"to",
"json",
"and",
"dump",
"to",
"disk",
".",
"Note",
"that",
"this",
"method",
"is",
"idempotent",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L378-L389 | train |
tensorpack/tensorpack | examples/SpatialTransformer/mnist-addition.py | sample | def sample(img, coords):
"""
Args:
img: bxhxwxc
coords: bxh2xw2x2. each coordinate is (y, x) integer.
Out of boundary coordinates will be clipped.
Return:
bxh2xw2xc image
"""
shape = img.get_shape().as_list()[1:] # h, w, c
batch = tf.shape(img)[0]
shape2... | python | def sample(img, coords):
"""
Args:
img: bxhxwxc
coords: bxh2xw2x2. each coordinate is (y, x) integer.
Out of boundary coordinates will be clipped.
Return:
bxh2xw2xc image
"""
shape = img.get_shape().as_list()[1:] # h, w, c
batch = tf.shape(img)[0]
shape2... | [
"def",
"sample",
"(",
"img",
",",
"coords",
")",
":",
"shape",
"=",
"img",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
":",
"]",
"# h, w, c",
"batch",
"=",
"tf",
".",
"shape",
"(",
"img",
")",
"[",
"0",
"]",
"shape2",
"=",
... | Args:
img: bxhxwxc
coords: bxh2xw2x2. each coordinate is (y, x) integer.
Out of boundary coordinates will be clipped.
Return:
bxh2xw2xc image | [
"Args",
":",
"img",
":",
"bxhxwxc",
"coords",
":",
"bxh2xw2x2",
".",
"each",
"coordinate",
"is",
"(",
"y",
"x",
")",
"integer",
".",
"Out",
"of",
"boundary",
"coordinates",
"will",
"be",
"clipped",
".",
"Return",
":",
"bxh2xw2xc",
"image"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SpatialTransformer/mnist-addition.py#L21-L44 | train |
tensorpack/tensorpack | examples/SpatialTransformer/mnist-addition.py | GridSample | def GridSample(inputs, borderMode='repeat'):
"""
Sample the images using the given coordinates, by bilinear interpolation.
This was described in the paper:
`Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_.
This is equivalent to `torch.nn.functional.grid_sample`,
up to some non-... | python | def GridSample(inputs, borderMode='repeat'):
"""
Sample the images using the given coordinates, by bilinear interpolation.
This was described in the paper:
`Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_.
This is equivalent to `torch.nn.functional.grid_sample`,
up to some non-... | [
"def",
"GridSample",
"(",
"inputs",
",",
"borderMode",
"=",
"'repeat'",
")",
":",
"image",
",",
"mapping",
"=",
"inputs",
"assert",
"image",
".",
"get_shape",
"(",
")",
".",
"ndims",
"==",
"4",
"and",
"mapping",
".",
"get_shape",
"(",
")",
".",
"ndims"... | Sample the images using the given coordinates, by bilinear interpolation.
This was described in the paper:
`Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_.
This is equivalent to `torch.nn.functional.grid_sample`,
up to some non-trivial coordinate transformation.
This implementati... | [
"Sample",
"the",
"images",
"using",
"the",
"given",
"coordinates",
"by",
"bilinear",
"interpolation",
".",
"This",
"was",
"described",
"in",
"the",
"paper",
":",
"Spatial",
"Transformer",
"Networks",
"<http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SpatialTransformer/mnist-addition.py#L48-L105 | train |
tensorpack/tensorpack | tensorpack/utils/debug.py | enable_call_trace | def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co.co_name
if func_name == 'write' or func_name == 'print':
# ignore write() calls from print stat... | python | def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co.co_name
if func_name == 'write' or func_name == 'print':
# ignore write() calls from print stat... | [
"def",
"enable_call_trace",
"(",
")",
":",
"def",
"tracer",
"(",
"frame",
",",
"event",
",",
"arg",
")",
":",
"if",
"event",
"==",
"'call'",
":",
"co",
"=",
"frame",
".",
"f_code",
"func_name",
"=",
"co",
".",
"co_name",
"if",
"func_name",
"==",
"'wr... | Enable trace for calls to any function. | [
"Enable",
"trace",
"for",
"calls",
"to",
"any",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/debug.py#L8-L27 | train |
tensorpack/tensorpack | tensorpack/train/interface.py | apply_default_prefetch | def apply_default_prefetch(input_source_or_dataflow, trainer):
"""
Apply a set of default rules to make a fast :class:`InputSource`.
Args:
input_source_or_dataflow(InputSource | DataFlow):
trainer (Trainer):
Returns:
InputSource
"""
if not isinstance(input_source_or_dat... | python | def apply_default_prefetch(input_source_or_dataflow, trainer):
"""
Apply a set of default rules to make a fast :class:`InputSource`.
Args:
input_source_or_dataflow(InputSource | DataFlow):
trainer (Trainer):
Returns:
InputSource
"""
if not isinstance(input_source_or_dat... | [
"def",
"apply_default_prefetch",
"(",
"input_source_or_dataflow",
",",
"trainer",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_source_or_dataflow",
",",
"InputSource",
")",
":",
"# to mimic same behavior of the old trainer interface",
"if",
"type",
"(",
"trainer",
")"... | Apply a set of default rules to make a fast :class:`InputSource`.
Args:
input_source_or_dataflow(InputSource | DataFlow):
trainer (Trainer):
Returns:
InputSource | [
"Apply",
"a",
"set",
"of",
"default",
"rules",
"to",
"make",
"a",
"fast",
":",
"class",
":",
"InputSource",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/interface.py#L15-L45 | train |
tensorpack/tensorpack | tensorpack/train/interface.py | launch_train_with_config | def launch_train_with_config(config, trainer):
"""
Train with a :class:`TrainConfig` and a :class:`Trainer`, to
present the simple and old training interface. It basically does the following
3 things (and you can easily do them by yourself if you need more control):
1. Setup the input with automati... | python | def launch_train_with_config(config, trainer):
"""
Train with a :class:`TrainConfig` and a :class:`Trainer`, to
present the simple and old training interface. It basically does the following
3 things (and you can easily do them by yourself if you need more control):
1. Setup the input with automati... | [
"def",
"launch_train_with_config",
"(",
"config",
",",
"trainer",
")",
":",
"if",
"is_tfv2",
"(",
")",
":",
"tfv1",
".",
"disable_eager_execution",
"(",
")",
"assert",
"isinstance",
"(",
"trainer",
",",
"SingleCostTrainer",
")",
",",
"trainer",
"assert",
"isin... | Train with a :class:`TrainConfig` and a :class:`Trainer`, to
present the simple and old training interface. It basically does the following
3 things (and you can easily do them by yourself if you need more control):
1. Setup the input with automatic prefetching heuristics,
from `config.data` or `con... | [
"Train",
"with",
"a",
":",
"class",
":",
"TrainConfig",
"and",
"a",
":",
"class",
":",
"Trainer",
"to",
"present",
"the",
"simple",
"and",
"old",
"training",
"interface",
".",
"It",
"basically",
"does",
"the",
"following",
"3",
"things",
"(",
"and",
"you... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/interface.py#L48-L101 | train |
tensorpack/tensorpack | tensorpack/train/base.py | _get_property | def _get_property(name):
"""
Delegate property to self.loop
"""
ret = property(
lambda self: getattr(self.loop, name))
if six.PY3: # __doc__ is readonly in Py2
try:
ret.__doc__ = getattr(TrainLoop, name).__doc__
except AttributeError:
pass
retu... | python | def _get_property(name):
"""
Delegate property to self.loop
"""
ret = property(
lambda self: getattr(self.loop, name))
if six.PY3: # __doc__ is readonly in Py2
try:
ret.__doc__ = getattr(TrainLoop, name).__doc__
except AttributeError:
pass
retu... | [
"def",
"_get_property",
"(",
"name",
")",
":",
"ret",
"=",
"property",
"(",
"lambda",
"self",
":",
"getattr",
"(",
"self",
".",
"loop",
",",
"name",
")",
")",
"if",
"six",
".",
"PY3",
":",
"# __doc__ is readonly in Py2",
"try",
":",
"ret",
".",
"__doc_... | Delegate property to self.loop | [
"Delegate",
"property",
"to",
"self",
".",
"loop"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L357-L368 | train |
tensorpack/tensorpack | tensorpack/train/base.py | TrainLoop.config | def config(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Configure the loop given the settings.
"""
self.starting_epoch = int(starting_epoch)
self.max_epoch = int(max_epoch)
self.steps_per_epoch = int(steps_per_epoch)
# Allow empty epoch (no steps), if we... | python | def config(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Configure the loop given the settings.
"""
self.starting_epoch = int(starting_epoch)
self.max_epoch = int(max_epoch)
self.steps_per_epoch = int(steps_per_epoch)
# Allow empty epoch (no steps), if we... | [
"def",
"config",
"(",
"self",
",",
"steps_per_epoch",
",",
"starting_epoch",
",",
"max_epoch",
")",
":",
"self",
".",
"starting_epoch",
"=",
"int",
"(",
"starting_epoch",
")",
"self",
".",
"max_epoch",
"=",
"int",
"(",
"max_epoch",
")",
"self",
".",
"steps... | Configure the loop given the settings. | [
"Configure",
"the",
"loop",
"given",
"the",
"settings",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L43-L53 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer._register_callback | def _register_callback(self, cb):
"""
Register callbacks to the trainer.
It can only be called before :meth:`Trainer.train()`.
Args:
cb (Callback or [Callback]): a callback or a list of callbacks
Returns:
succeed or not
"""
if isinstance(... | python | def _register_callback(self, cb):
"""
Register callbacks to the trainer.
It can only be called before :meth:`Trainer.train()`.
Args:
cb (Callback or [Callback]): a callback or a list of callbacks
Returns:
succeed or not
"""
if isinstance(... | [
"def",
"_register_callback",
"(",
"self",
",",
"cb",
")",
":",
"if",
"isinstance",
"(",
"cb",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"x",
"in",
"cb",
":",
"self",
".",
"_register_callback",
"(",
"x",
")",
"return",
"assert",
"isinstanc... | Register callbacks to the trainer.
It can only be called before :meth:`Trainer.train()`.
Args:
cb (Callback or [Callback]): a callback or a list of callbacks
Returns:
succeed or not | [
"Register",
"callbacks",
"to",
"the",
"trainer",
".",
"It",
"can",
"only",
"be",
"called",
"before",
":",
"meth",
":",
"Trainer",
".",
"train",
"()",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L142-L165 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer.run_step | def run_step(self):
"""
Defines what to do in one iteration. The default is:
``self.hooked_sess.run(self.train_op)``.
The behavior of each iteration can be changed by either setting ``trainer.train_op``,
or overriding this method.
"""
if not hasattr(self, 'train_... | python | def run_step(self):
"""
Defines what to do in one iteration. The default is:
``self.hooked_sess.run(self.train_op)``.
The behavior of each iteration can be changed by either setting ``trainer.train_op``,
or overriding this method.
"""
if not hasattr(self, 'train_... | [
"def",
"run_step",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'train_op'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Please either set `Trainer.train_op` or provide an implementation \"",
"\"of Trainer.run_step()!\"",
")",
"self",
".",
"ho... | Defines what to do in one iteration. The default is:
``self.hooked_sess.run(self.train_op)``.
The behavior of each iteration can be changed by either setting ``trainer.train_op``,
or overriding this method. | [
"Defines",
"what",
"to",
"do",
"in",
"one",
"iteration",
".",
"The",
"default",
"is",
":",
"self",
".",
"hooked_sess",
".",
"run",
"(",
"self",
".",
"train_op",
")",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L169-L181 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer.setup_callbacks | def setup_callbacks(self, callbacks, monitors):
"""
Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]):
"""
assert isinstance(callbacks, list), callbacks
assert isinst... | python | def setup_callbacks(self, callbacks, monitors):
"""
Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]):
"""
assert isinstance(callbacks, list), callbacks
assert isinst... | [
"def",
"setup_callbacks",
"(",
"self",
",",
"callbacks",
",",
"monitors",
")",
":",
"assert",
"isinstance",
"(",
"callbacks",
",",
"list",
")",
",",
"callbacks",
"assert",
"isinstance",
"(",
"monitors",
",",
"list",
")",
",",
"monitors",
"describe_trainable_va... | Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]): | [
"Setup",
"callbacks",
"and",
"monitors",
".",
"Must",
"be",
"called",
"after",
"the",
"main",
"graph",
"is",
"built",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L184-L211 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer.initialize | def initialize(self, session_creator, session_init):
"""
Create the session and set `self.sess`.
Call `self.initiailize_hooks()`
Finalize the graph.
It must be called after callbacks are setup.
Args:
session_creator (tf.train.SessionCreator):
ses... | python | def initialize(self, session_creator, session_init):
"""
Create the session and set `self.sess`.
Call `self.initiailize_hooks()`
Finalize the graph.
It must be called after callbacks are setup.
Args:
session_creator (tf.train.SessionCreator):
ses... | [
"def",
"initialize",
"(",
"self",
",",
"session_creator",
",",
"session_init",
")",
":",
"assert",
"isinstance",
"(",
"session_creator",
",",
"tfv1",
".",
"train",
".",
"SessionCreator",
")",
",",
"session_creator",
"assert",
"isinstance",
"(",
"session_init",
"... | Create the session and set `self.sess`.
Call `self.initiailize_hooks()`
Finalize the graph.
It must be called after callbacks are setup.
Args:
session_creator (tf.train.SessionCreator):
session_init (sessinit.SessionInit): | [
"Create",
"the",
"session",
"and",
"set",
"self",
".",
"sess",
".",
"Call",
"self",
".",
"initiailize_hooks",
"()",
"Finalize",
"the",
"graph",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L214-L243 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer.initialize_hooks | def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
... | python | def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
... | [
"def",
"initialize_hooks",
"(",
"self",
")",
":",
"hooks",
"=",
"self",
".",
"_callbacks",
".",
"get_hooks",
"(",
")",
"self",
".",
"hooked_sess",
"=",
"tfv1",
".",
"train",
".",
"MonitoredSession",
"(",
"session_creator",
"=",
"ReuseSessionCreator",
"(",
"s... | Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`. | [
"Create",
"SessionRunHooks",
"for",
"all",
"callbacks",
"and",
"hook",
"it",
"onto",
"self",
".",
"sess",
"to",
"create",
"self",
".",
"hooked_sess",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L246-L255 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer.main_loop | def main_loop(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Run the main training loop.
Args:
steps_per_epoch, starting_epoch, max_epoch (int):
"""
with self.sess.as_default():
self.loop.config(steps_per_epoch, starting_epoch, max_epoch)
... | python | def main_loop(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Run the main training loop.
Args:
steps_per_epoch, starting_epoch, max_epoch (int):
"""
with self.sess.as_default():
self.loop.config(steps_per_epoch, starting_epoch, max_epoch)
... | [
"def",
"main_loop",
"(",
"self",
",",
"steps_per_epoch",
",",
"starting_epoch",
",",
"max_epoch",
")",
":",
"with",
"self",
".",
"sess",
".",
"as_default",
"(",
")",
":",
"self",
".",
"loop",
".",
"config",
"(",
"steps_per_epoch",
",",
"starting_epoch",
",... | Run the main training loop.
Args:
steps_per_epoch, starting_epoch, max_epoch (int): | [
"Run",
"the",
"main",
"training",
"loop",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L258-L297 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer.train | def train(self,
callbacks, monitors,
session_creator, session_init,
steps_per_epoch, starting_epoch=1, max_epoch=9999999):
"""
Implemented by three lines:
.. code-block:: python
self.setup_callbacks(callbacks, monitors)
self.ini... | python | def train(self,
callbacks, monitors,
session_creator, session_init,
steps_per_epoch, starting_epoch=1, max_epoch=9999999):
"""
Implemented by three lines:
.. code-block:: python
self.setup_callbacks(callbacks, monitors)
self.ini... | [
"def",
"train",
"(",
"self",
",",
"callbacks",
",",
"monitors",
",",
"session_creator",
",",
"session_init",
",",
"steps_per_epoch",
",",
"starting_epoch",
"=",
"1",
",",
"max_epoch",
"=",
"9999999",
")",
":",
"self",
".",
"setup_callbacks",
"(",
"callbacks",
... | Implemented by three lines:
.. code-block:: python
self.setup_callbacks(callbacks, monitors)
self.initialize(session_creator, session_init)
self.main_loop(steps_per_epoch, starting_epoch, max_epoch)
You can call those methods by yourself to have better control on d... | [
"Implemented",
"by",
"three",
"lines",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L299-L316 | train |
tensorpack/tensorpack | tensorpack/train/base.py | Trainer.train_with_defaults | def train_with_defaults(
self, _sentinel=None,
callbacks=None, monitors=None,
session_creator=None, session_init=None,
steps_per_epoch=None, starting_epoch=1, max_epoch=9999999,
extra_callbacks=None):
"""
Same as :meth:`train()`, except:
... | python | def train_with_defaults(
self, _sentinel=None,
callbacks=None, monitors=None,
session_creator=None, session_init=None,
steps_per_epoch=None, starting_epoch=1, max_epoch=9999999,
extra_callbacks=None):
"""
Same as :meth:`train()`, except:
... | [
"def",
"train_with_defaults",
"(",
"self",
",",
"_sentinel",
"=",
"None",
",",
"callbacks",
"=",
"None",
",",
"monitors",
"=",
"None",
",",
"session_creator",
"=",
"None",
",",
"session_init",
"=",
"None",
",",
"steps_per_epoch",
"=",
"None",
",",
"starting_... | Same as :meth:`train()`, except:
1. Add `extra_callbacks` to callbacks. The default value for
`extra_callbacks` is :meth:`DEFAULT_CALLBACKS()`.
2. Default value for `monitors` is :meth:`DEFAULT_MONITORS()`.
3. Provide default values for every option except `steps_per_epoch`. | [
"Same",
"as",
":",
"meth",
":",
"train",
"()",
"except",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L318-L344 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.