id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
36,946 | import os
import sys
import time
import openai
from openai import OpenAI
from validate_json import validate_json
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def validate_json(data_path: str) -> None:
# Load dataset
with open(data_path) as f:
dataset = [json.loads(line) for line in f]
# We... | null |
36,947 | import re
from typing import List, Optional, Tuple
import pandas as pd
from llama_index.indices.utils import extract_numbers_given_response
from llama_index.llms import OpenAI
from llama_index.prompts import BasePromptTemplate, PromptTemplate
from sklearn.model_selection import train_test_split
The provided code snipp... | Get train and eval data. |
36,948 | import re
from typing import List, Optional, Tuple
import pandas as pd
from llama_index.indices.utils import extract_numbers_given_response
from llama_index.llms import OpenAI
from llama_index.prompts import BasePromptTemplate, PromptTemplate
from sklearn.model_selection import train_test_split
def get_sorted_dict_str(... | Get train str. |
36,949 | import re
from typing import List, Optional, Tuple
import pandas as pd
from llama_index.indices.utils import extract_numbers_given_response
from llama_index.llms import OpenAI
from llama_index.prompts import BasePromptTemplate, PromptTemplate
from sklearn.model_selection import train_test_split
def get_sorted_dict_str(... | Get eval preds. |
36,950 | import os
import tempfile
from typing import List, Union
import streamlit as st
import tiktoken
from langchain.text_splitter import (
CharacterTextSplitter,
RecursiveCharacterTextSplitter,
)
from langchain.text_splitter import (
TextSplitter as LCSplitter,
)
from langchain.text_splitter import TokenTextSpli... | null |
36,951 | from argparse import Namespace, _SubParsersAction
from .configuration import load_index
def query_cli(args: Namespace) -> None:
"""Handle subcommand "query"."""
index = load_index()
query_engine = index.as_query_engine()
print(query_engine.query(args.query))
The provided code snippet includes necessary... | Register subcommand "query" to ArgumentParser. |
36,952 | from argparse import Namespace, _SubParsersAction
from .configuration import load_config, save_config
def init_cli(args: Namespace) -> None:
"""Handle subcommand "init"."""
config = load_config(args.directory)
save_config(config, args.directory)
The provided code snippet includes necessary dependencies for... | Register subcommand "init" to ArgumentParser. |
36,953 | import os
from argparse import Namespace, _SubParsersAction
from llama_index import SimpleDirectoryReader
from .configuration import load_index, save_index
def add_cli(args: Namespace) -> None:
"""Handle subcommand "add"."""
index = load_index()
for p in args.files:
if not os.path.exists(p):
... | Register subcommand "add" to ArgumentParser. |
36,954 | import os
import os.path as osp
import platform
import shutil
import sys
import warnings
from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content | null |
36,955 | import os
import os.path as osp
import platform
import shutil
import sys
import warnings
from setuptools import find_packages, setup
version_file = 'mmpose/version.py'
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
import sys
# return short vers... | null |
36,956 | import os
import os.path as osp
import platform
import shutil
import sys
import warnings
from setuptools import find_packages, setup
The provided code snippet includes necessary dependencies for implementing the `parse_requirements` function. Write a Python function `def parse_requirements(fname='requirements.txt', wi... | Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_r... |
36,957 | import os
import os.path as osp
import platform
import shutil
import sys
import warnings
from setuptools import find_packages, setup
The provided code snippet includes necessary dependencies for implementing the `add_mim_extension` function. Write a Python function `def add_mim_extension()` to solve the following prob... | Add extra files that are required to support MIM into the package. These files will be added by creating a symlink to the originals if the package is installed in `editable` mode (e.g. pip install -e .), or by copying from the originals otherwise. |
36,958 | import functools as func
import glob
import re
from os.path import basename, splitext
import numpy as np
import titlecase
def anchor(name):
return re.sub(r'-+', '-', re.sub(r'[^a-zA-Z0-9]', '-',
name.strip().lower())).strip('-') | null |
36,959 | import os
import subprocess
import sys
import pytorch_sphinx_theme
version_file = '../../mmpose/version.py'
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] | null |
36,960 | import os
import subprocess
import sys
import pytorch_sphinx_theme
def builder_inited_handler(app):
subprocess.run(['./collect.py'])
subprocess.run(['./merge_docs.sh'])
subprocess.run(['./stats.py'])
def setup(app):
app.connect('builder-inited', builder_inited_handler) | null |
36,964 | import os
import warnings
from argparse import ArgumentParser
import cv2
from mmpose.apis import (inference_top_down_pose_model, init_pose_model,
vis_pose_tracking_result)
from mmpose.datasets import DatasetInfo
The provided code snippet includes necessary dependencies for implementing the `pr... | Process mmtracking results. :param mmtracking_results: :return: a list of tracked bounding boxes |
36,965 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import numpy as np
from mmpose.apis import (get_track_id, inference_top_down_pose_model,
init_pose_model, vis_pose_result)
from mmpose.core import apply_bugeye_... | null |
36,966 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import numpy as np
from mmpose.apis import (get_track_id, inference_top_down_pose_model,
init_pose_model, vis_pose_result)
from mmpose.core import apply_bugeye_... | null |
36,967 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import numpy as np
from mmpose.apis import (get_track_id, inference_top_down_pose_model,
init_pose_model, vis_pose_result)
from mmpose.core import apply_bugeye_... | null |
36,968 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import numpy as np
from mmpose.apis import (get_track_id, inference_top_down_pose_model,
init_pose_model, vis_pose_result)
from mmpose.core import apply_bugeye_... | null |
36,969 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import numpy as np
from mmpose.apis import (get_track_id, inference_top_down_pose_model,
init_pose_model, vis_pose_result)
from mmpose.core import apply_bugeye_... | null |
36,970 | import os
import warnings
from argparse import ArgumentParser
import cv2
from mmpose.apis import (inference_top_down_pose_model, init_pose_model,
vis_pose_result)
from mmpose.datasets import DatasetInfo
The provided code snippet includes necessary dependencies for implementing the `process_fac... | Process det results, and return a list of bboxes. :param face_det_results: (top, right, bottom and left) :return: a list of detected bounding boxes (x,y,x,y)-format |
36,971 | import os
import os.path as osp
from argparse import ArgumentParser
import mmcv
import numpy as np
from xtcocotools.coco import COCO
from mmpose.apis import inference_interhand_3d_model, vis_3d_pose_result
from mmpose.apis.inference import init_pose_model
from mmpose.core import SimpleCamera
The provided code snippet ... | Transform the camera parameters in interhand2.6m dataset to the format of SimpleCamera. Args: interhand_camera_param (dict): camera parameters including: - camrot: 3x3, camera rotation matrix (world-to-camera) - campos: 3x1, camera location in world space - focal: 2x1, camera focal length - princpt: 2x1, camera center ... |
36,972 | import os
import warnings
from argparse import ArgumentParser
from mmpose.apis import (inference_top_down_pose_model, init_pose_model,
vis_pose_result)
from mmpose.datasets import DatasetInfo
The provided code snippet includes necessary dependencies for implementing the `process_face_det_resul... | Process det results, and return a list of bboxes. :param face_det_results: (top, right, bottom and left) :return: a list of detected bounding boxes (x,y,x,y)-format |
36,973 | import copy
import os
import os.path as osp
from argparse import ArgumentParser
import cv2
import mmcv
import numpy as np
from mmpose.apis import (extract_pose_sequence, get_track_id,
inference_pose_lifter_model,
inference_top_down_pose_model, init_pose_model,
... | Convert pose det dataset keypoints definition to pose lifter dataset keypoints definition. Args: keypoints (ndarray[K, 2 or 3]): 2D keypoints to be transformed. pose_det_dataset, (str): Name of the dataset for 2D pose detector. pose_lift_dataset (str): Name of the dataset for pose lifter model. |
36,974 | import os
import os.path as osp
import warnings
from argparse import ArgumentParser
import mmcv
import numpy as np
from xtcocotools.coco import COCO
from mmpose.apis import (inference_pose_lifter_model,
inference_top_down_pose_model, vis_3d_pose_result)
from mmpose.apis.inference import init_po... | Project 3D keypoints from the camera space to the world space. Args: keypoints (np.ndarray): 3D keypoints in shape [..., 3] camera_params (dict): Parameters for all cameras. image_name (str): The image name to specify the camera. dataset (str): The dataset type, e.g. Body3DH36MDataset. |
36,976 | import warnings
import mmcv
import numpy as np
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (DistSamplerSeedHook, EpochBasedRunner, OptimizerHook,
get_dist_info)
from mmcv.utils import digit_version
fro... | Initialize random seed. If the seed is not set, the seed will be automatically randomized, and then broadcast to all processes to prevent some potential bugs. Args: seed (int, Optional): The seed. Default to None. device (str): The device where the seed will be put on. Default to 'cuda'. Returns: int: Seed to be used. |
36,977 | import warnings
import mmcv
import numpy as np
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (DistSamplerSeedHook, EpochBasedRunner, OptimizerHook,
get_dist_info)
from mmcv.utils import digit_version
fro... | Train model entry function. Args: model (nn.Module): The model to be trained. dataset (Dataset): Train dataset. cfg (dict): The config dict for training. distributed (bool): Whether to use distributed training. Default: False. validate (bool): Whether to do evaluation. Default: False. timestamp (str | None): Local time... |
36,978 | import warnings
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmpose.datasets.pipelines import Compose
from .inference import _box2cs, _xywh2xyxy, _xyxy2xywh
The provided code snippet includes necessary dependencies for implementing the `extract_pose_sequence` function. Write a Python... | Extract the target frame from 2D pose results, and pad the sequence to a fixed length. Args: pose_results (list[list[dict]]): Multi-frame pose detection results stored in a nested list. Each element of the outer list is the pose detection results of a single frame, and each element of the inner list is the pose informa... |
36,979 | import warnings
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmpose.datasets.pipelines import Compose
from .inference import _box2cs, _xywh2xyxy, _xyxy2xywh
def _gather_pose_lifter_inputs(pose_results,
bbox_center,
bbox_sca... | Inference 3D pose from 2D pose sequences using a pose lifter model. Args: model (nn.Module): The loaded pose lifter model pose_results_2d (list[list[dict]]): The 2D pose sequences stored in a nested list. Each element of the outer list is the 2D pose results of a single frame, and each element of the inner list is the ... |
36,980 | import warnings
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmpose.datasets.pipelines import Compose
from .inference import _box2cs, _xywh2xyxy, _xyxy2xywh
The provided code snippet includes necessary dependencies for implementing the `vis_3d_pose_result` function. Write a Python fu... | Visualize the 3D pose estimation results. Args: model (nn.Module): The loaded model. result (list[dict]) |
36,981 | import warnings
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmpose.datasets.pipelines import Compose
from .inference import _box2cs, _xywh2xyxy, _xyxy2xywh
def _xyxy2xywh(bbox_xyxy):
"""Transform the bbox format from x1y1x2y2 to xywh.
Args:
bbox_xyxy (np.ndarray): B... | Inference a single image with a list of hand bounding boxes. Note: - num_bboxes: N - num_keypoints: K Args: model (nn.Module): The loaded pose model. img_or_path (str | np.ndarray): Image filename or loaded image. det_results (list[dict]): The 2D bbox sequences stored in a list. Each each element of the list is the bbo... |
36,982 | import warnings
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmpose.datasets.pipelines import Compose
from .inference import _box2cs, _xywh2xyxy, _xyxy2xywh
def _xyxy2xywh(bbox_xyxy):
"""Transform the bbox format from x1y1x2y2 to xywh.
Args:
bbox_xyxy (np.ndarray): B... | Inference a single image with a list of bounding boxes. Note: - num_bboxes: N - num_keypoints: K - num_vertices: V - num_faces: F Args: model (nn.Module): The loaded pose model. img_or_path (str | np.ndarray): Image filename or loaded image. det_results (list[dict]): The 2D bbox sequences stored in a list. Each element... |
36,983 | import warnings
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmpose.datasets.pipelines import Compose
from .inference import _box2cs, _xywh2xyxy, _xyxy2xywh
The provided code snippet includes necessary dependencies for implementing the `vis_3d_mesh_result` function. Write a Python fu... | Visualize the 3D mesh estimation results. Args: model (nn.Module): The loaded model. result (list[dict]): 3D mesh estimation results. |
36,984 | import os
import warnings
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from PIL import Image
from mmpose.core.post_processing import oks_nms
from mmpose.datasets.dataset_info import DatasetInfo
from mmpose.datasets.pipelines import Compos... | Initialize a pose model from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any weights. Returns: nn.Module: The constructed detector. |
36,985 | import os
import warnings
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from PIL import Image
from mmpose.core.post_processing import oks_nms
from mmpose.datasets.dataset_info import DatasetInfo
from mmpose.datasets.pipelines import Compos... | Inference a single image with a list of person bounding boxes. Note: - num_people: P - num_keypoints: K - bbox height: H - bbox width: W Args: model (nn.Module): The loaded pose model. img_or_path (str| np.ndarray): Image filename or loaded image. person_results (list(dict), optional): a list of detected persons that c... |
36,986 | import os
import warnings
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from PIL import Image
from mmpose.core.post_processing import oks_nms
from mmpose.datasets.dataset_info import DatasetInfo
from mmpose.datasets.pipelines import Compos... | Inference a single image with a bottom-up pose model. Note: - num_people: P - num_keypoints: K - bbox height: H - bbox width: W Args: model (nn.Module): The loaded pose model. img_or_path (str| np.ndarray): Image filename or loaded image. dataset (str): Dataset name, e.g. 'BottomUpCocoDataset'. It is deprecated. Please... |
36,987 | import os
import warnings
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from PIL import Image
from mmpose.core.post_processing import oks_nms
from mmpose.datasets.dataset_info import DatasetInfo
from mmpose.datasets.pipelines import Compos... | Visualize the detection results on the image. Args: model (nn.Module): The loaded detector. img (str | np.ndarray): Image filename or loaded image. result (list[dict]): The results to draw over `img` (bbox_result, pose_result). radius (int): Radius of circles. thickness (int): Thickness of lines. kpt_score_thr (float):... |
36,988 | import os
import warnings
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from PIL import Image
from mmpose.core.post_processing import oks_nms
from mmpose.datasets.dataset_info import DatasetInfo
from mmpose.datasets.pipelines import Compos... | Process mmdet results, and return a list of bboxes. Args: mmdet_results (list|tuple): mmdet results. cat_id (int): category id (default: 1 for human) Returns: person_results (list): a list of detected bounding boxes |
36,989 | import warnings
import numpy as np
from mmpose.core import OneEuroFilter, oks_iou
def _track_by_iou(res, results_last, thr):
"""Get track id using IoU tracking greedily.
Args:
res (dict): The bbox & pose results of the person instance.
results_last (list[dict]): The bbox & pose & track_id info o... | Get track id for each person instance on the current frame. Args: results (list[dict]): The bbox & pose results of the current frame (bbox_result, pose_result). results_last (list[dict]): The bbox & pose & track_id info of the last frame (bbox_result, pose_result, track_id). next_id (int): The track id for the new pers... |
36,990 | import warnings
import numpy as np
from mmpose.core import OneEuroFilter, oks_iou
The provided code snippet includes necessary dependencies for implementing the `vis_pose_tracking_result` function. Write a Python function `def vis_pose_tracking_result(model, img, ... | Visualize the pose tracking results on the image. Args: model (nn.Module): The loaded detector. img (str | np.ndarray): Image filename or loaded image. result (list[dict]): The results to draw over `img` (bbox_result, pose_result). radius (int): Radius of circles. thickness (int): Thickness of lines. kpt_score_thr (flo... |
36,992 | import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `apply_bugeye_effect` function. Write a Python function `def apply_bugeye_effect(img, pose_results, left_eye_index, right_eye_index, ... | Apply bug-eye effect. Args: img (np.ndarray): Image data. pose_results (list[dict]): The pose estimation results containing: - "bbox" ([K, 4(or 5)]): detection bbox in [x1, y1, x2, y2, (score)] - "keypoints" ([K,3]): keypoint detection result in [x, y, score] left_eye_index (int): Keypoint index of left eye right_eye_i... |
36,993 | import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `apply_sunglasses_effect` function. Write a Python function `def apply_sunglasses_effect(img, pose_results, sunglasses_img, le... | Apply sunglasses effect. Args: img (np.ndarray): Image data. pose_results (list[dict]): The pose estimation results containing: - "keypoints" ([K,3]): keypoint detection result in [x, y, score] sunglasses_img (np.ndarray): Sunglasses image with white background. left_eye_index (int): Keypoint index of left eye right_ey... |
36,994 | import math
import os
import warnings
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from mmcv.utils.misc import deprecated_api_warning
from mmcv.visualization.color import color_val
The provided code snippet includes necessary dependencies for implementing the `imshow_bboxes` function.... | Draw bboxes with labels (optional) on an image. This is a wrapper of mmcv.imshow_bboxes. Args: img (str or ndarray): The image to be displayed. bboxes (ndarray): ndarray of shape (k, 4), each row is a bbox in format [x1, y1, x2, y2]. labels (str or list[str], optional): labels of each bbox. colors (list[str or tuple or... |
36,995 | import math
import os
import warnings
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from mmcv.utils.misc import deprecated_api_warning
from mmcv.visualization.color import color_val
The provided code snippet includes necessary dependencies for implementing the `imshow_keypoints` functi... | Draw keypoints and links on an image. Args: img (str or Tensor): The image to draw poses on. If an image array is given, id will be modified in-place. pose_result (list[kpts]): The poses to draw. Each element kpts is a set of K keypoints as an Kx3 numpy.ndarray, where each keypoint is represented as x, y, score. kpt_sc... |
36,996 | import math
import os
import warnings
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from mmcv.utils.misc import deprecated_api_warning
from mmcv.visualization.color import color_val
The provided code snippet includes necessary dependencies for implementing the `imshow_keypoints_3d` fun... | Draw 3D keypoints and links in 3D coordinates. Args: pose_result (list[dict]): 3D pose results containing: - "keypoints_3d" ([K,4]): 3D keypoints - "title" (str): Optional. A string to specify the title of the visualization of this pose result img (str|np.ndarray): Opptional. The image or image path to show input image... |
36,997 | import math
import os
import warnings
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from mmcv.utils.misc import deprecated_api_warning
from mmcv.visualization.color import color_val
try:
import trimesh
has_trimesh = True
except (ImportError, ModuleNotFoundError):
has_trimesh... | Render 3D meshes on background image. Args: img(np.ndarray): Background image. vertices (list of np.ndarray): Vetrex coordinates in camera space. faces (list of np.ndarray): Faces of meshes. camera_center ([2]): Center pixel. focal_length ([2]): Focal length of camera. colors (list[str or tuple or Color]): A list of me... |
36,998 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
def _get_max_preds(heatmaps):
"""Get keypoint predictions from score maps.
Note:
batch_size: N
num_keypoints: K
heatmap height: H
heatmap width: W
Args:
heatmaps (np.... | Calculate the pose accuracy of PCK for each individual keypoint and the averaged accuracy across all keypoints from heatmaps. Note: PCK metric measures accuracy of the localization of the body joints. The distances between predicted positions and the ground-truth ones are typically normalized by the bounding box size. ... |
36,999 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
def keypoint_pck_accuracy(pred, gt, mask, thr, normalize):
"""Calculate the pose accuracy of PCK for each individual keypoint and the
averaged accuracy across all keypoints for coordinates.
Note:
PC... | Calculate the pose accuracy of PCK for each individual keypoint and the averaged accuracy across all keypoints for coordinates. Note: - batch_size: N - num_keypoints: K Args: pred (np.ndarray[N, K, 2]): Predicted keypoint location. gt (np.ndarray[N, K, 2]): Groundtruth keypoint location. mask (np.ndarray[N, K]): Visibi... |
37,000 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
def _calc_distances(preds, targets, mask, normalize):
"""Calculate the normalized distances between preds and target.
Note:
batch_size: N
num_keypoints: K
dimension of keypoints: D (norm... | Calculate the normalized mean error (NME). Note: - batch_size: N - num_keypoints: K Args: pred (np.ndarray[N, K, 2]): Predicted keypoint location. gt (np.ndarray[N, K, 2]): Groundtruth keypoint location. mask (np.ndarray[N, K]): Visibility of the target. False for invisible joints, and True for visible. Invisible joint... |
37,001 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
def _calc_distances(preds, targets, mask, normalize):
"""Calculate the normalized distances between preds and target.
Note:
batch_size: N
num_keypoints: K
dimension of keypoints: D (norm... | Calculate the end-point error. Note: - batch_size: N - num_keypoints: K Args: pred (np.ndarray[N, K, 2]): Predicted keypoint location. gt (np.ndarray[N, K, 2]): Groundtruth keypoint location. mask (np.ndarray[N, K]): Visibility of the target. False for invisible joints, and True for visible. Invisible joints will be ig... |
37,002 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
The provided code snippet includes necessary dependencies for implementing the `keypoints_from_regression` function. Write a Python function `def keypoints_from_regression(regression_preds, center, scale, img_size)` t... | Get final keypoint predictions from regression vectors and transform them back to the image. Note: - batch_size: N - num_keypoints: K Args: regression_preds (np.ndarray[N, K, 2]): model prediction. center (np.ndarray[N, 2]): Center of the bounding box (x, y). scale (np.ndarray[N, 2]): Scale of the bounding box wrt heig... |
37,003 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
def _get_max_preds(heatmaps):
"""Get keypoint predictions from score maps.
Note:
batch_size: N
num_keypoints: K
heatmap height: H
heatmap width: W
Args:
heatmaps (np.... | Get final keypoint predictions from heatmaps and transform them back to the image. Note: - batch size: N - num keypoints: K - heatmap height: H - heatmap width: W Args: heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps. center (np.ndarray[N, 2]): Center of the bounding box (x, y). scale (np.ndarray[N, 2]): Sc... |
37,004 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
def _get_max_preds_3d(heatmaps):
"""Get keypoint predictions from 3D score maps.
Note:
batch size: N
num keypoints: K
heatmap depth size: D
heatmap height: H
heatmap widt... | Get final keypoint predictions from 3d heatmaps and transform them back to the image. Note: - batch size: N - num keypoints: K - heatmap depth size: D - heatmap height: H - heatmap width: W Args: heatmaps (np.ndarray[N, K, D, H, W]): model predicted heatmaps. center (np.ndarray[N, 2]): Center of the bounding box (x, y)... |
37,005 | import warnings
import cv2
import numpy as np
from mmpose.core.post_processing import transform_preds
The provided code snippet includes necessary dependencies for implementing the `multilabel_classification_accuracy` function. Write a Python function `def multilabel_classification_accuracy(pred, gt, mask, thr=0.5)` t... | Get multi-label classification accuracy. Note: - batch size: N - label number: L Args: pred (np.ndarray[N, L, 2]): model predicted labels. gt (np.ndarray[N, L, 2]): ground-truth labels. mask (np.ndarray[N, 1] or np.ndarray[N, L] ): reliability of ground-truth labels. Returns: float: multi-label classification accuracy. |
37,006 | import numpy as np
import torch
from mmpose.core.post_processing import (get_warp_matrix, transform_preds,
warp_affine_joints)
The provided code snippet includes necessary dependencies for implementing the `split_ae_outputs` function. Write a Python function `def split_ae_outpu... | Split multi-stage outputs into heatmaps & tags. Args: outputs (list(Tensor)): Outputs of network num_joints (int): Number of joints with_heatmaps (list[bool]): Option to output heatmaps for different stages. with_ae (list[bool]): Option to output ae tags for different stages. select_output_index (list[int]): Output kee... |
37,007 | import numpy as np
import torch
from mmpose.core.post_processing import (get_warp_matrix, transform_preds,
warp_affine_joints)
The provided code snippet includes necessary dependencies for implementing the `flip_feature_maps` function. Write a Python function `def flip_feature_... | Flip the feature maps and swap the channels. Args: feature_maps (list[Tensor]): Feature maps. flip_index (list[int] | None): Channel-flip indexes. If None, do not flip channels. Returns: list[Tensor]: Flipped feature_maps. |
37,008 | import numpy as np
import torch
from mmpose.core.post_processing import (get_warp_matrix, transform_preds,
warp_affine_joints)
def _resize_average(feature_maps, align_corners, index=-1, resize_size=None):
"""Resize the feature maps and compute the average.
Args:
... | Inference the model to get multi-stage outputs (heatmaps & tags), and resize them to base sizes. Args: feature_maps (list[Tensor]): feature_maps can be heatmaps, tags, and pafs. feature_maps_flip (list[Tensor] | None): flipped feature_maps. feature maps can be heatmaps, tags, and pafs. project2image (bool): Option to r... |
37,009 | import numpy as np
import torch
from mmpose.core.post_processing import (get_warp_matrix, transform_preds,
warp_affine_joints)
def _resize_average(feature_maps, align_corners, index=-1, resize_size=None):
"""Resize the feature maps and compute the average.
Args:
... | Aggregate multi-scale outputs. Note: batch size: N keypoints num : K heatmap width: W heatmap height: H Args: feature_maps_list (list[Tensor]): Aggregated feature maps. project2image (bool): Option to resize to base scale. align_corners (bool): Align corners when performing interpolation. aggregate_scale (str): Methods... |
37,010 | import numpy as np
import torch
from mmpose.core.post_processing import (get_warp_matrix, transform_preds,
warp_affine_joints)
The provided code snippet includes necessary dependencies for implementing the `get_group_preds` function. Write a Python function `def get_group_preds... | Transform the grouped joints back to the image. Args: grouped_joints (list): Grouped person joints. center (np.ndarray[2, ]): Center of the bounding box (x, y). scale (np.ndarray[2, ]): Scale of the bounding box wrt [width, height]. heatmap_size (np.ndarray[2, ]): Size of the destination heatmaps. use_udp (bool): Unbia... |
37,011 | import numpy as np
from .mesh_eval import compute_similarity_transform
def compute_similarity_transform(source_points, target_points):
"""Computes a similarity transform (sR, t) that takes a set of 3D points
source_points (N x 3) closest to a set of 3D points target_points, where R
is an 3x3 rotation matri... | Calculate the mean per-joint position error (MPJPE) and the error after rigid alignment with the ground truth (P-MPJPE). Note: - batch_size: N - num_keypoints: K - keypoint_dims: C Args: pred (np.ndarray): Predicted keypoint location with shape [N, K, C]. gt (np.ndarray): Groundtruth keypoint location with shape [N, K,... |
37,012 | import numpy as np
from .mesh_eval import compute_similarity_transform
def compute_similarity_transform(source_points, target_points):
"""Computes a similarity transform (sR, t) that takes a set of 3D points
source_points (N x 3) closest to a set of 3D points target_points, where R
is an 3x3 rotation matri... | Calculate the Percentage of Correct Keypoints (3DPCK) w. or w/o rigid alignment. Paper ref: `Monocular 3D Human Pose Estimation In The Wild Using Improved CNN Supervision' 3DV'2017. <https://arxiv.org/pdf/1611.09813>`__ . Note: - batch_size: N - num_keypoints: K - keypoint_dims: C Args: pred (np.ndarray[N, K, C]): Pred... |
37,013 | import numpy as np
from .mesh_eval import compute_similarity_transform
def compute_similarity_transform(source_points, target_points):
"""Computes a similarity transform (sR, t) that takes a set of 3D points
source_points (N x 3) closest to a set of 3D points target_points, where R
is an 3x3 rotation matri... | Calculate the Area Under the Curve (3DAUC) computed for a range of 3DPCK thresholds. Paper ref: `Monocular 3D Human Pose Estimation In The Wild Using Improved CNN Supervision' 3DV'2017. <https://arxiv.org/pdf/1611.09813>`__ . This implementation is derived from mpii_compute_3d_pck.m, which is provided as part of the MP... |
37,014 | import functools
import warnings
from inspect import getfullargspec
import torch
from .utils import cast_tensor_type
def cast_tensor_type(inputs, src_type, dst_type):
"""Recursively convert Tensor in inputs from src_type to dst_type.
Args:
inputs: Inputs that to be casted.
src_type (torch.dtyp... | Decorator to enable fp16 training automatically. This decorator is useful when you write custom modules and want to support mixed precision training. If inputs arguments are fp32 tensors, they will be converted to fp16 automatically. Arguments other than fp32 tensors are ignored. Args: apply_to (Iterable, optional): Th... |
37,015 | import functools
import warnings
from inspect import getfullargspec
import torch
from .utils import cast_tensor_type
def cast_tensor_type(inputs, src_type, dst_type):
"""Recursively convert Tensor in inputs from src_type to dst_type.
Args:
inputs: Inputs that to be casted.
src_type (torch.dtyp... | Decorator to convert input arguments to fp32 in force. This decorator is useful when you write custom modules and want to support mixed precision training. If there are some inputs that must be processed in fp32 mode, then this decorator can handle it. If inputs arguments are fp16 tensors, they will be converted to fp3... |
37,016 | import copy
import torch
import torch.nn as nn
from mmcv.runner import OptimizerHook
from mmcv.utils import _BatchNorm
from ..utils.dist_utils import allreduce_grads
from .utils import cast_tensor_type
def patch_norm_fp32(module):
"""Recursively convert normalization layers from FP16 to FP32.
Args:
modu... | Wrap the FP32 model to FP16. 1. Convert FP32 model to FP16. 2. Remain some necessary layers to be FP32, e.g., normalization layers. Args: model (nn.Module): Model in FP32. |
37,017 | import math
import cv2
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `fliplr_joints` function. Write a Python function `def fliplr_joints(joints_3d, joints_3d_visible, img_width, flip_pairs)` to solve the following problem:
Flip human joints horizontally... | Flip human joints horizontally. Note: - num_keypoints: K Args: joints_3d (np.ndarray([K, 3])): Coordinates of keypoints. joints_3d_visible (np.ndarray([K, 1])): Visibility of keypoints. img_width (int): Image width. flip_pairs (list[tuple]): Pairs of keypoints which are mirrored (for example, left ear and right ear). R... |
37,018 | import math
import cv2
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `fliplr_regression` function. Write a Python function `def fliplr_regression(regression, flip_pairs, center_mode='static', ... | Flip human joints horizontally. Note: - batch_size: N - num_keypoint: K Args: regression (np.ndarray([..., K, C])): Coordinates of keypoints, where K is the joint number and C is the dimension. Example shapes are: - [N, K, C]: a batch of keypoints where N is the batch size. - [N, T, K, C]: a batch of pose sequences, wh... |
37,019 | import math
import cv2
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `flip_back` function. Write a Python function `def flip_back(output_flipped, flip_pairs, target_type='GaussianHeatmap')` to solve the following problem:
Flip the flipped heatmaps back t... | Flip the flipped heatmaps back to the original form. Note: - batch_size: N - num_keypoints: K - heatmap height: H - heatmap width: W Args: output_flipped (np.ndarray[N, K, H, W]): The output heatmaps obtained from the flipped images. flip_pairs (list[tuple()): Pairs of keypoints which are mirrored (for example, left ea... |
37,020 | import math
import cv2
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `transform_preds` function. Write a Python function `def transform_preds(coords, center, scale, output_size, use_udp=False)` to solve the following problem:
Get final keypoint predictio... | Get final keypoint predictions from heatmaps and apply scaling and translation to map them back to the image. Note: num_keypoints: K Args: coords (np.ndarray[K, ndims]): * If ndims=2, corrds are predicted keypoint location. * If ndims=4, corrds are composed of (x, y, scores, tags) * If ndims=5, corrds are composed of (... |
37,021 | import math
import cv2
import numpy as np
import torch
def _get_3rd_point(a, b):
"""To calculate the affine matrix, three pairs of points are required. This
function is used to get the 3rd point, given 2D points a & b.
The 3rd point is defined by rotating vector `a - b` by 90 degrees
anticlockwise, usin... | Get the affine transform matrix, given the center/scale/rot/output_size. Args: center (np.ndarray[2, ]): Center of the bounding box (x, y). scale (np.ndarray[2, ]): Scale of the bounding box wrt [width, height]. rot (float): Rotation angle (degree). output_size (np.ndarray[2, ] | list(2,)): Size of the destination heat... |
37,022 | import math
import cv2
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `affine_transform` function. Write a Python function `def affine_transform(pt, trans_mat)` to solve the following problem:
Apply an affine transformation to the points. Args: pt (np.nda... | Apply an affine transformation to the points. Args: pt (np.ndarray): a 2 dimensional point to be transformed trans_mat (np.ndarray): 2x3 matrix of an affine transform Returns: np.ndarray: Transformed points. |
37,023 | import math
import cv2
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `get_warp_matrix` function. Write a Python function `def get_warp_matrix(theta, size_input, size_dst, size_target)` to solve the following problem:
Calculate the transformation matrix u... | Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input image [w, h]. size_dst (np.ndarra... |
37,024 | import math
import cv2
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `warp_affine_joints` function. Write a Python function `def warp_affine_joints(joints, mat)` to solve the following problem:
Apply affine transformation defined by the transform matrix ... | Apply affine transformation defined by the transform matrix on the joints. Args: joints (np.ndarray[..., 2]): Origin coordinate of joints. mat (np.ndarray[3, 2]): The affine matrix. Returns: np.ndarray[..., 2]: Result coordinate of joints. |
37,025 | import math
import cv2
import numpy as np
import torch
def affine_transform_torch(pts, t):
npts = pts.shape[0]
pts_homo = torch.cat([pts, torch.ones(npts, 1, device=pts.device)], dim=1)
out = torch.mm(t, torch.t(pts_homo))
return torch.t(out[:2, :]) | null |
37,026 | from time import time
import numpy as np
def smoothing_factor(t_e, cutoff):
r = 2 * np.pi * cutoff * t_e
return r / (r + 1) | null |
37,027 | from time import time
import numpy as np
def exponential_smoothing(a, x, x_prev):
return a * x + (1 - a) * x_prev | null |
37,028 | import numpy as np
import torch
from munkres import Munkres
from mmpose.core.evaluation import post_dark_udp
def _py_max_match(scores):
"""Apply munkres algorithm to get the best match.
Args:
scores(np.ndarray): cost matrix.
Returns:
np.ndarray: best match.
"""
m = Munkres()
tmp ... | Match joints by tags. Use Munkres algorithm to calculate the best match for keypoints grouping. Note: number of keypoints: K max number of people in an image: M (M=30 by default) dim of tags: L If use flip testing, L=2; else L=1. Args: inp(tuple): tag_k (np.ndarray[KxMxL]): tag corresponding to the top k values of feat... |
37,029 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `nms` function. Write a Python function `def nms(dets, thr)` to solve the following problem:
Greedily select boxes with high confidence and overlap <= thr. Args: dets: [[x1, y1, x2, y2, score]]. thr: Retain overlap < thr.... | Greedily select boxes with high confidence and overlap <= thr. Args: dets: [[x1, y1, x2, y2, score]]. thr: Retain overlap < thr. Returns: list: Indexes to keep. |
37,030 | import numpy as np
def oks_iou(g, d, a_g, a_d, sigmas=None, vis_thr=None):
"""Calculate oks ious.
Args:
g: Ground truth keypoints.
d: Detected keypoints.
a_g: Area of the ground truth object.
a_d: Area of the detected object.
sigmas: standard deviation of keypoint labelli... | OKS NMS implementations. Args: kpts_db: keypoints. thr: Retain overlap < thr. sigmas: standard deviation of keypoint labelling. vis_thr: threshold of the keypoint visibility. score_per_joint: the input scores (in kpts_db) are per joint scores Returns: np.ndarray: indexes to keep. |
37,031 | import numpy as np
def oks_iou(g, d, a_g, a_d, sigmas=None, vis_thr=None):
"""Calculate oks ious.
Args:
g: Ground truth keypoints.
d: Detected keypoints.
a_g: Area of the ground truth object.
a_d: Area of the detected object.
sigmas: standard deviation of keypoint labelli... | Soft OKS NMS implementations. Args: kpts_db thr: retain oks overlap < thr. max_dets: max number of detections to keep. sigmas: Keypoint labelling uncertainty. score_per_joint: the input scores (in kpts_db) are per joint scores Returns: np.ndarray: indexes to keep. |
37,032 | from collections import OrderedDict
import torch.distributed as dist
from torch._utils import (_flatten_dense_tensors, _take_tensors,
_unflatten_dense_tensors)
def _allreduce_coalesced(tensors, world_size, bucket_size_mb=-1):
"""Allreduce parameters as a whole."""
if bucket_size_mb > 0... | Allreduce gradients. Args: params (list[torch.Parameters]): List of parameters of a model coalesce (bool, optional): Whether allreduce parameters as a whole. Default: True. bucket_size_mb (int, optional): Size of bucket, the unit is MB. Default: -1. |
37,033 | import cv2
import numpy as np
from mmpose.core.post_processing import (get_affine_transform, get_warp_matrix,
warp_affine_joints)
from mmpose.datasets.builder import PIPELINES
from .shared_transform import Compose
def _get_multi_scale_size(image,
input_... | Resize the images for multi-scale training. Args: image: Input image input_size (np.ndarray[2]): Size (w, h) of the image input current_scale (float): Current scale min_scale (float): Minimal scale Returns: tuple: A tuple containing image info. - image_resized (np.ndarray): resized image - center (np.ndarray): center o... |
37,034 | import cv2
import numpy as np
from mmpose.core.post_processing import (get_affine_transform, get_warp_matrix,
warp_affine_joints)
from mmpose.datasets.builder import PIPELINES
from .shared_transform import Compose
def _get_multi_scale_size(image,
input_... | Resize the images for multi-scale training. Args: image: Input image input_size (np.ndarray[2]): Size (w, h) of the image input current_scale (float): Current scale min_scale (float): Minimal scale Returns: tuple: A tuple containing image info. - image_resized (np.ndarray): resized image - center (np.ndarray): center o... |
37,035 | import cv2
import mmcv
import numpy as np
import torch
from mmpose.core.post_processing import (affine_transform, fliplr_joints,
get_affine_transform)
from mmpose.datasets.builder import PIPELINES
The provided code snippet includes necessary dependencies for implementing the `_... | Flip SMPL pose parameters horizontally. Args: pose (np.ndarray([72])): SMPL pose parameters Returns: pose_flipped |
37,036 | import cv2
import mmcv
import numpy as np
import torch
from mmpose.core.post_processing import (affine_transform, fliplr_joints,
get_affine_transform)
from mmpose.datasets.builder import PIPELINES
The provided code snippet includes necessary dependencies for implementing the `_... | Flip IUV image horizontally. Note: IUV image height: H IUV image width: W Args: iuv np.ndarray([H, W, 3]): IUV image uv_type (str): The type of the UV map. Candidate values: 'DP': The UV map used in DensePose project. 'SMPL': The default UV map of SMPL model. 'BF': The UV map used in DecoMR project. Default: 'BF' Retur... |
37,037 | import cv2
import mmcv
import numpy as np
import torch
from mmpose.core.post_processing import (affine_transform, fliplr_joints,
get_affine_transform)
from mmpose.datasets.builder import PIPELINES
def _construct_rotation_matrix(rot, size=3):
"""Construct the in-plane rotatio... | Rotate the 3D joints in the local coordinates. Note: Joints number: K Args: joints_3d (np.ndarray([K, 3])): Coordinates of keypoints. rot (float): Rotation angle (degree). Returns: joints_3d_rotated |
37,038 | import cv2
import mmcv
import numpy as np
import torch
from mmpose.core.post_processing import (affine_transform, fliplr_joints,
get_affine_transform)
from mmpose.datasets.builder import PIPELINES
def _construct_rotation_matrix(rot, size=3):
"""Construct the in-plane rotatio... | Rotate SMPL pose parameters. SMPL (https://smpl.is.tue.mpg.de/) is a 3D human model. Args: pose (np.ndarray([72])): SMPL pose parameters rot (float): Rotation angle (degree). Returns: pose_rotated |
37,039 | import cv2
import mmcv
import numpy as np
import torch
from mmpose.core.post_processing import (affine_transform, fliplr_joints,
get_affine_transform)
from mmpose.datasets.builder import PIPELINES
The provided code snippet includes necessary dependencies for implementing the `_... | Flip human joints in 3D space horizontally. Note: num_keypoints: K Args: joints_3d (np.ndarray([K, 3])): Coordinates of keypoints. joints_3d_visible (np.ndarray([K, 1])): Visibility of keypoints. flip_pairs (list[tuple()]): Pairs of keypoints which are mirrored (for example, left ear -- right ear). Returns: joints_3d_f... |
37,040 | import copy
import platform
import random
from functools import partial
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg, is_seq_of
from mmcv.utils.parrots_wrapper import _get_dataloader
from torch.utils.data.dataset import Concat... | Build PyTorch DataLoader. In distributed training, each GPU/process has a dataloader. In non-distributed training, there is only one dataloader for all GPUs. Args: dataset (Dataset): A PyTorch dataset. samples_per_gpu (int): Number of training samples on each GPU, i.e., batch size of each GPU. workers_per_gpu (int): Ho... |
37,041 | import torch
import torch.nn as nn
from ..builder import LOSSES
The provided code snippet includes necessary dependencies for implementing the `_make_input` function. Write a Python function `def _make_input(t, requires_grad=False, device=torch.device('cpu'))` to solve the following problem:
Make zero inputs for AE lo... | Make zero inputs for AE loss. Args: t (torch.Tensor): input requires_grad (bool): Option to use requires_grad. device: torch device Returns: torch.Tensor: zero input. |
37,042 | import torch
import torch.nn as nn
from ..builder import LOSSES
from ..utils.geometry import batch_rodrigues
The provided code snippet includes necessary dependencies for implementing the `perspective_projection` function. Write a Python function `def perspective_projection(points, rotation, translation, focal_length,... | This function computes the perspective projection of a set of 3D points. Note: - batch size: B - point number: N Args: points (Tensor([B, N, 3])): A set of 3D points rotation (Tensor([B, 3, 3])): Camera rotation matrix translation (Tensor([B, 3])): Camera translation focal_length (Tensor([B,])): Focal length camera_cen... |
37,043 | import math
import torch
import torch.nn as nn
from mmcv.cnn import (build_activation_layer, build_conv_layer,
build_norm_layer, trunc_normal_init)
from mmcv.cnn.bricks.transformer import build_dropout
from mmcv.runner import BaseModule
from torch.nn.functional import pad
from ..builder import BAC... | Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor. Args: x (Tensor): The input tensor of shape [N, L, C] before conversion. hw_shape (Sequence[int]): The height and width of output feature map. Returns: Tensor: The output tensor of shape [N, C, H, W] after conversion. |
37,044 | import math
import torch
import torch.nn as nn
from mmcv.cnn import (build_activation_layer, build_conv_layer,
build_norm_layer, trunc_normal_init)
from mmcv.cnn.bricks.transformer import build_dropout
from mmcv.runner import BaseModule
from torch.nn.functional import pad
from ..builder import BAC... | Flatten [N, C, H, W] shape tensor to [N, L, C] shape tensor. Args: x (Tensor): The input tensor of shape [N, C, H, W] before conversion. Returns: Tensor: The output tensor of shape [N, L, C] after conversion. |
37,045 | import math
import torch
import torch.nn as nn
from mmcv.cnn import (build_activation_layer, build_conv_layer,
build_norm_layer, trunc_normal_init)
from mmcv.cnn.bricks.transformer import build_dropout
from mmcv.runner import BaseModule
from torch.nn.functional import pad
from ..builder import BAC... | Build drop path layer. |
37,046 | import math
import torch
from functools import partial
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
The provided code snippet i... | Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token dimension for the original embeddings. Args: abs_pos (Tensor): absolute positional embeddings with (1, num_position, C). has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token. hw (Tuple): size of input image to... |
37,048 | import copy
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import ConvModule, build_conv_layer, build_norm_layer
from mmcv.cnn.bricks import ContextBlock
from mmcv.utils.parrots_wrapper import _BatchNorm
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
class ViPNAS_Bottle... | Get the expansion of a residual block. The block expansion will be obtained by the following order: 1. If ``expansion`` is given, just return it. 2. If ``block`` has the attribute ``expansion``, then return ``block.expansion``. 3. Return the default value according the the block type: 4 for ``ViPNAS_Bottleneck``. Args:... |
37,049 | import copy
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (ConvModule, build_conv_layer, build_norm_layer,
constant_init, kaiming_init)
from mmcv.utils.parrots_wrapper import _BatchNorm
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
class B... | Get the expansion of a residual block. The block expansion will be obtained by the following order: 1. If ``expansion`` is given, just return it. 2. If ``block`` has the attribute ``expansion``, then return ``block.expansion``. 3. Return the default value according the the block type: 1 for ``BasicBlock`` and 4 for ``B... |
37,050 | import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init, kaiming_init, normal_init
from mmcv.utils.parrots_wrapper import _BatchNorm
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
def make_vgg_layer(in_channels,
out_channels,
num_blocks,
... | null |
37,051 | from collections import OrderedDict
from mmcv.runner.checkpoint import _load_checkpoint, load_state_dict
The provided code snippet includes necessary dependencies for implementing the `load_checkpoint` function. Write a Python function `def load_checkpoint(model, filename, map_l... | Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different params for the model and checkpoint. logger (:mod:`loggi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.