id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
31,219
import os from yacs.config import CfgNode as CN import yaml def _update_config_from_file(config, cfg_file): config.defrost() with open(cfg_file, 'r') as infile: yaml_cfg = yaml.load(infile, Loader=yaml.FullLoader) for cfg in yaml_cfg.setdefault('BASE', ['']): if cfg: _update_conf...
Update config by ArgumentParser Args: args: ArgumentParser contains options Return: config: updated config
31,220
import os from yacs.config import CfgNode as CN import yaml _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 4 _C.DATA.BATCH_SIZE_VAL = 1 _C.DATA.DATASET = 'PascalContext' _C.DATA.DATA_PATH = '/home/ssd3/wutianyi/datasets/pascal_context' _C.DATA.CROP_SIZE = (480,480) _C.DATA.NUM_CLASSES = 60 _C.DATA.NUM_W...
null
31,221
import os import time import shutil import random import argparse import numpy as np import cv2 from PIL import Image as PILImage import shutil import paddle import paddle.nn.functional as F import sys from config import * from src.api import infer from src.transforms import Compose, Resize, Normalize from src.models ...
null
31,222
import time import shutil import random import argparse import numpy as np import paddle import paddle.nn.functional as F from config import * from src.api import infer from src.datasets import get_dataset from src.transforms import Resize, Normalize from src.models import get_model from src.utils import multi_val_fn ...
null
31,223
import argparse import os.path as osp from functools import partial import mmcv import numpy as np from detail import Detail from PIL import Image _mapping = np.sort( np.array([ 0, 2, 259, 260, 415, 324, 9, 258, 144, 18, 19, 22, 23, 397, 25, 284, 158, 159, 416, 33, 162, 420, 454, 295, 296, 427, 44, ...
null
31,224
import argparse import os.path as osp from functools import partial import mmcv import numpy as np from detail import Detail from PIL import Image def parse_args(): parser = argparse.ArgumentParser( description='Convert PASCAL VOC annotations to mmdetection format') parser.add_argument('--devkit_path',...
null
31,225
import argparse import os.path as osp import mmcv from cityscapesscripts.preparation.json2labelImg import json2labelImg def convert_json_to_label(json_file): label_file = json_file.replace('_polygons.json', '_labelTrainIds.png') json2labelImg(json_file, label_file, 'trainIds')
null
31,226
import argparse import os.path as osp import mmcv from cityscapesscripts.preparation.json2labelImg import json2labelImg def parse_args(): parser = argparse.ArgumentParser( description='Convert Cityscapes annotations to TrainIds') parser.add_argument('--cityscapes_path', default='/home/ssd3/wuti...
null
31,227
import sys import argparse import os import numpy as np import paddle import torch import legacy import dnnlib from generator import Generator as Generator_paddle from config import * print(config) def print_model_named_params(model): sum=0 print('----------------------------------') for name, param in mod...
null
31,228
import sys import argparse import os import numpy as np import paddle import torch import legacy import dnnlib from generator import Generator as Generator_paddle from config import * print(config) def print_model_named_buffers(model): sum=0 print('----------------------------------') for name, param in mo...
null
31,229
import sys import argparse import os import numpy as np import paddle import torch import legacy import dnnlib from generator import Generator as Generator_paddle from config import * print(config) def torch_to_paddle_mapping(): resolution = config.MODEL.GEN.RESOLUTION prefix = f'synthesis.b{resolution}_0' ...
null
31,233
import sys import argparse import os import numpy as np import paddle import torch import legacy import dnnlib from training.networks_Generator import * from generator import Generator as Generator_paddle from config import * print(config) def print_model_named_params(model): sum=0 print('---------------------...
null
31,234
import sys import argparse import os import numpy as np import paddle import torch import legacy import dnnlib from training.networks_Generator import * from generator import Generator as Generator_paddle from config import * print(config) def print_model_named_buffers(model): sum=0 print('--------------------...
null
31,235
import sys import argparse import os import numpy as np import paddle import torch import legacy import dnnlib from training.networks_Generator import * from generator import Generator as Generator_paddle from config import * print(config) def torch_to_paddle_mapping(): resolution = config.MODEL.GEN.RESOLUTION ...
null
31,239
import copy import paddle from .Registry import * METRICS = Registry("METRIC") def build_metric(cfg): cfg_ = cfg.copy() name = cfg_.pop('name', None) metric = METRICS.get(name)(**cfg_) return metric
null
31,240
import os import fnmatch import numpy as np import cv2 import paddle from PIL import Image from cv2 import imread from scipy import linalg from .inception import InceptionV3 from paddle.utils.download import get_weights_path_from_url from .builder import METRICS def _get_activations_from_ims(img, model, batch_size, dim...
null
31,241
import os import fnmatch import numpy as np import cv2 import paddle from PIL import Image from cv2 import imread from scipy import linalg from .inception import InceptionV3 from paddle.utils.download import get_weights_path_from_url from .builder import METRICS def _calculate_frechet_distance(mu1, sigma1, mu2, sigma2,...
null
31,242
import os import fnmatch import numpy as np import cv2 import paddle from PIL import Image from cv2 import imread from scipy import linalg from .inception import InceptionV3 from paddle.utils.download import get_weights_path_from_url from .builder import METRICS def _calculate_frechet_distance(mu1, sigma1, mu2, sigma2,...
null
31,243
import cv2 import numpy as np import paddle from .builder import METRICS def reorder_image(img, input_order='HWC'): """Reorder images to 'HWC' order. If the input_order is (h, w), return (h, w, 1); If the input_order is (c, h, w), return (h, w, c); If the input_order is (h, w, c), return as it is. A...
Calculate PSNR (Peak Signal-to-Noise Ratio). Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Args: img1 (ndarray): Images with range [0, 255]. img2 (ndarray): Images with range [0, 255]. crop_border (int): Cropped pixels in each edge of an image. These pixels are not involved in the PSNR calculation. inpu...
31,244
import cv2 import numpy as np import paddle from .builder import METRICS def _ssim(img1, img2): """Calculate SSIM (structural similarity) for one channel images. It is called by func:`calculate_ssim`. Args: img1 (ndarray): Images with range [0, 255] with order 'HWC'. img2 (ndarray): Images w...
Calculate SSIM (structural similarity). Ref: Image quality assessment: From error visibility to structural similarity The results are the same as that of the official released MATLAB code in https://ece.uwaterloo.ca/~z70wang/research/ssim/. For three-channel images, SSIM is calculated for each channel and then averaged...
31,245
import cv2 import numpy as np import paddle from .builder import METRICS The provided code snippet includes necessary dependencies for implementing the `bgr2ycbcr` function. Write a Python function `def bgr2ycbcr(img, y_only=False)` to solve the following problem: Convert a BGR image to YCbCr image. The bgr version of...
Convert a BGR image to YCbCr image. The bgr version of rgb2ycbcr. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`. In OpenCV, it implements a...
31,246
import inspect import traceback class Registry(object): """ The registry that provides name -> object mapping, to support third-party users' custom modules. To create a registry (inside ppgan): .. code-block:: python BACKBONE_REGISTRY = Registry('BACKBONE') To register an object: .. code...
Build a class from config dict. Args: cfg (dict): Config dict. It should at least contain the key "name". registry (ppgan.utils.Registry): The registry to search the name from. default_args (dict, optional): Default initialization arguments. Returns: class: The constructed class.
31,247
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.distributed as dist from datasets import get_dataloader from datasets import get_dataset from generator import Generator from discriminator import StyleGANv2Discriminator from utils.utils import ...
R1 regularization for discriminator. The core idea is to penalize the gradient on real data alone: when the generator distribution produces the true data distribution and the discriminator is equal to 0 on the data manifold, the gradient penalty ensures that the discriminator cannot create a non-zero gradient orthogona...
31,248
import sys import os import time import logging import argparse import random import numpy as np import paddle import paddle.distributed as dist from datasets import get_dataloader from datasets import get_dataset from generator import Generator from discriminator import StyleGANv2Discriminator from utils.utils import ...
null
31,249
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 datasets from paddle.vision import image_load from stl10_dataset import STL10Dataset from lsun_church_dataset import LSUNchurc...
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 Returns: dataset: dataset object
31,250
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 datasets from paddle.vision import image_load from stl10_dataset import STL10Dataset from lsun_church_dataset import LSUNchurc...
Get dataloader with config, dataset, mode as input, allows multiGPU settings. Multi-GPU loader is implements as distributedBatchSampler. Args: config: see config.py for details dataset: paddle.io.dataset object mode: train/val multi_process: if True, use DistributedBatchSampler to support multi-processing Returns: data...
31,251
import os import io import numpy as np import lmdb from PIL import Image from paddle.io import Dataset The provided code snippet includes necessary dependencies for implementing the `read_image` function. Write a Python function `def read_image(image_bytes)` to solve the following problem: read image from bytes loaded...
read image from bytes loaded from lmdb file Args: image_bytes: bytes, image data in bytes Returns: image: np.array, stores the image with shape [h, w, c]
31,252
import os import io import numpy as np import lmdb from PIL import Image from paddle.io import Dataset def save_image(image, name): img = Image.fromarray(image) img.save(f"{name}.png") def save_images(images, labels, out_path): for idx, image in enumerate(images): out_path = os.path.join(out_path, ...
null
31,253
import os from yacs.config import CfgNode as CN import yaml def _update_config_from_file(config, cfg_file): config.defrost() with open(cfg_file, 'r') as infile: yaml_cfg = yaml.load(infile, Loader=yaml.FullLoader) for cfg in yaml_cfg.setdefault('BASE', ['']): if cfg: _update_conf...
Update config by ArgumentParser Args: args: ArgumentParser contains options Return: config: updated config
31,254
import os from yacs.config import CfgNode as CN import yaml _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 32 _C.DATA.BATCH_SIZE_EVAL = 32 _C.DATA.DATA_PATH = '/dataset/cifar10/' _C.DATA.DATASET = 'cifar10' _C.DATA.IMAGE_SIZE = 32 _C.DATA.CHANNEL = 3 _C.DATA.CROP_PCT = 1.0 _C.DATA.NUM_WORKERS = 2 _C.DATA....
Return a clone of config or load from yaml file
31,255
import math import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from utils.upfirdn2d import setup_filter, Upfirdn2dUpsample from utils.fused_act import fused_leaky_relu The provided code snippet includes necessary dependencies for implementing the `bias_act` function. Write a Pytho...
Slow reference implementation of `bias_act()`
31,256
import math import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from utils.upfirdn2d import setup_filter, Upfirdn2dUpsample from utils.fused_act import fused_leaky_relu def normalize_2nd_moment(x, dim=-1, eps=1e-8): return x * (x.square().mean(axis=dim, keepdim=True) + eps).rsq...
null
31,257
import math import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from utils.upfirdn2d import setup_filter, Upfirdn2dUpsample from utils.fused_act import fused_leaky_relu The provided code snippet includes necessary dependencies for implementing the `lerp` function. Write a Python fu...
Linear interpolation.
31,258
import math import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from utils.upfirdn2d import setup_filter, Upfirdn2dUpsample from utils.fused_act import fused_leaky_relu def modulated_style_mlp(x, weight, styles): batch_size = x.shape[0] channel = x.shape[1] width = x.sh...
null
31,259
import math import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from utils.upfirdn2d import setup_filter, Upfirdn2dUpsample from utils.fused_act import fused_leaky_relu The provided code snippet includes necessary dependencies for implementing the `modulated_channel_attention` func...
Style modulation effect to the input. input feature map is scaled through a style vector, which is equivalent to scaling the linear weight.
31,260
import math import paddle import paddle.nn as nn import paddle.nn.functional as F from utils.equalized import EqualLinear, EqualConv2D from utils.fused_act import FusedLeakyReLU from utils.upfirdn2d import Upfirdn2dBlur def var(x, axis=None, unbiased=True, keepdim=False, name=None): u = paddle.mean(x, axis, True,...
null
31,261
import argparse import os import numpy as np import paddle import torch from training.networks_Generator import * import legacy import dnnlib from generator import Generator from config import * print(config) def print_model_named_params(model): sum=0 print('----------------------------------') for name, p...
null
31,262
import argparse import os import numpy as np import paddle import torch from training.networks_Generator import * import legacy import dnnlib from generator import Generator from config import * print(config) def print_model_named_buffers(model): sum=0 print('----------------------------------') for name, ...
null
31,263
import argparse import os import numpy as np import paddle import torch from training.networks_Generator import * import legacy import dnnlib from generator import Generator from config import * print(config) def torch_to_paddle_mapping(): def convert(torch_model, paddle_model): def _set_value(th_name, pd_name, n...
null
31,264
import os import numpy as np from PIL import Image from paddle.io import Dataset The provided code snippet includes necessary dependencies for implementing the `read_labels` function. Write a Python function `def read_labels(label_path)` to solve the following problem: read data labels from binary file Args: label_pat...
read data labels from binary file Args: label_path: label binary file path, e.g.,'train_y.bin' Returns: labels: np.array, the label array with shape [num_images]
31,265
import os import numpy as np from PIL import Image from paddle.io import Dataset The provided code snippet includes necessary dependencies for implementing the `read_all_images` function. Write a Python function `def read_all_images(data_path)` to solve the following problem: read all images from binary file Args: dat...
read all images from binary file Args: data_path: data binary file path, e.g.,'train_X.bin' Returns: images: np.array, the image array with shape [num_images, 96, 96, 3]
31,266
import os import numpy as np from PIL import Image from paddle.io import Dataset def save_image(image, name): img = Image.fromarray(image) img.save(f"{name}.png") def save_images(images, labels, out_path): for idx, image in enumerate(images): out_path = os.path.join(out_path, str(labels[idx])) ...
null
31,267
import sys import os import time import logging import argparse import random import numpy as np import paddle from datasets import get_dataloader from datasets import get_dataset from generator import Generator from discriminator import StyleGANv2Discriminator from utils.utils import AverageMeter from utils.utils impo...
Training for one epoch Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, a ViT model criterion: nn.criterion epoch: int, current epoch total_epoch: int, total num of epoch, for logging debug_steps: int, num of iters to log info Returns: train_loss_meter.avg train_acc_meter.avg train_time
31,268
import sys import os import time import logging import argparse import random import numpy as np import paddle from datasets import get_dataloader from datasets import get_dataset from generator import Generator from discriminator import StyleGANv2Discriminator from utils.utils import AverageMeter from utils.utils impo...
R1 regularization for discriminator. The core idea is to penalize the gradient on real data alone: when the generator distribution produces the true data distribution and the discriminator is equal to 0 on the data manifold, the gradient penalty ensures that the discriminator cannot create a non-zero gradient orthogona...
31,269
import sys import os import time import logging import argparse import random import numpy as np import paddle from datasets import get_dataloader from datasets import get_dataset from generator import Generator from discriminator import StyleGANv2Discriminator from utils.utils import AverageMeter from utils.utils impo...
Validation for whole dataset Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, a ViT model batch_size: int, batch size (used to init FID measturement) total_epoch: int, total num of epoch, for logging max_real_num: int, max num of real images loaded from dataset max_gen_num: int, max num of f...
31,270
import math import pickle import random import numpy as np import paddle from paddle.optimizer.lr import LRScheduler import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler The provided code snippet includes necessary dependencies for implementing the `get_exclude_from_weight_decay_fn` function. ...
Set params with no weight decay during the training For certain params, e.g., positional encoding in ViT, weight decay may not needed during the learning, this method is used to find these params. Args: exclude_list: a list of params names which need to exclude from weight decay. Returns: exclude_from_weight_decay_fn: ...
31,271
import math import pickle import random import numpy as np import paddle from paddle.optimizer.lr import LRScheduler import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler AUGMENT_FNS = { 'color': [rand_brightness, rand_saturation, rand_contrast], 'translation': [rand_translation], 'c...
method based on Revisiting unreasonable effectiveness of data in deep learning era
31,272
import math import pickle import random import numpy as np import paddle from paddle.optimizer.lr import LRScheduler import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler def rand_brightness(x, affine=None): x = x + (paddle.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) ...
null
31,273
import math import pickle import random import numpy as np import paddle from paddle.optimizer.lr import LRScheduler import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler def rand_saturation(x, affine=None): x_mean = x.mean(dim=1, keepdim=True) x = (x - x_mean) * (paddle.rand(x.size(0),...
null
31,274
import math import pickle import random import numpy as np import paddle from paddle.optimizer.lr import LRScheduler import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler def rand_contrast(x, affine=None): x_mean = x.mean(dim=[1, 2, 3], keepdim=True) x = (x - x_mean) * (paddle.rand(x.si...
null
31,275
import math import pickle import random import numpy as np import paddle from paddle.optimizer.lr import LRScheduler import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler def rand_cutout(x, ratio=0.5, affine=None): if random.random() < 0.3: cutout_size = int(x.size(2) * ratio + 0.5)...
null
31,276
import math import pickle import random import numpy as np import paddle from paddle.optimizer.lr import LRScheduler import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler def rand_translation(x, ratio=0.2, affine=None): shift_x, shift_y = int(x.shape[2] * ratio + 0.5), int(x.shape[3] * rati...
null
31,277
import numpy import paddle import paddle.nn as nn import paddle.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `setup_filter` function. Write a Python function `def setup_filter(f, normalize=True, flip_filter=False, gain=1, separable=None)` to solve the following prob...
r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`. Args: f: Torch tensor, numpy array, or python list of the shape `[filter_height, filter_width]` (non-separable), `[filter_taps]` (separable), `[]` (impulse), or `None` (identity). device: Result device (default: cpu). normalize: Normalize the filter so ...
31,278
import numpy import paddle import paddle.nn as nn import paddle.nn.functional as F def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): _, channel, in_h, in_w = input.shape input = input.reshape((-1, in_h, in_w, 1)) _, in_h, in_w, minor = inpu...
null
31,279
import numpy import paddle import paddle.nn as nn import paddle.nn.functional as F def make_kernel(k): k = paddle.to_tensor(k, dtype='float32') if k.ndim == 1: k = k.unsqueeze(0) * k.unsqueeze(1) k /= k.sum() return k
null
31,280
import paddle import paddle.nn as nn import paddle.nn.functional as F def fused_leaky_relu(input, bias=None, negative_slope=0.2, scale=2 ** 0.5): if bias is not None: rest_dim = [1] * (len(input.shape) - len(bias.shape) - 1) return ( F.leaky_relu( input + bias.reshape((1...
null
31,281
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def uniform_(x, a=-1., b=1.): temp_value = paddle.uniform(min=a, max=b, shape=x.shape) x.set...
null
31,282
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `gelu` function. Writ...
Original Implementation of the gelu activation function in Google Bert repo when initialy created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see https://arxiv.org/abs/1606.08...
31,283
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `leakyrelu` function....
An activation function: if x > 0, return x. else return negative_slope * x. the value of negative_slope is 0.2. more information can see https://www.paddlepaddle.org.cn/documentation/ docs/zh/api/paddle/nn/functional/leaky_relu_cn.html#leaky-relu
31,284
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def _no_grad_trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master u...
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,285
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_exclude_from_wei...
Set params with no weight decay during the training For certain params, e.g., positional encoding in ViT, weight decay may not needed during the learning, this method is used to find these params. Args: exclude_list: a list of params names which need to exclude from weight decay. Returns: exclude_from_weight_decay_fn: ...
31,286
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def leakyrelu(x): return nn.functional.leaky_relu(x, 0.2)
null
31,287
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F AUGMENT_FNS = { 'color': [rand_brightness, rand_saturation, rand_contrast], 'translation': [r...
null
31,288
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def rand_brightness(x, affine=None): x = x + (paddle.rand(x.size(0), 1, 1, 1, dtype=x.dtype, dev...
null
31,289
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def rand_saturation(x, affine=None): x_mean = x.mean(dim=1, keepdim=True) x = (x - x_mean) *...
null
31,290
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def rand_contrast(x, affine=None): x_mean = x.mean(dim=[1, 2, 3], keepdim=True) x = (x - x_m...
null
31,291
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def rand_cutout(x, ratio=0.5, affine=None): if random.random() < 0.3: cutout_size = int(...
null
31,292
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def rand_translation(x, ratio=0.2, affine=None): shift_x, shift_y = int(x.shape[2] * ratio + 0.5...
null
31,293
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `drop_path` function....
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl author created for EfficientNet, etc networks, however,the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github....
31,294
import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F def pixel_upsample(x, H, W): B, N, C = x.shape assert N == H*W x = x.transpose((0, 2, 1)...
null
31,303
import sys import os import time import logging import argparse import random import numpy as np import matplotlib.pyplot as plt import paddle import paddle.distributed as dist from datasets import get_dataloader from datasets import get_dataset from utils import AverageMeter from utils import WarmupCosineScheduler fro...
null
31,304
import os import math from paddle.io import Dataset, DataLoader, DistributedBatchSampler from paddle.vision import transforms, datasets, image_load class ImageNet2012Dataset(Dataset): """Build ImageNet2012 dataset This class gets train/val imagenet datasets, which loads transfomed data and labels. Attribute...
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 Returns: dataset: dataset object
31,305
import os import math from paddle.io import Dataset, DataLoader, DistributedBatchSampler from paddle.vision import transforms, datasets, image_load The provided code snippet includes necessary dependencies for implementing the `get_dataloader` function. Write a Python function `def get_dataloader(config, dataset, mode...
Get dataloader with config, dataset, mode as input, allows multiGPU settings. Multi-GPU loader is implements as distributedBatchSampler. Args: config: see config.py for details dataset: paddle.io.dataset object mode: train/val multi_process: if True, use DistributedBatchSampler to support multi-processing Returns: data...
31,307
import os import io import numpy as np import lmdb from PIL import Image from paddle.io import Dataset def save_image(image, name): def save_images(images, labels, out_path): for idx, image in enumerate(images): out_path = os.path.join(out_path, str(labels[idx])) os.makedirs(out_path, exist_ok=True...
null
31,308
import sys import argparse import json import os import numpy as np import torch import torch.nn as nn import paddle import TransGAN.models_search as models_search from models.ViT_custom import Generator from models.ViT_custom_scale2 import Discriminator from config import get_config, update_config import matplotlib.py...
null
31,309
import sys import argparse import json import os import numpy as np import torch import torch.nn as nn import paddle import TransGAN.models_search as models_search from models.ViT_custom import Generator from models.ViT_custom_scale2 import Discriminator from config import get_config, update_config import matplotlib.py...
null
31,310
import sys import argparse import json import os import numpy as np import torch import torch.nn as nn import paddle import TransGAN.models_search as models_search from models.ViT_custom import Generator from models.ViT_custom_scale2 import Discriminator from config import get_config, update_config import matplotlib.py...
null
31,311
import os from yacs.config import CfgNode as CN import yaml def _update_config_from_file(config, cfg_file): config.defrost() with open(cfg_file, 'r') as infile: yaml_cfg = yaml.load(infile, Loader=yaml.FullLoader) for cfg in yaml_cfg.setdefault('BASE', ['']): if cfg: _update_conf...
Update config by ArgumentParser Args: args: ArgumentParser contains options Return: config: updated config
31,312
import os from yacs.config import CfgNode as CN import yaml _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 32 _C.DATA.DATA_PATH = '/dataset/imagenet/' _C.DATA.DATASET = 'cifar10' _C.DATA.IMAGE_SIZE = 32 _C.DATA.CROP_PCT = 0.875 _C.DATA.NUM_WORKERS = 2 _C.DATA.GEN_BATCH_SIZE = 128 _C.DATA.DIS_BATCH_SIZE = ...
Return a clone of config or load from yaml file
31,316
import sys import os import time import logging import argparse import random import numpy as np import matplotlib.pyplot as plt import paddle import paddle.nn as nn from datasets import get_dataloader from datasets import get_dataset from utils import AverageMeter from utils import WarmupCosineScheduler from utils imp...
null
31,317
import sys import os import time import logging import argparse import random import numpy as np import matplotlib.pyplot as plt import paddle import paddle.nn as nn from datasets import get_dataloader from datasets import get_dataset from utils import AverageMeter from utils import WarmupCosineScheduler from utils imp...
Validation for whole dataset Args: dataloader: paddle.io.DataLoader, dataloader instance model: nn.Layer, a transGAN gen_net model batch_size: int, batch size (used to init FID measturement) total_batch: int, total num of epoch, for logging max_real_num: int, max num of real images loaded from dataset max_gen_num: int,...
31,318
import sys import os import time import logging import argparse import random import numpy as np import matplotlib.pyplot as plt import paddle import paddle.nn as nn from datasets import get_dataloader from datasets import get_dataset from utils import AverageMeter from utils import WarmupCosineScheduler from utils imp...
Training for one epoch Args: args: the default set of net gen_net: nn.Layer, the generator net dis_net: nn.Layer, the discriminator net gen_optimizer: generator's optimizer dis_optimizer: discriminator's optimizer dataloader: paddle.io.DataLoader, dataloader instance lr_schedulers: learning rate epoch: int, current epo...
31,319
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _check_args_tf(kwargs): if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs) def shear_x(img, factor, **kwargs):...
null
31,320
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _check_args_tf(kwargs): if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs) def shear_y(img, factor, **kwargs):...
null
31,321
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _check_args_tf(kwargs): if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs) def translate_x_rel(img, pct, **kwa...
null
31,322
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _check_args_tf(kwargs): if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs) def translate_y_rel(img, pct, **kwa...
null
31,323
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _check_args_tf(kwargs): def translate_x_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
null
31,324
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def _check_args_tf(kwargs): if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs) def translate_y_abs(img, pixels, **...
null
31,325
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _PIL_VER = tuple([int(x) for x in PIL.__version__.split('.')[:2]]) def _check_args_tf(kwargs): def rotate(img, degrees, **kwargs): _check_args_tf(kwargs) if _PIL_VER >= (5, 2): re...
null
31,326
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def auto_contrast(img, **__): return ImageOps.autocontrast(img)
null
31,327
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def invert(img, **__): return ImageOps.invert(img)
null
31,328
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def equalize(img, **__): return ImageOps.equalize(img)
null
31,329
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def solarize(img, thresh, **__): return ImageOps.solarize(img, thresh)
null
31,330
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def solarize_add(img, add, thresh=128, **__): lut = [] for i in range(256): if i < thresh: lut.append(min(255, i + add)) else: lut.append(i) if...
null
31,331
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def posterize(img, bits_to_keep, **__): if bits_to_keep >= 8: return img return ImageOps.posterize(img, bits_to_keep)
null
31,332
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def contrast(img, factor, **__): return ImageEnhance.Contrast(img).enhance(factor)
null
31,333
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def color(img, factor, **__): return ImageEnhance.Color(img).enhance(factor)
null
31,334
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor)
null
31,335
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np def sharpness(img, factor, **__): return ImageEnhance.Sharpness(img).enhance(factor)
null
31,336
import random import math import re from PIL import Image, ImageOps, ImageEnhance, ImageChops import PIL import numpy as np _MAX_LEVEL = 10. def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v def _rotate_level_to_arg(level, _hparams): # range [-30, 30] ...
null