id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
30,810 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
30,812 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 256
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.IMAGE_CHANNELS = 3
_C.DATA.CROP_PCT = 0.875
_C.DAT... | Return a clone of config and optionally overwrite it from yaml file |
30,813 | import math
from functools import partial
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from droppath import DropPath
class PoolingTransformer(nn.Layer):
def __init__(self,
image_size,
patch_size,
stride,
base_dims,
... | null |
30,814 | import os
import numpy as np
import paddle
import torch
import timm
from pit import build_pit
from config import get_config
def print_model_named_params(model):
print('----------------------------------')
for name, param in model.named_parameters():
print(name, param.shape)
print('-----------------... | null |
30,815 | import os
import numpy as np
import paddle
import torch
import timm
from pit import build_pit
from config import get_config
def print_model_named_buffers(model):
print('----------------------------------')
for name, param in model.named_buffers():
print(name, param.shape)
print('-------------------... | null |
30,816 | import os
import numpy as np
import paddle
import torch
import timm
from pit import build_pit
from config import get_config
def torch_to_paddle_mapping(model_name, config):
def convert(torch_model, paddle_model, model_name, config):
def _set_value(th_name, pd_name, transpose=True):
th_shape = th_params[th_... | null |
30,855 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
30,856 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
30,861 | import paddle
import paddle.nn as nn
from droppath import DropPath
def _init_weights_linear():
weight_attr = paddle.ParamAttr(initializer=nn.initializer.TruncatedNormal(std=.02))
bias_attr = paddle.ParamAttr(initializer=nn.initializer.Constant(0.0))
return weight_attr, bias_attr | null |
30,862 | import paddle
import paddle.nn as nn
from droppath import DropPath
def _init_weights_layernorm():
weight_attr = paddle.ParamAttr(initializer=nn.initializer.Constant(1.0))
bias_attr = paddle.ParamAttr(initializer=nn.initializer.Constant(0.0))
return weight_attr, bias_attr | null |
30,863 | import paddle
import paddle.nn as nn
from droppath import DropPath
class MobileViT(nn.Layer):
def __init__(self,
in_channels=3,
dims=[16, 32, 48, 48, 48, 64, 80, 96, 384],
hidden_dims=[96, 120, 144], # d: hidden dims in mobilevit block
num_classes=... | Build MobileViT by reading options in config object Args: config: config instance contains setting options Returns: model: MobileViT model |
30,864 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
30,865 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
30,866 | import os
import math
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
from paddle.vision import transforms
from paddle.vision import image_load
from augment import auto_augment_policy_original
from augment import AutoAugment
from augment import rand_augment_p... | Get full training transforms For training, a RandomResizedCrop is applied with random mirror, then RandAug, AutoAug or ColorJitter is applied, then normalization is applied with mean and std, and RandomErase is applied. The input pixel values must be rescaled to [0, 1.]. Outputs is converted to tensor. Args: config: co... |
30,867 | import os
import math
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
from paddle.vision import transforms
from paddle.vision import image_load
from augment import auto_augment_policy_original
from augment import AutoAugment
from augment import rand_augment_p... | Get dataset from config and mode (train/val) Returns the related dataset object according to configs and mode(train/val) Args: config: configs contains dataset related settings. see config.py for details is_train: bool, set True to use training set, otherwise val set. Default: True Returns: dataset: dataset object |
30,868 | import os
import math
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
from paddle.vision import transforms
from paddle.vision import image_load
from augment import auto_augment_policy_original
from augment import AutoAugment
from augment import rand_augment_p... | Get dataloader from dataset, allows multiGPU settings. Multi-GPU loader is implements as distributedBatchSampler. Args: config: see config.py for details dataset: paddle.io.dataset object is_train: bool, when False, shuffle is off and BATCH_SIZE_EVAL is used, default: True use_dist_sampler: if True, DistributedBatchSam... |
30,869 | import os
from yacs.config import CfgNode as CN
import yaml
def _update_config_from_file(config, cfg_file):
"""Load cfg file (.yaml) and update config object
Args:
config: config object
cfg_file: config file (.yaml)
Return:
None
"""
config.defrost()
with open(cfg_file, 'r... | Update config by ArgumentParser Configs that are often used can be updated from arguments Args: args: ArgumentParser contains options Return: config: updated config |
30,870 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 256
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.IMAGE_CHANNELS = 3
_C.DATA.CROP_PCT = 0.9
_C.DATA.... | Return a clone of config and optionally overwrite it from yaml file |
30,913 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
30,914 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
30,919 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 256
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.IMAGE_CHANNELS = 3
_C.DATA.CROP_PCT = 0.875
_C.DAT... | Return a clone of config and optionally overwrite it from yaml file |
30,920 | import os
import numpy as np
import paddle
import torch
import timm
from cait import build_cait as build_model
from config import get_config
def print_model_named_params(model):
print('----------------------------------')
for name, param in model.named_parameters():
print(name, param.shape)
print('... | null |
30,921 | import os
import numpy as np
import paddle
import torch
import timm
from cait import build_cait as build_model
from config import get_config
def print_model_named_buffers(model):
print('----------------------------------')
for name, param in model.named_buffers():
print(name, param.shape)
print('--... | null |
30,922 | import os
import numpy as np
import paddle
import torch
import timm
from cait import build_cait as build_model
from config import get_config
def torch_to_paddle_mapping(model_name, config):
mapping = [
('cls_token', 'cls_token'),
('pos_embed', 'pos_embed'),
('patch_embed.proj', 'patch_embed.... | null |
30,925 | import paddle
import paddle.nn as nn
from droppath import DropPath
class Cait(nn.Layer):
""" CaiT model
Args:
image_size: int, input image size, default: 224
in_channels: int, input image channels, default: 3
num_classes: int, num of classes, default: 1000
patch_size: int, patch ... | build cait model from config |
30,965 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
30,966 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
30,971 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 256
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.IMAGE_CHANNELS = 3
_C.DATA.CROP_PCT = 0.875
_C.DAT... | Return a clone of config and optionally overwrite it from yaml file |
30,972 | import math
import numpy as np
import paddle
from paddle import nn
from paddle.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition(x, window_size)` to solve the following problem:
r"""window_... | r"""window_partition Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) |
30,973 | import math
import numpy as np
import paddle
from paddle import nn
from paddle.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `window_partition_noreshape` function. Write a Python function `def window_partition_noreshape(x, window_size)` to solve the following ... | r"""window_partition_noreshape Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (B, num_windows_h, num_windows_w, window_size, window_size, C) |
30,974 | import math
import numpy as np
import paddle
from paddle import nn
from paddle.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_reverse(windows, window_size, H, W)` to solve the following problem:
r""... | r"""window_reverse Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) |
30,975 | import math
import numpy as np
import paddle
from paddle import nn
from paddle.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `get_relative_position_index` function. Write a Python function `def get_relative_position_index(q_windows, k_windows)` to solve the fo... | r""" Args: q_windows: tuple (query_window_height, query_window_width) k_windows: tuple (key_window_height, key_window_width) Returns: relative_position_index: query_window_height*query_window_width, key_window_height*key_window_width |
30,976 | import math
import numpy as np
import paddle
from paddle import nn
from paddle.nn import functional as F
class FocalTransformer(nn.Layer):
r"""Focal Transformer:Focal Self-attention for Local-Global Interactions in Vision Transformer
Args:
img_size (int | tuple(int)): Input image size. Default 224
... | null |
31,018 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
31,019 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
31,024 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 64
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.IMAGE_CHANNELS = 3
_C.DATA.CROP_PCT = 0.875
_C.DATA... | Return a clone of config and optionally overwrite it from yaml file |
31,025 | import os
import paddle
import paddle.nn as nn
from droppath import DropPath
The provided code snippet includes necessary dependencies for implementing the `get_conv2d` function. Write a Python function `def get_conv2d(in_channels, out_channels, kernel_size, stride, ... | Return a regular Conv op or an optimized Conv op for large kernel (not supported yet) Now only support regular conv op |
31,026 | import os
import paddle
import paddle.nn as nn
from droppath import DropPath
class ConvNormAct(nn.Sequential):
"""Layer ops: Conv2D -> NormLayer -> ActLayer"""
def __init__(self,
in_channels,
out_channels,
kernel_size=3,
stride=1,
... | fuse bn into conv Args: branch(ConvNormAct): nn.Sequential(conv2d -> norm -> act). groups(int): gropus in branch's conv op, default: None Returns: kernel_weight(tensor), kernel_bias(tensor): fused conv weights value and bias value |
31,027 | import os
import paddle
import paddle.nn as nn
from droppath import DropPath
class RepLKNet(nn.Layer):
def __init__(self,
large_kernel_sizes,
layers,
channels,
droppath,
small_kernel,
dw_ratio=1,
f... | Build RepLKNet by reading options in config object Args: config: config instance contains setting options Returns: model: RepLKNet model |
31,028 | import os
import numpy as np
import paddle
import torch
import timm
from replknet import build_replknet as build_model
from config import get_config
from replknet_pth import create_RepLKNet31B
from replknet_pth import create_RepLKNet31L
from replknet_pth import create_RepLKNetXL
def print_model_named_params(model):
... | null |
31,029 | import os
import numpy as np
import paddle
import torch
import timm
from replknet import build_replknet as build_model
from config import get_config
from replknet_pth import create_RepLKNet31B
from replknet_pth import create_RepLKNet31L
from replknet_pth import create_RepLKNetXL
def print_model_named_buffers(model):
... | null |
31,030 | import os
import numpy as np
import paddle
import torch
import timm
from replknet import build_replknet as build_model
from config import get_config
from replknet_pth import create_RepLKNet31B
from replknet_pth import create_RepLKNet31L
from replknet_pth import create_RepLKNetXL
def torch_to_paddle_mapping(model_name, ... | null |
31,072 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
31,073 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
31,075 | import os
import math
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
from paddle.vision import transforms
from paddle.vision import image_load
from augment import auto_augment_policy_original
from augment import AutoAugment
from augment import rand_augment_p... | Get dataset from config and mode (train/val) Returns the related dataset object according to configs and mode(train/val) Args: config: configs contains dataset related settings. see config.py for details is_train: bool, set True to use training set, otherwise val set. Default: True Returns: dataset: dataset object |
31,078 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 256
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.IMAGE_CHANNELS = 3
_C.DATA.CROP_PCT = 0.875
_C.DAT... | Return a clone of config and optionally overwrite it from yaml file |
31,079 | import os
import numpy as np
import paddle
import torch
import timm
from repmlp import build_repmlp as build_model
from config import get_config
from repmlp_torch import create_RepMLPNet_B224
from repmlp_torch import create_RepMLPNet_B256
def print_model_named_params(model):
print('--------------------------------... | null |
31,080 | import os
import numpy as np
import paddle
import torch
import timm
from repmlp import build_repmlp as build_model
from config import get_config
from repmlp_torch import create_RepMLPNet_B224
from repmlp_torch import create_RepMLPNet_B256
def print_model_named_buffers(model):
print('-------------------------------... | null |
31,081 | import os
import numpy as np
import paddle
import torch
import timm
from repmlp import build_repmlp as build_model
from config import get_config
from repmlp_torch import create_RepMLPNet_B224
from repmlp_torch import create_RepMLPNet_B256
def torch_to_paddle_mapping(model_name, config):
mapping = [
('conv_e... | null |
31,118 | import copy
import paddle
import paddle.nn.functional as F
from paddle import nn
def conv_bn_relu(in_channels, out_channels, kernel_size, stride, padding, groups=1, relu=True):
ops = []
ops.append(('conv', nn.Conv2D(in_channels=in_channels, out_channels=out_channels,
kernel_size=kernel_size,... | null |
31,119 | import copy
import paddle
import paddle.nn.functional as F
from paddle import nn
def fuse_bn(conv_or_fc, bn):
std = (bn._variance + bn.epsilon).sqrt()
t = bn.weight / std
t = t.reshape([-1, 1, 1, 1])
if len(t) == conv_or_fc.weight.shape[0]:
return conv_or_fc.weight * t, bn.bias - bn._mean * bn... | null |
31,120 | import copy
import paddle
import paddle.nn.functional as F
from paddle import nn
class RepMLP(nn.Layer):
"""RepMLP Layer"""
def __init__(self,
in_channels=3,
num_class=1000,
patch_size=(4, 4),
num_blocks=(2,2,6,2),
channels=(19... | null |
31,122 | from numpy import repeat
import os
import paddle
import paddle.nn as nn
from droppath import DropPath
class ConvolutionalVisionTransformer(nn.Layer):
'''CvT model
Introducing Convolutions to Vision Transformers
Args:
in_chans: int, input image channels, default: 3
num_classes: int, number of... | null |
31,127 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | return argumeents, this will overwrite the config by (1) yaml file (2) argument values |
31,128 | import sys
import os
import time
import argparse
import random
import math
import numpy as np
import paddle
from datasets import get_dataloader
from datasets import get_dataset
from config import get_config
from config import update_config
from utils import AverageMeter
from utils import get_logger
from utils import wr... | main method for each process |
31,133 | import os
from yacs.config import CfgNode as CN
import yaml
_C = CN()
_C.BASE = ['']
_C.DATA = CN()
_C.DATA.BATCH_SIZE = 256
_C.DATA.BATCH_SIZE_EVAL = None
_C.DATA.DATA_PATH = '/dataset/imagenet/'
_C.DATA.DATASET = 'imagenet2012'
_C.DATA.IMAGE_SIZE = 224
_C.DATA.IMAGE_CHANNELS = 3
_C.DATA.CROP_PCT = 0.875
_C.DAT... | Return a clone of config and optionally overwrite it from yaml file |
31,171 | import os
import time
import random
import argparse
import numpy as np
from collections import deque
import paddle
import paddle.nn as nn
from config import *
from src.utils import logger
from src.datasets import get_dataset
from src.models import get_model
from src.transforms import *
from src.utils import TimeAverage... | null |
31,172 | import numpy as np
import math
import cv2
import collections.abc
import paddle
import paddle.nn.functional as F
def slide_inference(model, imgs, crop_size, stride_size, num_classes):
"""
Inference by sliding-window with overlap, the overlap is equal to stride.
Args:
model (paddle.nn.Layer): model to... | Single-scale inference for image. Args: model (paddle.nn.Layer): model to get logits of image. img (Tensor): the input image. ori_shape (list): origin shape of image. is_slide (bool): whether to infer by sliding window. base_size (list): the size of short edge is resize to min(base_size) when it is smaller than min(bas... |
31,173 | import numpy as np
import math
import cv2
import collections.abc
import paddle
import paddle.nn.functional as F
def slide_inference(model, imgs, crop_size, stride_size, num_classes):
"""
Inference by sliding-window with overlap, the overlap is equal to stride.
Args:
model (paddle.nn.Layer): model to... | Multi-scale inference. For each scale, the segmentation result is first generated by sliding-window testing with overlap. Then the segmentation result is resize to the original size, followed by softmax operation. Finally, the segmenation logits of all scales are averaged (+argmax) Args: model (paddle.nn.Layer): model ... |
31,174 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def normalize(img, mean, std):
img = img.astype(np.float32, copy=False) / 255.0
img -= mean
img /= std
return img | null |
31,175 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def imnormalize_(img, mean, std):
"""Inplace normalize an image with mean and std.
Args:
img (ndarray): Image to be normalized. (0~255)
mean (ndarray): The mean to be use... | Normalize an image with mean and std. Args: img (ndarray): Image to be normalized. mean (ndarray): The mean to be used for normalize. std (ndarray): The std to be used for normalize. to_rgb (bool): Whether to convert to rgb. Returns: ndarray: The normalized image. |
31,176 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def horizontal_flip(img):
if len(img.shape) == 3:
img = img[:, ::-1, :]
elif len(img.shape) == 2:
img = img[:, ::-1]
return img | null |
31,177 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def vertical_flip(img):
if len(img.shape) == 3:
img = img[::-1, :, :]
elif len(img.shape) == 2:
img = img[::-1, :]
return img | null |
31,178 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def brightness(img, brightness_lower, brightness_upper):
brightness_delta = np.random.uniform(brightness_lower, brightness_upper)
img = ImageEnhance.Brightness(img).enhance(brightness_d... | null |
31,179 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def contrast(img, contrast_lower, contrast_upper):
contrast_delta = np.random.uniform(contrast_lower, contrast_upper)
img = ImageEnhance.Contrast(img).enhance(contrast_delta)
return... | null |
31,180 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def saturation(img, saturation_lower, saturation_upper):
saturation_delta = np.random.uniform(saturation_lower, saturation_upper)
img = ImageEnhance.Color(img).enhance(saturation_delta)... | null |
31,181 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def hue(img, hue_lower, hue_upper):
hue_delta = np.random.uniform(hue_lower, hue_upper)
img = np.array(img.convert('HSV'))
img[:, :, 0] = img[:, :, 0] + hue_delta
img = Image.fr... | null |
31,182 | import cv2
import numpy as np
from PIL import Image, ImageEnhance
from scipy.ndimage.morphology import distance_transform_edt
def rotate(img, rotate_lower, rotate_upper):
rotate_delta = np.random.uniform(rotate_lower, rotate_upper)
img = img.rotate(int(rotate_delta))
return img | null |
31,183 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `multi_cross_entropy_loss` function. Write a Python function `def multi_cross_entropy_loss(pred_list, label, num... | MultiCrossEntropyLoss Function |
31,184 | import math
import paddle
import warnings
import paddle.nn as nn
import paddle.nn.functional as F
from .swin_transformer import Identity, DropPath, Mlp
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
def norm_cdf(x):
... | r"""Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values wo... |
31,185 | import math
import paddle
import warnings
import paddle.nn as nn
import paddle.nn.functional as F
from .swin_transformer import Identity, DropPath, Mlp
def expand(x, nclass):
return x.unsqueeze(1).tile([1, nclass, 1, 1, 1]).flatten(0, 1) | null |
31,186 | import copy
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `img2windows` function. Write a Python function `def img2windows(img, h_split, w_split)` to solve the following problem:
Convert input tens... | Convert input tensor into split stripes Args: img: tensor, image tensor with shape [B, C, H, W] h_split: int, splits width in height direction w_split: int, splits width in width direction Returns: out: tensor, splitted image |
31,187 | import copy
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `windows2img` function. Write a Python function `def windows2img(img_splits, h_split, w_split, img_h, img_w)` to solve the following proble... | Convert splitted stripes back Args: img_splits: tensor, image tensor with shape [B, C, H, W] h_split: int, splits width in height direction w_split: int, splits width in width direction img_h: int, original tensor height img_w: int, original tensor width Returns: img: tensor, original tensor |
31,188 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from src.utils import load_pretrained_model
def to_2tuple(ele):
return (ele, ele) | null |
31,189 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from src.utils import load_pretrained_model
def nlc_to_nchw(x, H, W):
assert len(x.shape) == 3
B, L, C = x.shape
assert L == H * W
return x.transpose([0, 2, 1]).reshape([B, C, H, W]) | null |
31,190 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from src.utils import load_pretrained_model
def nchw_to_nlc(x):
assert len(x.shape) == 4
return x.flatten(2).transpose([0, 2, 1]) | null |
31,191 | import math
import numpy as np
import paddle
from paddle import nn
from paddle.nn import functional as F
from .swin_transformer import Identity, DropPath, Mlp, windows_partition, windows_reverse
The provided code snippet includes necessary dependencies for implementing the `window_partition_noreshape` function. Write ... | r"""window_partition_noreshape Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (B, num_windows_h, num_windows_w, window_size, window_size, C) |
31,192 | import math
import numpy as np
import paddle
from paddle import nn
from paddle.nn import functional as F
from .swin_transformer import Identity, DropPath, Mlp, windows_partition, windows_reverse
The provided code snippet includes necessary dependencies for implementing the `get_relative_position_index` function. Write... | r""" Args: q_windows: tuple (query_window_height, query_window_width) k_windows: tuple (key_window_height, key_window_width) Returns: relative_position_index: query_window_height*query_window_width, key_window_height*key_window_width |
31,193 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from .swin_transformer import Identity, DropPath
The provided code snippet includes necessary dependencies for implementing the `_make_divisible` function. Write a Python function `def _make_divisible(v, divisor, min_value=None)` to solve the follow... | This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return: |
31,194 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `windows_partition` function. Write a Python function `def windows_partition(x, window_size)` to solve the following problem:
partite windows into wind... | partite windows into window_size x window_size Args: x: Tensor, shape=[b, h, w, c] window_size: int, window size Returns: x: Tensor, shape=[num_windows*b, window_size, window_size, c] |
31,195 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `windows_reverse` function. Write a Python function `def windows_reverse(windows, window_size, H, W)` to solve the following problem:
Window reverse Ar... | Window reverse Args: windows: (n_windows * B, window_size, window_size, C) window_size: (int) window size H: (int) height of image W: (int) width of image Returns: x: (B, H, W, C) |
31,196 | import os
import logging
import paddle
import paddle.nn as nn
def resnet50c(config, norm_layer=nn.BatchNorm2D):
"""resnet50c implement
The ResNet-50 [Heet al., 2016] with dilation convolution at last stage,
ResNet-50 model Ref, https://arxiv.org/pdf/1512.03385.pdf
Args:
config (dict): configurat... | Built the backbone model, defined by `config.MODEL.BACKBONE`. |
31,197 | import math
import logging
from typing import List
from bisect import bisect_right
from paddle.optimizer.lr import LRScheduler
import paddle.optimizer.lr as lr_scheduler
class WarmupCosineLR(LRScheduler):
def __init__(self,
learning_rate: float,
max_iters: int,
... | null |
31,198 | from paddle import optimizer as optim
from paddle.nn import ClipGradByGlobalNorm
The provided code snippet includes necessary dependencies for implementing the `get_optimizer` function. Write a Python function `def get_optimizer(model, lr_scheduler, config)` to solve the following problem:
Get Optimizer for Training A... | Get Optimizer for Training Attributes: model: nn.Layer, training model lr_scheduler: (LRScheduler|float), learning rate scheduler config: CfgNode, hyper for optimizer |
31,199 | import warnings
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
def resize(input_data,
size=None,
scale_factor=None,
mode='nearest',
align_corners=None,
warning=True):
if warning:
if size is not None and align_corners:
... | null |
31,200 | import copy
import paddle
import paddle.nn as nn
The provided code snippet includes necessary dependencies for implementing the `readout_oper` function. Write a Python function `def readout_oper(config)` to solve the following problem:
get the layer to process the feature asnd the cls token
Here is the function:
def... | get the layer to process the feature asnd the cls token |
31,201 | import copy
import paddle
import paddle.nn as nn
The provided code snippet includes necessary dependencies for implementing the `get_scratch` function. Write a Python function `def get_scratch(config, groups=1, expand=False)` to solve the following problem:
function to get the layer to make sure the features have the ... | function to get the layer to make sure the features have the same dims |
31,202 | import copy
import paddle
import paddle.nn as nn
The provided code snippet includes necessary dependencies for implementing the `get_process` function. Write a Python function `def get_process(config)` to solve the following problem:
function to get the layers to process the feature from the backbone
Here is the func... | function to get the layers to process the feature from the backbone |
31,207 | from paddle.io import BatchSampler, DistributedBatchSampler, DataLoader
class IterationBasedBatchSampler(BatchSampler):
"""
Wraps a BatchSampler, resampling from it until
a specified number of iterations have been sampled.
"""
def __init__(self, batch_sampler, num_iterations, start_iter=0):
... | get iterable data loader, the lenth is num_iters. |
31,208 | import math
import os
import paddle.nn.functional as F
import paddle
from src.utils import logger
def load_pretrained_model(model, pretrained_model, pos_embed_interp=True):
if pretrained_model is not None:
logger.info('Loading pretrained model from {}'.format(pretrained_model))
if os.path.exists(pre... | Load the weights of the whole model Arges: model: model based paddle pretrained: the path of weight file of model |
31,209 | import math
import os
import paddle.nn.functional as F
import paddle
from src.utils import logger
def resume(model, optimizer, resume_model):
if resume_model is not None:
logger.info('Resume model from {}'.format(resume_model))
if os.path.exists(resume_model):
resume_model = os.path.nor... | null |
31,210 | import time
def calculate_eta(remaining_step, speed):
if remaining_step < 0:
remaining_step = 0
remaining_time = int(remaining_step * speed)
result = "{:0>2}:{:0>2}:{:0>2}"
arr = []
for i in range(2, -1, -1):
arr.append(int(remaining_time / 60**i))
remaining_time %= 60**i
... | null |
31,211 | import cv2
import numpy as np
def get_pseudo_color_map(num_classes=256):
"""
Get the pseduo color map for visualizing the segmentation mask,
Args:
num_classes (int): Number of classes.
Returns:
colar_map (list): The color map.
"""
num_classes += 1
color_map = num_classes * [0... | Convert predict result to color image, and save added image. Args: img_path (str): The path of input image. pred (np.ndarray): The predict result of segmentation model. weight (float): The image weight of visual image, and the result weight is (1 - weight). Default: 0.6 Returns: vis_result (np.ndarray): the visualized ... |
31,212 | import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_cityscapes_color_map` function. Write a Python function `def get_cityscapes_color_map()` to solve the following problem:
Get the color map of Cityscapes dataset Returns: color_map (list): The color map of ... | Get the color map of Cityscapes dataset Returns: color_map (list): The color map of Cityscapes |
31,213 | import sys
import time
import paddle
def log(level=2, message=""):
if paddle.distributed.ParallelEnv().local_rank == 0:
current_time = time.time()
time_array = time.localtime(current_time)
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
if log_level >= level:
... | null |
31,214 | import sys
import time
import paddle
def log(level=2, message=""):
if paddle.distributed.ParallelEnv().local_rank == 0:
current_time = time.time()
time_array = time.localtime(current_time)
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
if log_level >= level:
... | null |
31,215 | import numpy as np
import paddle
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `calculate_area` function. Write a Python function `def calculate_area(pred, label, num_classes, ignore_index=255)` to solve the following problem:
Calculate intersect, predi... | Calculate intersect, prediction and label area Args: pred (type: Tensor, shape: [B,1,H,W]): prediction results. label (type: Tensor, shape: [B,1,H,W]): ground truth (segmentation) num_classes (int): The unique number of target classes. ignore_index (int): Specifies a class that is ignored. Default: 255. Returns: Tensor... |
31,216 | import numpy as np
import paddle
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `mean_iou` function. Write a Python function `def mean_iou(intersect_area, pred_area, label_area)` to solve the following problem:
Calculate iou. Args: intersect_area (Tensor... | Calculate iou. Args: intersect_area (Tensor): The intersection area of prediction and ground truth on all classes. pred_area (Tensor): The prediction area on all classes. label_area (Tensor): The ground truth area on all classes. Returns: class_iou (np.ndarray): iou on all classes. mean_iou (float): mean iou of all cla... |
31,217 | import numpy as np
import paddle
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `accuracy` function. Write a Python function `def accuracy(intersect_area, pred_area)` to solve the following problem:
Calculate accuracy Args: intersect_area (Tensor): The i... | Calculate accuracy Args: intersect_area (Tensor): The intersection area of prediction and ground truth on all classeds. pred_area (Tensor): The prediction area on all classes. Returns: class_acc (np.ndarray): accuracy on all classes. mean_acc (float): mean accuracy. |
31,218 | import numpy as np
import paddle
import paddle.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `kappa` function. Write a Python function `def kappa(intersect_area, pred_area, label_area)` to solve the following problem:
Calculate kappa coefficient Args: intersect_area ... | Calculate kappa coefficient Args: intersect_area (Tensor): The intersection area of prediction and ground truth on all classes. pred_area (Tensor): The prediction area on all classes. label_area (Tensor): The ground truth area on all classes. Returns: kappa (float): kappa coefficient. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.