code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def angle_between(self, v1: np.ndarray, v2: np.ndarray) -> float:
"""Returns the angle in radians between vectors 'v1' and 'v2'."""
if np.abs(v1).sum() < 1e-6 or np.abs(v2).sum() < 1e-6:
return 0
v1_u = self.unit_vector(v1)
v2_u = self.unit_vector(v2)
return np.arccos... | Returns the angle in radians between vectors 'v1' and 'v2'. | angle_between | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def rotation_matrix(self, axis: np.ndarray, theta: float) -> np.ndarray:
"""Returns the rotation matrix associated with counterclockwise
rotation about the given axis by theta radians."""
if np.abs(axis).sum() < 1e-6 or np.abs(theta) < 1e-6:
return np.eye(3)
axis = np.asarray... | Returns the rotation matrix associated with counterclockwise
rotation about the given axis by theta radians. | rotation_matrix | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`PreNormalize3D`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
skeleton = results['keypoint']
total_frames = results.get('total_frames',... | The transform function of :class:`PreNormalize3D`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`PreNormalize2D`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
h, w = results.get('img_shape', self.img_shape)
results['keypoint'][..., ... | The transform function of :class:`PreNormalize2D`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`JointToBone`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
keypoint = results['keypoint']
M, T, V, C = keypoint.shape
bone = np... | The transform function of :class:`JointToBone`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`ToMotion`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
data = results[self.source]
M, T, V, C = data.shape
motion = np.zeros_l... | The transform function of :class:`ToMotion`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`MergeSkeFeat`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
feats = []
for name in self.feat_list:
feats.append(results.pop... | The transform function of :class:`MergeSkeFeat`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`GenSkeFeat`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
if 'keypoint_score' in results and 'keypoint' in results:
assert self.dat... | The transform function of :class:`GenSkeFeat`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def _get_train_clips(self, num_frames: int, clip_len: int) -> np.ndarray:
"""Uniformly sample indices for training clips.
Args:
num_frames (int): The number of frames.
clip_len (int): The length of the clip.
Returns:
np.ndarray: The sampled indices for train... | Uniformly sample indices for training clips.
Args:
num_frames (int): The number of frames.
clip_len (int): The length of the clip.
Returns:
np.ndarray: The sampled indices for training clips.
| _get_train_clips | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def _get_test_clips(self, num_frames: int, clip_len: int) -> np.ndarray:
"""Uniformly sample indices for testing clips.
Args:
num_frames (int): The number of frames.
clip_len (int): The length of the clip.
Returns:
np.ndarray: The sampled indices for testing... | Uniformly sample indices for testing clips.
Args:
num_frames (int): The number of frames.
clip_len (int): The length of the clip.
Returns:
np.ndarray: The sampled indices for testing clips.
| _get_test_clips | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`UniformSampleFrames`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
num_frames = results['total_frames']
if self.test_mode:
... | The transform function of :class:`UniformSampleFrames`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`PadTo`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
total_frames = results['total_frames']
assert total_frames <= self.length
... | The transform function of :class:`PadTo`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def _load_kpscore(kpscore: np.ndarray,
frame_inds: np.ndarray) -> np.ndarray:
"""Load keypoint scores according to sampled indexes."""
return kpscore[:, frame_inds].astype(np.float32) | Load keypoint scores according to sampled indexes. | _load_kpscore | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`PoseDecode`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
if 'total_frames' not in results:
results['total_frames'] = results['keyp... | The transform function of :class:`PoseDecode`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`MMUniformSampleFrames`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
num_frames = results['total_frames']
modalities = []
for m... | The transform function of :class:`MMUniformSampleFrames`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`MMDecode`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
for mod in results['modality']:
if results[f'{mod}_inds'].ndim != 1:
... | The transform function of :class:`MMDecode`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def _get_box(self, keypoint: np.ndarray, img_shape: Tuple[int]) -> Tuple:
"""Calculate the bounding box surrounding all joints in the frames."""
h, w = img_shape
kp_x = keypoint[..., 0]
kp_y = keypoint[..., 1]
min_x = np.min(kp_x[kp_x != 0], initial=np.Inf)
min_y = np.m... | Calculate the bounding box surrounding all joints in the frames. | _get_box | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def _compact_images(self, imgs: List[np.ndarray], img_shape: Tuple[int],
box: Tuple[int]) -> List:
"""Crop the images acoordding the bounding box."""
h, w = img_shape
min_x, min_y, max_x, max_y = box
pad_l, pad_u, pad_r, pad_d = 0, 0, 0, 0
if min_x < 0:
... | Crop the images acoordding the bounding box. | _compact_images | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`MMCompact`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
img_shape = results['img_shape']
kp = results['keypoint']
# Make NaN z... | The transform function of :class:`MMCompact`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/pose_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/pose_transforms.py | Apache-2.0 |
def _init_lazy_if_proper(results, lazy):
"""Initialize lazy operation properly.
Make sure that a lazy operation is properly initialized,
and avoid a non-lazy operation accidentally getting mixed in.
Required keys in results are "imgs" if "img_shape" not in results,
otherwise, Required keys in resu... | Initialize lazy operation properly.
Make sure that a lazy operation is properly initialized,
and avoid a non-lazy operation accidentally getting mixed in.
Required keys in results are "imgs" if "img_shape" not in results,
otherwise, Required keys in results are "img_shape", add or modified keys
ar... | _init_lazy_if_proper | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Fuse lazy operations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
if 'lazy' not in results:
raise ValueError('No lazy operation detected')
lazyo... | Fuse lazy operations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def _box_crop(box, crop_bbox):
"""Crop the bounding boxes according to the crop_bbox.
Args:
box (np.ndarray): The bounding boxes.
crop_bbox(np.ndarray): The bbox used to crop the original image.
"""
x1, y1, x2, y2 = crop_bbox
img_w, img_h = x2 - x1, y2 -... | Crop the bounding boxes according to the crop_bbox.
Args:
box (np.ndarray): The bounding boxes.
crop_bbox(np.ndarray): The bbox used to crop the original image.
| _box_crop | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def _all_box_crop(self, results, crop_bbox):
"""Crop the gt_bboxes and proposals in results according to crop_bbox.
Args:
results (dict): All information about the sample, which contain
'gt_bboxes' and 'proposals' (optional).
crop_bbox(np.ndarray): The bbox used ... | Crop the gt_bboxes and proposals in results according to crop_bbox.
Args:
results (dict): All information about the sample, which contain
'gt_bboxes' and 'proposals' (optional).
crop_bbox(np.ndarray): The bbox used to crop the original image.
| _all_box_crop | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the RandomCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, self.lazy)
if 'keypoint' in results:
... | Performs the RandomCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def get_crop_bbox(img_shape,
area_range,
aspect_ratio_range,
max_attempts=10):
"""Get a crop bbox given the area range and aspect ratio range.
Args:
img_shape (Tuple[int]): Image shape
area_range (Tuple[float]): T... | Get a crop bbox given the area range and aspect ratio range.
Args:
img_shape (Tuple[int]): Image shape
area_range (Tuple[float]): The candidate area scales range of
output cropped images. Default: (0.08, 1.0).
aspect_ratio_range (Tuple[float]): The candidate ... | get_crop_bbox | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the RandomResizeCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, self.lazy)
if 'keypoint' in results:
... | Performs the RandomResizeCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the MultiScaleCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, self.lazy)
if 'keypoint' in results:
... | Performs the MultiScaleCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def _box_resize(box, scale_factor):
"""Rescale the bounding boxes according to the scale_factor.
Args:
box (np.ndarray): The bounding boxes.
scale_factor (np.ndarray): The scale factor used for rescaling.
"""
assert len(scale_factor) == 2
scale_factor = n... | Rescale the bounding boxes according to the scale_factor.
Args:
box (np.ndarray): The bounding boxes.
scale_factor (np.ndarray): The scale factor used for rescaling.
| _box_resize | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the Resize augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, self.lazy)
if 'keypoint' in results:
... | Performs the Resize augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the Resize augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
short_edge = np.random.randint(self.scale_range[0],
... | Performs the Resize augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def _box_flip(box, img_width):
"""Flip the bounding boxes given the width of the image.
Args:
box (np.ndarray): The bounding boxes.
img_width (int): The img width.
"""
box_ = box.copy()
box_[..., 0::4] = img_width - box[..., 2::4]
box_[..., 2::4] ... | Flip the bounding boxes given the width of the image.
Args:
box (np.ndarray): The bounding boxes.
img_width (int): The img width.
| _box_flip | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the Flip augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, self.lazy)
if 'keypoint' in results:
a... | Performs the Flip augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Perform ColorJitter.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
imgs = results['imgs']
num_clips, clip_len = 1, len(imgs)
new_imgs = []
fo... | Perform ColorJitter.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the CenterCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, self.lazy)
if 'keypoint' in results:
... | Performs the CenterCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the ThreeCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, False)
if 'gt_bboxes' in results or 'proposal... | Performs the ThreeCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""Performs the TenCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
_init_lazy_if_proper(results, False)
if 'gt_bboxes' in results or 'proposals... | Performs the TenCrop augmentation.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def _img_fill_pixels(self, img, top, left, h, w):
"""Fill pixels to the patch of image."""
if self.mode == 'const':
patch = np.empty((h, w, 3), dtype=np.uint8)
patch[:, :] = np.array(self.fill_color, dtype=np.uint8)
elif self.fill_std is None:
# Uniform distri... | Fill pixels to the patch of image. | _img_fill_pixels | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results):
"""
Args:
results (dict): Results dict from pipeline
Returns:
dict: Results after the transformation.
"""
if self.random_disable():
return results
imgs = results['imgs']
img_h, img_w = imgs[0].sha... |
Args:
results (dict): Results dict from pipeline
Returns:
dict: Results after the transformation.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/processing.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/processing.py | Apache-2.0 |
def transform(self, results: Dict) -> Dict:
"""The transform function of :class:`CLIPTokenize`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
"""
try:
import clip
except ImportError:
raise ImportE... | The transform function of :class:`CLIPTokenize`.
Args:
results (dict): The result dict.
Returns:
dict: The result dict.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/text_transforms.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/text_transforms.py | Apache-2.0 |
def transform(self, results):
"""Perform Torchvision augmentations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
assert 'imgs' in results
imgs = [x.transpose(2, 0, 1) for x in results['imgs... | Perform Torchvision augmentations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/wrappers.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py | Apache-2.0 |
def transform(self, results):
"""Perform PytorchVideoTrans augmentations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
assert 'imgs' in results
assert 'gt_bboxes' not in results,\
... | Perform PytorchVideoTrans augmentations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/wrappers.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py | Apache-2.0 |
def default_transforms():
"""Default transforms for imgaug.
Implement RandAugment by imgaug.
Please visit `https://arxiv.org/abs/1909.13719` for more information.
Augmenters and hyper parameters are borrowed from the following repo:
https://github.com/tensorflow/tpu/blob/master... | Default transforms for imgaug.
Implement RandAugment by imgaug.
Please visit `https://arxiv.org/abs/1909.13719` for more information.
Augmenters and hyper parameters are borrowed from the following repo:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaug... | default_transforms | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/wrappers.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py | Apache-2.0 |
def imgaug_builder(self, cfg):
"""Import a module from imgaug.
It follows the logic of :func:`build_from_cfg`. Use a dict object to
create an iaa.Augmenter object.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
Returns:
obj:`i... | Import a module from imgaug.
It follows the logic of :func:`build_from_cfg`. Use a dict object to
create an iaa.Augmenter object.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
Returns:
obj:`iaa.Augmenter`: The constructed imgaug augm... | imgaug_builder | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/wrappers.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py | Apache-2.0 |
def transform(self, results):
"""Perform Imgaug augmentations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
"""
assert results['modality'] == 'RGB', 'Imgaug only support RGB images.'
in_type = r... | Perform Imgaug augmentations.
Args:
results (dict): The resulting dict to be modified and passed
to the next transform in pipeline.
| transform | python | open-mmlab/mmaction2 | mmaction/datasets/transforms/wrappers.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/datasets/transforms/wrappers.py | Apache-2.0 |
def _draw_samples(self,
batch_idx: int,
data_batch: dict,
data_samples: Sequence[ActionDataSample],
step: int = 0) -> None:
"""Visualize every ``self.interval`` samples from a data batch.
Args:
batch_idx... | Visualize every ``self.interval`` samples from a data batch.
Args:
batch_idx (int): The index of the current batch in the val loop.
data_batch (dict): Data from dataloader.
outputs (Sequence[:obj:`ActionDataSample`]): Outputs from model.
step (int): Global step v... | _draw_samples | python | open-mmlab/mmaction2 | mmaction/engine/hooks/visualization_hook.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/hooks/visualization_hook.py | Apache-2.0 |
def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
outputs: Sequence[ActionDataSample]) -> None:
"""Visualize every ``self.interval`` samples during validation.
Args:
runner (:obj:`Runner`): The runner of the validation process.
bat... | Visualize every ``self.interval`` samples during validation.
Args:
runner (:obj:`Runner`): The runner of the validation process.
batch_idx (int): The index of the current batch in the val loop.
data_batch (dict): Data from dataloader.
outputs (Sequence[:obj:`Acti... | after_val_iter | python | open-mmlab/mmaction2 | mmaction/engine/hooks/visualization_hook.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/hooks/visualization_hook.py | Apache-2.0 |
def after_test_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
outputs: Sequence[ActionDataSample]) -> None:
"""Visualize every ``self.interval`` samples during test.
Args:
runner (:obj:`Runner`): The runner of the testing process.
batch_idx ... | Visualize every ``self.interval`` samples during test.
Args:
runner (:obj:`Runner`): The runner of the testing process.
batch_idx (int): The index of the current batch in the test loop.
data_batch (dict): Data from dataloader.
outputs (Sequence[:obj:`DetDataSampl... | after_test_iter | python | open-mmlab/mmaction2 | mmaction/engine/hooks/visualization_hook.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/hooks/visualization_hook.py | Apache-2.0 |
def conv_branch_init(conv: nn.Module, branches: int) -> None:
"""Perform initialization for a conv branch.
Args:
conv (nn.Module): The conv module of a branch.
branches (int): The number of branches.
"""
weight = conv.weight
n = weight.size(0)
k1 = weight.size(1)
k2 = weigh... | Perform initialization for a conv branch.
Args:
conv (nn.Module): The conv module of a branch.
branches (int): The number of branches.
| conv_branch_init | python | open-mmlab/mmaction2 | mmaction/engine/model/weight_init.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/model/weight_init.py | Apache-2.0 |
def get_layer_id_for_vit(var_name: str, max_layer_id: int) -> int:
"""Get the layer id to set the different learning rates for ViT.
Args:
var_name (str): The key of the model.
num_max_layer (int): Maximum number of backbone layers.
Returns:
int: Returns the layer id of the key.
... | Get the layer id to set the different learning rates for ViT.
Args:
var_name (str): The key of the model.
num_max_layer (int): Maximum number of backbone layers.
Returns:
int: Returns the layer id of the key.
| get_layer_id_for_vit | python | open-mmlab/mmaction2 | mmaction/engine/optimizers/layer_decay_optim_wrapper_constructor.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/optimizers/layer_decay_optim_wrapper_constructor.py | Apache-2.0 |
def get_layer_id_for_mvit(var_name, max_layer_id):
"""Get the layer id to set the different learning rates in ``layer_wise``
decay_type.
Args:
var_name (str): The key of the model.
max_layer_id (int): Maximum layer id.
Returns:
int: The id number corresponding to different lear... | Get the layer id to set the different learning rates in ``layer_wise``
decay_type.
Args:
var_name (str): The key of the model.
max_layer_id (int): Maximum layer id.
Returns:
int: The id number corresponding to different learning rate in
``LearningRateDecayOptimizerConstruct... | get_layer_id_for_mvit | python | open-mmlab/mmaction2 | mmaction/engine/optimizers/layer_decay_optim_wrapper_constructor.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/optimizers/layer_decay_optim_wrapper_constructor.py | Apache-2.0 |
def add_params(self, params: List[dict], module: nn.Module,
**kwargs) -> None:
"""Add all parameters of module to the params list.
The parameters of the given module will be added to the list of param
groups, with specific rules defined by paramwise_cfg.
Args:
... | Add all parameters of module to the params list.
The parameters of the given module will be added to the list of param
groups, with specific rules defined by paramwise_cfg.
Args:
params (list[dict]): A list of param groups, it will be modified
in place.
... | add_params | python | open-mmlab/mmaction2 | mmaction/engine/optimizers/layer_decay_optim_wrapper_constructor.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/optimizers/layer_decay_optim_wrapper_constructor.py | Apache-2.0 |
def add_params(self,
params: List[dict],
module: nn.Module,
prefix: str = 'base',
**kwargs) -> None:
"""Add all parameters of module to the params list.
The parameters of the given module will be added to the list of param
... | Add all parameters of module to the params list.
The parameters of the given module will be added to the list of param
groups, with specific rules defined by paramwise_cfg.
Args:
params (list[dict]): A list of param groups, it will be modified
in place.
... | add_params | python | open-mmlab/mmaction2 | mmaction/engine/optimizers/swin_optim_wrapper_constructor.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/optimizers/swin_optim_wrapper_constructor.py | Apache-2.0 |
def add_params(self, params, model, **kwargs):
"""Add parameters and their corresponding lr and wd to the params.
Args:
params (list): The list to be modified, containing all parameter
groups and their corresponding lr and wd configurations.
model (nn.Module): Th... | Add parameters and their corresponding lr and wd to the params.
Args:
params (list): The list to be modified, containing all parameter
groups and their corresponding lr and wd configurations.
model (nn.Module): The model to be trained with the optimizer.
| add_params | python | open-mmlab/mmaction2 | mmaction/engine/optimizers/tsm_optim_wrapper_constructor.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/engine/optimizers/tsm_optim_wrapper_constructor.py | Apache-2.0 |
def confusion_matrix(y_pred, y_real, normalize=None):
"""Compute confusion matrix.
Args:
y_pred (list[int] | np.ndarray[int]): Prediction labels.
y_real (list[int] | np.ndarray[int]): Ground truth labels.
normalize (str | None): Normalizes confusion matrix over the true
(row... | Compute confusion matrix.
Args:
y_pred (list[int] | np.ndarray[int]): Prediction labels.
y_real (list[int] | np.ndarray[int]): Ground truth labels.
normalize (str | None): Normalizes confusion matrix over the true
(rows), predicted (columns) conditions or all the population.
... | confusion_matrix | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def mean_class_accuracy(scores, labels):
"""Calculate mean class accuracy.
Args:
scores (list[np.ndarray]): Prediction scores for each class.
labels (list[int]): Ground truth labels.
Returns:
np.ndarray: Mean class accuracy.
"""
pred = np.argmax(scores, axis=1)
cf_mat =... | Calculate mean class accuracy.
Args:
scores (list[np.ndarray]): Prediction scores for each class.
labels (list[int]): Ground truth labels.
Returns:
np.ndarray: Mean class accuracy.
| mean_class_accuracy | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def top_k_classes(scores, labels, k=10, mode='accurate'):
"""Calculate the most K accurate (inaccurate) classes.
Given the prediction scores, ground truth label and top-k value,
compute the top K accurate (inaccurate) classes.
Args:
scores (list[np.ndarray]): Prediction scores for each class.
... | Calculate the most K accurate (inaccurate) classes.
Given the prediction scores, ground truth label and top-k value,
compute the top K accurate (inaccurate) classes.
Args:
scores (list[np.ndarray]): Prediction scores for each class.
labels (list[int] | np.ndarray): Ground truth labels.
... | top_k_classes | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def top_k_accuracy(scores, labels, topk=(1, )):
"""Calculate top k accuracy score.
Args:
scores (list[np.ndarray]): Prediction scores for each class.
labels (list[int]): Ground truth labels.
topk (tuple[int]): K value for top_k_accuracy. Default: (1, ).
Returns:
list[float]... | Calculate top k accuracy score.
Args:
scores (list[np.ndarray]): Prediction scores for each class.
labels (list[int]): Ground truth labels.
topk (tuple[int]): K value for top_k_accuracy. Default: (1, ).
Returns:
list[float]: Top k accuracy score for each k.
| top_k_accuracy | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def mean_average_precision(scores, labels):
"""Mean average precision for multi-label recognition.
Args:
scores (list[np.ndarray]): Prediction scores of different classes for
each sample.
labels (list[np.ndarray]): Ground truth many-hot vector for each
sample.
Retur... | Mean average precision for multi-label recognition.
Args:
scores (list[np.ndarray]): Prediction scores of different classes for
each sample.
labels (list[np.ndarray]): Ground truth many-hot vector for each
sample.
Returns:
np.float64: The mean average precision.... | mean_average_precision | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def binary_precision_recall_curve(y_score, y_true):
"""Calculate the binary precision recall curve at step thresholds.
Args:
y_score (np.ndarray): Prediction scores for each class.
Shape should be (num_classes, ).
y_true (np.ndarray): Ground truth many-hot vector.
Shape ... | Calculate the binary precision recall curve at step thresholds.
Args:
y_score (np.ndarray): Prediction scores for each class.
Shape should be (num_classes, ).
y_true (np.ndarray): Ground truth many-hot vector.
Shape should be (num_classes, ).
Returns:
precision ... | binary_precision_recall_curve | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def pairwise_temporal_iou(candidate_segments,
target_segments,
calculate_overlap_self=False):
"""Compute intersection over union between segments.
Args:
candidate_segments (np.ndarray): 1-dim/2-dim array in format
``[init, end]/[m x 2:=[in... | Compute intersection over union between segments.
Args:
candidate_segments (np.ndarray): 1-dim/2-dim array in format
``[init, end]/[m x 2:=[init, end]]``.
target_segments (np.ndarray): 2-dim array in format
``[n x 2:=[init, end]]``.
calculate_overlap_self (bool): Whe... | pairwise_temporal_iou | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def average_recall_at_avg_proposals(ground_truth,
proposals,
total_num_proposals,
max_avg_proposals=None,
temporal_iou_thresholds=np.linspace(
... | Computes the average recall given an average number (percentile) of
proposals per video.
Args:
ground_truth (dict): Dict containing the ground truth instances.
proposals (dict): Dict containing the proposal instances.
total_num_proposals (int): Total number of proposals in the
... | average_recall_at_avg_proposals | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def get_weighted_score(score_list, coeff_list):
"""Get weighted score with given scores and coefficients.
Given n predictions by different classifier: [score_1, score_2, ...,
score_n] (score_list) and their coefficients: [coeff_1, coeff_2, ...,
coeff_n] (coeff_list), return weighted score: weighted_sco... | Get weighted score with given scores and coefficients.
Given n predictions by different classifier: [score_1, score_2, ...,
score_n] (score_list) and their coefficients: [coeff_1, coeff_2, ...,
coeff_n] (coeff_list), return weighted score: weighted_score =
score_1 * coeff_1 + score_2 * coeff_2 + ... + ... | get_weighted_score | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def softmax(x, dim=1):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x, axis=dim, keepdims=True))
return e_x / e_x.sum(axis=dim, keepdims=True) | Compute softmax values for each sets of scores in x. | softmax | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def average_precision_at_temporal_iou(ground_truth,
prediction,
temporal_iou_thresholds=(np.linspace(
0.5, 0.95, 10))):
"""Compute average precision (in detection task) between ground truth and
... | Compute average precision (in detection task) between ground truth and
predicted data frames. If multiple predictions match the same predicted
segment, only the one with highest score is matched as true positive. This
code is greatly inspired by Pascal VOC devkit.
Args:
ground_truth (dict): Dic... | average_precision_at_temporal_iou | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/accuracy.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/accuracy.py | Apache-2.0 |
def det2csv(results, custom_classes):
"""Convert detection results to csv file."""
csv_results = []
for idx in range(len(results)):
video_id = results[idx]['video_id']
timestamp = results[idx]['timestamp']
result = results[idx]['outputs']
for label, _ in enumerate(result):
... | Convert detection results to csv file. | det2csv | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_utils.py | Apache-2.0 |
def results2csv(results, out_file, custom_classes=None):
"""Convert detection results to csv file."""
csv_results = det2csv(results, custom_classes)
# save space for float
def to_str(item):
if isinstance(item, float):
return f'{item:.4f}'
return str(item)
with open(out_... | Convert detection results to csv file. | results2csv | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_utils.py | Apache-2.0 |
def read_csv(csv_file, class_whitelist=None):
"""Loads boxes and class labels from a CSV file in the AVA format.
CSV file format described at https://research.google.com/ava/download.html.
Args:
csv_file: A file object.
class_whitelist: If provided, boxes corresponding to (integer) class
... | Loads boxes and class labels from a CSV file in the AVA format.
CSV file format described at https://research.google.com/ava/download.html.
Args:
csv_file: A file object.
class_whitelist: If provided, boxes corresponding to (integer) class
labels not in this set are skipped.
Retur... | read_csv | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_utils.py | Apache-2.0 |
def read_exclusions(exclusions_file):
"""Reads a CSV file of excluded timestamps.
Args:
exclusions_file: A file object containing a csv of video-id,timestamp.
Returns:
A set of strings containing excluded image keys, e.g.
"aaaaaaaaaaa,0904",
or an empty set if exclusions fi... | Reads a CSV file of excluded timestamps.
Args:
exclusions_file: A file object containing a csv of video-id,timestamp.
Returns:
A set of strings containing excluded image keys, e.g.
"aaaaaaaaaaa,0904",
or an empty set if exclusions file is None.
| read_exclusions | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_utils.py | Apache-2.0 |
def read_labelmap(labelmap_file):
"""Reads a labelmap without the dependency on protocol buffers.
Args:
labelmap_file: A file object containing a label map protocol buffer.
Returns:
labelmap: The label map in the form used by the
object_detection_evaluation
module - a list ... | Reads a labelmap without the dependency on protocol buffers.
Args:
labelmap_file: A file object containing a label map protocol buffer.
Returns:
labelmap: The label map in the form used by the
object_detection_evaluation
module - a list of {"id": integer, "name": classname } di... | read_labelmap | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_utils.py | Apache-2.0 |
def _import_ground_truth(ground_truth_filename):
"""Read ground truth file and return the ground truth instances and the
activity classes.
Args:
ground_truth_filename (str): Full path to the ground truth json
file.
Returns:
tuple[list, dict]: (gr... | Read ground truth file and return the ground truth instances and the
activity classes.
Args:
ground_truth_filename (str): Full path to the ground truth json
file.
Returns:
tuple[list, dict]: (ground_truth, activity_index).
ground_truth co... | _import_ground_truth | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/eval_detection.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py | Apache-2.0 |
def _import_prediction(self, prediction_filename):
"""Read prediction file and return the prediction instances.
Args:
prediction_filename (str): Full path to the prediction json file.
Returns:
List: List containing the prediction instances (dictionaries).
"""
... | Read prediction file and return the prediction instances.
Args:
prediction_filename (str): Full path to the prediction json file.
Returns:
List: List containing the prediction instances (dictionaries).
| _import_prediction | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/eval_detection.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py | Apache-2.0 |
def wrapper_compute_average_precision(self):
"""Computes average precision for each class."""
ap = np.zeros((len(self.tiou_thresholds), len(self.activity_index)))
# Adaptation to query faster
ground_truth_by_label = []
prediction_by_label = []
for i in range(len(self.act... | Computes average precision for each class. | wrapper_compute_average_precision | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/eval_detection.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py | Apache-2.0 |
def evaluate(self):
"""Evaluates a prediction file.
For the detection task we measure the interpolated mean average
precision to measure the performance of a method.
"""
self.ap = self.wrapper_compute_average_precision()
self.mAP = self.ap.mean(axis=1)
self.aver... | Evaluates a prediction file.
For the detection task we measure the interpolated mean average
precision to measure the performance of a method.
| evaluate | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/eval_detection.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py | Apache-2.0 |
def compute_average_precision_detection(ground_truth,
prediction,
tiou_thresholds=np.linspace(
0.5, 0.95, 10)):
"""Compute average precision (detection task) between ground truth and
predi... | Compute average precision (detection task) between ground truth and
predictions data frames. If multiple predictions occurs for the same
predicted segment, only the one with highest score is matches as true
positive. This code is greatly inspired by Pascal VOC devkit.
Args:
ground_truth (list[d... | compute_average_precision_detection | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/eval_detection.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py | Apache-2.0 |
def overlap2d_voc(b1, b2):
"""Compute the overlaps between a set of boxes b1 and one box b2."""
xmin = np.maximum(b1[:, 0], b2[:, 0])
ymin = np.maximum(b1[:, 1], b2[:, 1])
xmax = np.minimum(b1[:, 2], b2[:, 2])
ymax = np.minimum(b1[:, 3], b2[:, 3])
width = np.maximum(0, xmax - xmin)
height =... | Compute the overlaps between a set of boxes b1 and one box b2. | overlap2d_voc | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/multisports_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py | Apache-2.0 |
def iou2d_voc(b1, b2):
"""Compute the IoU between a set of boxes b1 and 1 box b2."""
if b1.ndim == 1:
b1 = b1[None, :]
if b2.ndim == 1:
b2 = b2[None, :]
assert b2.shape[0] == 1
ov = overlap2d_voc(b1, b2)
return ov / (area2d_voc(b1) + area2d_voc(b2) - ov) | Compute the IoU between a set of boxes b1 and 1 box b2. | iou2d_voc | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/multisports_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py | Apache-2.0 |
def iou3d_voc(b1, b2):
"""Compute the IoU between two tubes with same temporal extent."""
assert b1.shape[0] == b2.shape[0]
assert np.all(b1[:, 0] == b2[:, 0])
ov = overlap2d_voc(b1[:, 1:5], b2[:, 1:5])
return np.mean(ov / (area2d_voc(b1[:, 1:5]) + area2d_voc(b2[:, 1:5]) - ov)) | Compute the IoU between two tubes with same temporal extent. | iou3d_voc | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/multisports_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py | Apache-2.0 |
def iou3dt_voc(b1, b2, spatialonly=False, temporalonly=False):
"""Compute the spatio-temporal IoU between two tubes."""
tmin = max(b1[0, 0], b2[0, 0])
tmax = min(b1[-1, 0], b2[-1, 0])
if tmax < tmin:
return 0.0
temporal_inter = tmax - tmin
temporal_union = max(b1[-1, 0], b2[-1, 0]) - m... | Compute the spatio-temporal IoU between two tubes. | iou3dt_voc | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/multisports_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py | Apache-2.0 |
def nms_tubelets(dets, overlapThresh=0.3, top_k=None):
"""Compute the NMS for a set of scored tubelets scored tubelets are numpy
array with 4K+1 columns, last one being the score return the indices of the
tubelets to keep."""
# If there are no detections, return an empty list
if len(dets) == 0:
... | Compute the NMS for a set of scored tubelets scored tubelets are numpy
array with 4K+1 columns, last one being the score return the indices of the
tubelets to keep. | nms_tubelets | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/multisports_utils.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py | Apache-2.0 |
def compute_precision_recall(scores, labels, num_gt):
"""Compute precision and recall.
Args:
scores: A float numpy array representing detection score
labels: A boolean numpy array representing true/false positive labels
num_gt: Number of ground truth instances
Raises:
Value... | Compute precision and recall.
Args:
scores: A float numpy array representing detection score
labels: A boolean numpy array representing true/false positive labels
num_gt: Number of ground truth instances
Raises:
ValueError: if the input is not of the correct format
Returns... | compute_precision_recall | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/metrics.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/metrics.py | Apache-2.0 |
def compute_average_precision(precision, recall):
"""Compute Average Precision according to the definition in VOCdevkit.
Precision is modified to ensure that it does not decrease as recall
decrease.
Args:
precision: A float [N, 1] numpy array of precisions
recall: A float [N, 1] numpy ... | Compute Average Precision according to the definition in VOCdevkit.
Precision is modified to ensure that it does not decrease as recall
decrease.
Args:
precision: A float [N, 1] numpy array of precisions
recall: A float [N, 1] numpy array of recalls
Raises:
ValueError: if the ... | compute_average_precision | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/metrics.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/metrics.py | Apache-2.0 |
def compute_cor_loc(num_gt_imgs_per_class,
num_images_correctly_detected_per_class):
"""Compute CorLoc according to the definition in the following paper.
https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf
Returns nans if there are no ground truth images for a class.
... | Compute CorLoc according to the definition in the following paper.
https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf
Returns nans if there are no ground truth images for a class.
Args:
num_gt_imgs_per_class: 1D array, representing number of images
containing at least one... | compute_cor_loc | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/metrics.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/metrics.py | Apache-2.0 |
def __init__(self, data):
"""Constructs box collection.
Args:
data: a numpy array of shape [N, 4] representing box coordinates
Raises:
ValueError: if bbox data is not a numpy array
ValueError: if invalid dimensions for bbox data
"""
if not is... | Constructs box collection.
Args:
data: a numpy array of shape [N, 4] representing box coordinates
Raises:
ValueError: if bbox data is not a numpy array
ValueError: if invalid dimensions for bbox data
| __init__ | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_list.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py | Apache-2.0 |
def add_field(self, field, field_data):
"""Add data to a specified field.
Args:
field: a string parameter used to specify a related field to be
accessed.
field_data: a numpy array of [N, ...] representing the data
associated with the field.
... | Add data to a specified field.
Args:
field: a string parameter used to specify a related field to be
accessed.
field_data: a numpy array of [N, ...] representing the data
associated with the field.
Raises:
ValueError: if the field is a... | add_field | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_list.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py | Apache-2.0 |
def get_field(self, field):
"""Accesses data associated with the specified field in the box
collection.
Args:
field: a string parameter used to specify a related field to be
accessed.
Returns:
a numpy 1-d array representing data of an associated ... | Accesses data associated with the specified field in the box
collection.
Args:
field: a string parameter used to specify a related field to be
accessed.
Returns:
a numpy 1-d array representing data of an associated field
Raises:
Valu... | get_field | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_list.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py | Apache-2.0 |
def get_coordinates(self):
"""Get corner coordinates of boxes.
Returns:
a list of 4 1-d numpy arrays [y_min, x_min, y_max, x_max]
"""
box_coordinates = self.get()
y_min = box_coordinates[:, 0]
x_min = box_coordinates[:, 1]
y_max = box_coordinates[:, 2... | Get corner coordinates of boxes.
Returns:
a list of 4 1-d numpy arrays [y_min, x_min, y_max, x_max]
| get_coordinates | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_list.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py | Apache-2.0 |
def _is_valid_boxes(data):
"""Check whether data fulfills the format of N*[ymin, xmin, ymax,
xmin].
Args:
data: a numpy array of shape [N, 4] representing box coordinates
Returns:
a boolean indicating whether all ymax of boxes are equal or greater
th... | Check whether data fulfills the format of N*[ymin, xmin, ymax,
xmin].
Args:
data: a numpy array of shape [N, 4] representing box coordinates
Returns:
a boolean indicating whether all ymax of boxes are equal or greater
than ymin, and all xmax of boxes are equ... | _is_valid_boxes | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_list.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py | Apache-2.0 |
def intersection(boxes1, boxes2):
"""Compute pairwise intersection areas between boxes.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes
boxes2: a numpy array with shape [M, 4] holding M boxes
Returns:
a numpy array with shape [N*M] representing pairwise intersection a... | Compute pairwise intersection areas between boxes.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes
boxes2: a numpy array with shape [M, 4] holding M boxes
Returns:
a numpy array with shape [N*M] representing pairwise intersection area
| intersection | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_ops.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_ops.py | Apache-2.0 |
def iou(boxes1, boxes2):
"""Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding N boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou ... | Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding N boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou scores.
| iou | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_ops.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_ops.py | Apache-2.0 |
def ioa(boxes1, boxes2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
... | Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a numpy array with s... | ioa | python | open-mmlab/mmaction2 | mmaction/evaluation/functional/ava_evaluation/np_box_ops.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_ops.py | Apache-2.0 |
def process(self, data_batch: Sequence[Tuple[Any, Dict]],
data_samples: Sequence[Dict]) -> None:
"""Process one batch of data samples and data_samples. The processed
results should be stored in ``self.results``, which will be used to
compute the metrics when all batches have been... | Process one batch of data samples and data_samples. The processed
results should be stored in ``self.results``, which will be used to
compute the metrics when all batches have been processed.
Args:
data_batch (Sequence[dict]): A batch of data from the dataloader.
data_sa... | process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/acc_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/acc_metric.py | Apache-2.0 |
def compute_metrics(self, results: List) -> Dict:
"""Compute the metrics from processed results.
Args:
results (list): The processed results of each batch.
Returns:
dict: The computed metrics. The keys are the names of the metrics,
and the values are corresp... | Compute the metrics from processed results.
Args:
results (list): The processed results of each batch.
Returns:
dict: The computed metrics. The keys are the names of the metrics,
and the values are corresponding results.
| compute_metrics | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/acc_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/acc_metric.py | Apache-2.0 |
def calculate(self, preds: List[np.ndarray],
labels: List[Union[int, np.ndarray]]) -> Dict:
"""Compute the metrics from processed results.
Args:
preds (list[np.ndarray]): List of the prediction scores.
labels (list[int | np.ndarray]): List of the labels.
... | Compute the metrics from processed results.
Args:
preds (list[np.ndarray]): List of the prediction scores.
labels (list[int | np.ndarray]): List of the labels.
Returns:
dict: The computed metrics. The keys are the names of the metrics,
and the values are... | calculate | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/acc_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/acc_metric.py | Apache-2.0 |
def calculate(pred, target, num_classes=None) -> dict:
"""Calculate the confusion matrix for single-label task.
Args:
pred (torch.Tensor | np.ndarray | Sequence): The prediction
results. It can be labels (N, ), or scores of every
class (N, C).
tar... | Calculate the confusion matrix for single-label task.
Args:
pred (torch.Tensor | np.ndarray | Sequence): The prediction
results. It can be labels (N, ), or scores of every
class (N, C).
target (torch.Tensor | np.ndarray | Sequence): The target of
... | calculate | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/acc_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/acc_metric.py | Apache-2.0 |
def plot(confusion_matrix: torch.Tensor,
include_values: bool = False,
cmap: str = 'viridis',
classes: Optional[List[str]] = None,
colorbar: bool = True,
show: bool = True):
"""Draw a confusion matrix by matplotlib.
Modified from `Scikit-... | Draw a confusion matrix by matplotlib.
Modified from `Scikit-Learn
<https://github.com/scikit-learn/scikit-learn/blob/dc580a8ef/sklearn/metrics/_plot/confusion_matrix.py#L81>`_
Args:
confusion_matrix (torch.Tensor): The confusion matrix to draw.
include_values (bool): W... | plot | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/acc_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/acc_metric.py | Apache-2.0 |
def process(self, data_batch: Sequence[Tuple[Any, dict]],
predictions: Sequence[dict]) -> None:
"""Process one batch of data samples and predictions. The processed
results should be stored in ``self.results``, which will be used to
compute the metrics when all batches have been p... | Process one batch of data samples and predictions. The processed
results should be stored in ``self.results``, which will be used to
compute the metrics when all batches have been processed.
Args:
data_batch (Sequence[Tuple[Any, dict]]): A batch of data
from the data... | process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/anet_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py | Apache-2.0 |
def compute_metrics(self, results: list) -> dict:
"""Compute the metrics from processed results.
If `metric_type` is 'TEM', only dump middle results and do not compute
any metrics.
Args:
results (list): The processed results of each batch.
Returns:
dict: ... | Compute the metrics from processed results.
If `metric_type` is 'TEM', only dump middle results and do not compute
any metrics.
Args:
results (list): The processed results of each batch.
Returns:
dict: The computed metrics. The keys are the names of the metrics,
... | compute_metrics | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/anet_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py | Apache-2.0 |
def dump_results(self, results, version='VERSION 1.3'):
"""Save middle or final results to disk."""
if self.output_format == 'json':
result_dict = self.proposals2json(results)
output_dict = {
'version': version,
'results': result_dict,
... | Save middle or final results to disk. | dump_results | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/anet_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py | Apache-2.0 |
def proposals2json(results, show_progress=False):
"""Convert all proposals to a final dict(json) format.
Args:
results (list[dict]): All proposals.
show_progress (bool): Whether to show the progress bar.
Defaults: False.
Returns:
dict: The fina... | Convert all proposals to a final dict(json) format.
Args:
results (list[dict]): All proposals.
show_progress (bool): Whether to show the progress bar.
Defaults: False.
Returns:
dict: The final result dict. E.g.
.. code-block:: Python
... | proposals2json | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/anet_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py | Apache-2.0 |
def process(self, data_batch: Sequence[Tuple[Any, dict]],
data_samples: Sequence[dict]) -> None:
"""Process one batch of data samples and predictions. The processed
results should be stored in ``self.results``, which will be used to
compute the metrics when all batches have been ... | Process one batch of data samples and predictions. The processed
results should be stored in ``self.results``, which will be used to
compute the metrics when all batches have been processed.
Args:
data_batch (Sequence[Tuple[Any, dict]]): A batch of data
from the data... | process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/ava_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/ava_metric.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.