id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
25,987 | import torch.nn as nn
import numpy as np
import torch
import copy
def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1):
result = nn.Sequential()
result.add_module('conv', nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
ke... | null |
25,988 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,989 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,990 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,991 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
def _make_stage(self, planes, num_blocks, stride):
def forward(self, x):
def ... | null |
25,992 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,993 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,994 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,995 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,996 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,997 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,998 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
25,999 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
26,000 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
26,001 | import torch.nn as nn
import numpy as np
import torch
import copy
class RepVGG(nn.Module):
def __init__(self, num_blocks, width_multiplier, feat_dim=512, out_h=7, out_w=7, override_groups_map=None, deploy=False, use_se=False):
super(RepVGG, self).__init__()
assert len(width_multiplier) == 4
... | null |
26,002 | import torch.nn as nn
import numpy as np
import torch
import copy
func_dict = {
'RepVGG-A0': create_RepVGG_A0,
'RepVGG-A1': create_RepVGG_A1,
'RepVGG-A2': create_RepVGG_A2,
'RepVGG-B0': create_RepVGG_B0,
'RepVGG-B1': create_RepVGG_B1,
'RepVGG-B1g2': create_RepVGG_B1g2,
'RepVGG-B1g4': create_RepVGG_B1g4,
'RepVGG-B2': cr... | null |
26,003 | import torch.nn as nn
import numpy as np
import torch
import copy
def repvgg_model_convert(model:torch.nn.Module, save_path=None, do_copy=True):
if do_copy:
model = copy.deepcopy(model)
for module in model.modules():
if hasattr(module, 'switch_to_deploy'):
module.switch_to_deploy()
... | null |
26,004 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class resblock(nn.Module):
def __init__(self, in_channels, out_channels):
super(resblock, self).__init__()
self.conv1 = mfm(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.conv2 = mfm(in_channe... | null |
26,005 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def LightCNN_9Layers(drop_ratio, out_h, out_w, feat_dim):
def LightCNN_29Layers_v2(drop_ratio, out_h, out_w, feat_dim):
def LightCNN(depth, drop_ratio, out_h, out_w, feat_dim):
if depth == 9:
return LightCNN_9Layers(drop_ratio, ... | null |
26,006 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Sequential, BatchNorm2d, Dropout, Module, Linear, BatchNorm1d
The provided code snippet includes necessary dependencies for implementing the `_make_divisible` function. Write a Python function `def _make_divisible(v, di... | 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 |
26,007 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Sequential, BatchNorm2d, Dropout, Module, Linear, BatchNorm1d
def hard_sigmoid(x, inplace: bool = False):
if inplace:
return x.add_(3.).clamp_(0., 6.).div_(6.)
else:
return F.relu6(x + 3.) / 6. | null |
26,008 | import torch
from .resnet import ResNet, Bottleneck
_model_sha256 = {name: checksum for checksum, name in [
('d8fbf808', 'resnest50_fast_1s1x64d'),
('44938639', 'resnest50_fast_2s1x64d'),
('f74f3fc3', 'resnest50_fast_4s1x64d'),
('32830b84', 'resnest50_fast_1s2x40d'),
('9d126481', 'resnest50_fast_2s2... | null |
26,009 | import torch
from .resnet import ResNet, Bottleneck
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
name in _model_sha256.keys()
}
class Bottleneck(nn.Module):
def __init__(self, inplanes, planes, stride=1, downsample=None,
radix=1, cardinality=1, bottleneck_wid... | null |
26,010 | import torch
from .resnet import ResNet, Bottleneck
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
name in _model_sha256.keys()
}
class Bottleneck(nn.Module):
"""ResNet Bottleneck
"""
# pylint: disable=unused-argument
expansion = 4
def __init__(self, inplanes, planes... | null |
26,011 | import torch
from .resnet import ResNet, Bottleneck
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
name in _model_sha256.keys()
}
class Bottleneck(nn.Module):
"""ResNet Bottleneck
"""
# pylint: disable=unused-argument
expansion = 4
def __init__(self, inplanes, planes... | null |
26,012 | import torch
from .resnet import ResNet, Bottleneck
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
name in _model_sha256.keys()
}
class Bottleneck(nn.Module):
"""ResNet Bottleneck
"""
# pylint: disable=unused-argument
expansion = 4
def __init__(self, inplanes, planes... | null |
26,013 | import torch
from .resnet import ResNet, Bottleneck
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
name in _model_sha256.keys()
}
class Bottleneck(nn.Module):
"""ResNet Bottleneck
"""
# pylint: disable=unused-argument
expansion = 4
def __init__(self, inplanes, planes... | null |
26,014 | import torch
from .resnet import ResNet, Bottleneck
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
name in _model_sha256.keys()
}
class Bottleneck(nn.Module):
"""ResNet Bottleneck
"""
# pylint: disable=unused-argument
expansion = 4
def __init__(self, inplanes, planes... | null |
26,015 | import torch
from .resnet import ResNet, Bottleneck
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
name in _model_sha256.keys()
}
class Bottleneck(nn.Module):
"""ResNet Bottleneck
"""
# pylint: disable=unused-argument
expansion = 4
def __init__(self, inplanes, planes... | null |
26,016 | import torch
import torch.nn as nn
from .resnet import ResNet, Bottleneck
def l2_norm(input,axis=1):
norm = torch.norm(input,2,axis,True)
output = torch.div(input, norm)
return output | null |
26,017 | import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
def channel_shuffle(x, groups):
assert groups > 1
batchsize, num_channels, height, width = x.size()
assert (num_channels % groups == 0)
channels_per_group = num_channels // groups
# reshape
x = x.vie... | null |
26,018 | import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
def get_same_padding(kernel_size):
if isinstance(kernel_size, tuple):
assert len(kernel_size) == 2, 'invalid kernel size: {}'.format(kernel_size)
p1 = get_same_padding(kernel_size[0])
p2 = get_same_... | null |
26,019 | import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition(x, window_size)` to ... | Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) |
26,020 | import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_reverse(windows, window_size, H,... | 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) |
26,021 | import os
import sys
import shutil
import argparse
import logging as logger
import torch
import torch.distributed as dist
import torch.utils.data.distributed
from torch import optim
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from apex import amp
from optimizer import build_optimize... | Total training procedure. |
26,022 | import os
import sys
import shutil
import argparse
import logging as logger
import torch
from torch import optim
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from losses import OnlineContrastiveLoss, OnlineTripletLoss
from pair_selector import HardNegativePairSelector, FunctionNegative... | Total training procedure. |
26,023 | from itertools import combinations
import numpy as np
import torch
def pdist(vectors):
distance_matrix = -2 * vectors.mm(torch.t(vectors)) + vectors.pow(2).sum(dim=1).view(1, -1) + vectors.pow(2).sum(
dim=1).view(-1, 1)
return distance_matrix | null |
26,024 | from itertools import combinations
import numpy as np
import torch
def hardest_negative(loss_values):
hard_negative = np.argmax(loss_values)
return hard_negative if loss_values[hard_negative] > 0 else None
class FunctionNegativeTripletSelector(TripletSelector):
"""
For each positive pair, takes the hard... | null |
26,025 | from itertools import combinations
import numpy as np
import torch
def random_hard_negative(loss_values):
hard_negatives = np.where(loss_values > 0)[0]
return np.random.choice(hard_negatives) if len(hard_negatives) > 0 else None
class FunctionNegativeTripletSelector(TripletSelector):
"""
For each positi... | null |
26,026 | from itertools import combinations
import numpy as np
import torch
def semihard_negative(loss_values, margin):
semihard_negatives = np.where(np.logical_and(loss_values < margin, loss_values > 0))[0]
return np.random.choice(semihard_negatives) if len(semihard_negatives) > 0 else None
class FunctionNegativeTriple... | null |
26,027 | import os
import sys
import shutil
import argparse
import logging as logger
import torch
import torch.distributed as dist
import torch.utils.data.distributed
from torch import optim
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from utils.AverageMeter import AverageMeter
from data_pro... | Total training procedure. |
26,028 | import os
import sys
import shutil
import argparse
import logging as logger
import torch
from torch import optim
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from utils.AverageMeter import AverageMeter
from data_processor.train_dataset import ImageDataset
from backbone.backbone_def imp... | Total training procedure. |
26,029 | import os
import sys
import shutil
import argparse
import logging as logger
import torch
from torch import optim
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from apex import amp
from utils.AverageMeter import AverageMeter
from data_processor.train_dataset import ImageDataset
from back... | Total training procedure. |
26,030 | import os
import cv2
import numpy as np
from skimage import transform as trans
from core.image_cropper.BaseImageCropper import BaseImageCropper
from utils.lms_trans import lms106_2_lms5, lms25_2_lms5
def estimate_norm(lmk, image_size = 112, mode='arcface'):
assert lmk.shape==(5,2)
tform = trans.SimilarityTransform(... | null |
26,031 | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(inp, oup, kernel_size, stride, padding=1, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU):
return nn.Sequential(
conv_layer(inp, oup, kernel_size, stride, padding, bias=False),
norm_layer(oup),
... | null |
26,033 | import torch
import torch.nn as nn
import torchvision.models._utils as _utils
import torch.nn.functional as F
from collections import OrderedDict
def conv_bn(inp, oup, stride = 1, leaky = 0):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.LeakyR... | null |
26,034 | import torch
import torch.nn as nn
import torchvision.models._utils as _utils
import torch.nn.functional as F
from collections import OrderedDict
def conv_bn_no_relu(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
) | null |
26,035 | import torch
import torch.nn as nn
import torchvision.models._utils as _utils
import torch.nn.functional as F
from collections import OrderedDict
def conv_bn1X1(inp, oup, stride, leaky=0):
return nn.Sequential(
nn.Conv2d(inp, oup, 1, stride, padding=0, bias=False),
nn.BatchNorm2d(oup),
nn.L... | null |
26,036 | import torch
import torch.nn as nn
import torchvision.models._utils as _utils
import torch.nn.functional as F
from collections import OrderedDict
def conv_dw(inp, oup, stride, leaky=0.1):
return nn.Sequential(
nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),
nn.BatchNorm2d(inp),
n... | null |
26,037 | from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
def l2_norm(input,axis=1):
norm = torch.norm(input,2,axis,True)
output = torch.div(input, norm)
return output | null |
26,038 | from typing import Optional, Tuple
import torch
from PIL import Image
import matplotlib.pyplot as plt
import math
def bchw2hwc(images: torch.Tensor, nrows: Optional[int] = None, border: int = 2,
background_value: float = 0) -> torch.Tensor:
""" make a grid image from an image batch.
Args:
... | null |
26,039 | from typing import Dict, List
import torch
import colorsys
import random
import numpy as np
from skimage.draw import line_aa, circle_perimeter_aa
def _gen_random_colors(N, bright=True):
brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys... | null |
26,040 | from typing import Dict, List
import torch
import colorsys
import random
import numpy as np
from skimage.draw import line_aa, circle_perimeter_aa
def select_data(selection, data):
if isinstance(data, dict):
return {name: select_data(selection, val) for name, val in data.items()}
elif isinstance(data, (... | null |
26,041 | from typing import Dict, List
import torch
import colorsys
import random
import numpy as np
from skimage.draw import line_aa, circle_perimeter_aa
def _draw_hwc(image: torch.Tensor, data: Dict[str, torch.Tensor]):
dtype = image.dtype
h, w, _ = image.shape
for tag, batch_content in data.items():
if ta... | null |
26,042 | lms25_2_lms106 = {1:105, 2:106, 3:34, 4:38, 5:43,
6:47, 7:52, 8:55, 9:88, 10:94,
11:85, 12:91, 13:63, 14:59, 15:99,
16:61, 17:71, 18:73, 19:67, 20:80,
21:82, 22:76, 23:36, 24:45, 25:17}
def lms106_2_lms25(lms_106):
lms25 = []
for cur_point... | null |
26,043 | lms5_2_lms106 = {1:105, 2:106, 3:55, 4:85, 5:91}
def lms106_2_lms5(lms_106):
lms5 = []
for cur_point_index in range(5):
cur_point_id = cur_point_index + 1
point_id_106 = lms5_2_lms106[cur_point_id]
cur_point_index_106 = point_id_106 - 1
cur_point_x = lms_106[cur_point_index_106 ... | null |
26,044 | lms5_2_lms25 = {1:1, 2:2, 3:8, 4:11, 5:12}
def lms25_2_lms5(lms_25):
lms5 = []
for cur_point_index in range(5):
cur_point_id = cur_point_index + 1
point_id_25 = lms5_2_lms25[cur_point_id]
cur_point_index_25 = point_id_25 - 1
cur_point_x = lms_25[cur_point_index_25 * 2]
c... | null |
26,045 | from typing import List, Dict, Callable, Tuple, Optional
import torch
import torch.nn.functional as F
import functools
def get_similarity_transform_matrix(
from_pts: torch.Tensor, to_pts: torch.Tensor) -> torch.Tensor:
"""
Args:
from_pts, to_pts: b x n x 2
Returns:
torch.Tensor: b x ... | null |
26,046 | from typing import List, Dict, Callable, Tuple, Optional
import torch
import torch.nn.functional as F
import functools
def _forge_grid(batch_size: int, device: torch.device,
output_shape: Tuple[int, int],
fn: Callable[[torch.Tensor], torch.Tensor]
) -> Tuple[torch.Tensor,... | Args: matrix: bx4x4 matrix. warp_factor: The warping factor. `warp_factor=1.0` represents a vannila Tanh-warping, `warp_factor=0.0` represents a cropping. warped_shape: The target image shape to transform to. Returns: torch.Tensor: b x h x w x 2 (x, y). |
26,047 | from typing import List, Dict, Callable, Tuple, Optional
import torch
import torch.nn.functional as F
import functools
def _forge_grid(batch_size: int, device: torch.device,
output_shape: Tuple[int, int],
fn: Callable[[torch.Tensor], torch.Tensor]
) -> Tuple[torch.Tensor,... | Args: matrix: bx4x4 matrix. warp_factor: The warping factor. `warp_factor=1.0` represents a vannila Tanh-warping, `warp_factor=0.0` represents a cropping. warped_shape: The target image shape to transform to. orig_shape: The original image shape that is transformed from. Returns: torch.Tensor: b x h x w x 2 (x, y). |
26,048 | import os
from face_masker import FaceMasker
The provided code snippet includes necessary dependencies for implementing the `get_lms_templateName` function. Write a Python function `def get_lms_templateName(face_info_file, image_name2template_name_file, masked_face_root)` to solve the following problem:
Generate to do... | Generate to do task list. Args: face_info_file: The file which contains image_name and landmarks. image_name2template_name_file: a mapping file masked_face_root: Targe folder to save masked images. Returns: image_name2lms dict, image_name2template_name dict. |
26,049 | import numpy as np
def isPointInTri(point, tri_points):
''' Judge whether the point is in the triangle
Method:
http://blackpawn.com/texts/pointinpoly/
Args:
point: [u, v] or [x, y]
tri_points: three vertices(2d points) of a triangle. 2 coords x 3 vertices
Returns:
bool: ... | render mesh by z buffer Args: vertices: 3 x nver colors: 3 x nver triangles: 3 x ntri h: height w: width |
26,050 | import numpy as np
def get_point_weight(point, tri_points):
''' Get the weights of the position
Methods: https://gamedev.stackexchange.com/questions/23743/whats-the-most-efficient-way-to-find-barycentric-coordinates
-m1.compute the area of the triangles formed by embedding the point P inside the triangle
... | Args: triangles: 3 x ntri # src src_image: height x width x nchannels src_vertices: 3 x nver # dst dst_vertices: 3 x nver dst_triangle_buffer: height x width. the triangle index of each pixel in dst image Returns: dst_image: height x width x nchannels |
26,051 | import numpy as np
def isPointInTri(point, tri_points):
''' Judge whether the point is in the triangle
Method:
http://blackpawn.com/texts/pointinpoly/
Args:
point: [u, v] or [x, y]
tri_points: three vertices(2d points) of a triangle. 2 coords x 3 vertices
Returns:
bool: ... | Args: vertices: 3 x nver triangles: 3 x ntri h: height w: width Returns: depth_buffer: height x width ToDo: whether to add x, y by 0.5? the center of the pixel? m3. like somewhere is wrong # Each triangle has 3 vertices & Each vertex has 3 coordinates x, y, z. # Here, the bigger the z, the fronter the point. |
26,052 | import numpy as np
def get_depth_buffer(vertices, triangles, h, w):
'''
Args:
vertices: 3 x nver
triangles: 3 x ntri
h: height
w: width
Returns:
depth_buffer: height x width
ToDo:
whether to add x, y by 0.5? the center of the pixel?
m3. like somewh... | Args: vertices: 3 x nver triangles: 3 x ntri depth_buffer: height x width Returns: vertices_vis: nver. the visibility of each vertex |
26,053 | import numpy as np
def read_landmark_106_file(filepath):
map = [[1,2],[3,4],[5,6],7,9,11,[12,13],14,16,18,[19,20],21,23,25,[26,27],[28,29],[30,31],33,34,35,36,37,42,43,44,45,46,51,52,53,54,58,59,60,61,62,66,67,69,70,71,73,75,76,78,79,80,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103]
line =... | null |
26,054 | import numpy as np
def read_landmark_106_array(face_lms):
map = [[1,2],[3,4],[5,6],7,9,11,[12,13],14,16,18,[19,20],21,23,25,[26,27],[28,29],[30,31],33,34,35,36,37,42,43,44,45,46,51,52,53,54,58,59,60,61,62,66,67,69,70,71,73,75,76,78,79,80,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103]
pts1 ... | null |
26,055 | import numpy as np
def read_landmark_106(filepath):
map = [[1,2],[3,4],[5,6],7,9,11,[12,13],14,16,18,[19,20],21,23,25,[26,27],[28,29],[30,31],33,34,35,36,37,42,43,44,45,46,51,52,53,54,58,59,60,61,62,66,67,69,70,71,73,75,76,78,79,80,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103]
lines = ope... | null |
26,056 | import numpy as np
def read_bbox(filepath):
lines = open(filepath).readlines()
bbox = lines[0].strip().split()
bbox = [int(float(_)) for _ in bbox]
return np.array(bbox) | null |
26,057 | import os
import cv2
if not os.path.exists(img_dir):
os.makedirs(img_dir)
def save_image(image, img_dir, vedio_name, num):
flod_path = img_dir + vedio_name[:-4] + '/'
if not os.path.exists(flod_path):
os.makedirs(flod_path)
address = flod_path + vedio_name[:-4] + '_' + str(num) + '_scene.jpg'
... | null |
26,058 | import os
import copy
import math
import time
import random
import numpy as np
from PIL import Image
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
def default_loader(path):
img = Image.open(path).convert('L')
return img | null |
26,059 | import os
import copy
import math
import time
import random
import numpy as np
from PIL import Image
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
def default_list_reader(fileList):
imgList = []
with open(fileList, 'r') as file:
for line in file.readlines():
... | null |
26,060 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def make_layer(block, num_of_layer, inc=64, outc=64, groups=1):
if num_of_layer < 1:
num_of_layer = 1
layers = []
layers.append(block(inc=inc, outc=outc, groups=groups))
for... | null |
26,061 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def rgb2gray(img):
r, g, b = torch.split(img, 1, dim=1)
return torch.mul(r, 0.299) + torch.mul(g, 0.587) + torch.mul(b, 0.114) | null |
26,062 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def reparameterize(mu, logvar):
std = logvar.mul(0.5).exp_()
eps = torch.cuda.FloatTensor(std.size()).normal_()
return eps.mul(std).add_(mu) | null |
26,063 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def kl_loss(mu, logvar, prior_mu=0):
v_kl = mu.add(-prior_mu).pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar)
v_kl = v_kl.sum(dim=-1).mul_(-0.5) # (batch, 2)
return v_kl | null |
26,064 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def reconstruction_loss(prediction, target, size_average=False):
error = (prediction - target).view(prediction.size(0), -1)
error = error ** 2
error = torch.sum(error, dim=-1)
if size_average:
... | null |
26,065 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def load_model(model, pretrained):
weights = torch.load(pretrained)
pretrained_dict = weights['model'].state_dict()
model_dict = model.state_dict()
# 1. filter out unnecessary keys
pretrained_dict ... | null |
26,066 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def save_checkpoint(model_path, model, epoch, iteration, name):
model_out_path = model_path + name + "model_epoch_{}_iter_{}.pth".format(epoch, iteration)
state = {"epoch": epoch, "model": model}
if not os... | null |
26,067 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def MMD_Loss(fc_nir, fc_vis):
mean_fc_nir = torch.mean(fc_nir, 0)
mean_fc_vis = torch.mean(fc_vis, 0)
loss_mmd = F.mse_loss(mean_fc_nir, mean_fc_vis)
return loss_mmd | null |
26,068 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
def adjust_learning_rate(lr, step, optimizer, epoch):
scale = 0.457305051927326
lr = lr * (scale ** (epoch // step))
print('lr: {}'.format(lr))
if (epoch != 0) & (epoch % step == 0):
print('Cha... | null |
26,069 | import os
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `accuracy` function. Write a Python function `def accuracy(output, target, topk=(1,))` to solve the following problem:
Computes the precis... | Computes the precision@k for the specified values of k |
26,070 | from __future__ import print_function, division
import torch
import matplotlib.pyplot as plt
import argparse, os
import numpy as np
from torch.utils.data import DataLoader
from torchvision import transforms
from models.CDCNs_u import Conv2d_cd, CDCN_u
from Load_OULUNPUcrop_train import Spoofing_train_g, SeparateBatchSa... | compute contrast depth in both of (out, label) |
26,071 | from __future__ import print_function, division
import torch
import matplotlib.pyplot as plt
import argparse, os
import numpy as np
from torch.utils.data import DataLoader
from torchvision import transforms
from models.CDCNs_u import Conv2d_cd, CDCN_u
from Load_OULUNPUcrop_train import Spoofing_train_g, SeparateBatchSa... | null |
26,072 | import math
import os
import cv2
import numpy as np
def crop_face_from_scene(image, face_name_full, scale):
f = open(face_name_full, 'r')
lines = f.readlines()
lines = lines[0].split(' ')
y1, x1, w, h = [int(ele) for ele in lines[:4]]
f.close()
y2 = y1 + w
x2 = x1 + h
y_mid = (y1 + y2)... | null |
26,073 | import math
import os
import cv2
import numpy as np
def crop_face_from_scene_prnet(image, face_name_full, scale):
h_img, w_img = image.shape[0], image.shape[1]
f = open(face_name_full, 'r')
lines = f.readlines()
lines = lines[0].split(' ')
l, r, t, b = [int(ele) for ele in lines[:4]]
if l < 0:
... | null |
26,074 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.... | null |
26,075 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def get_threshold(score_file):
with open(score_file, 'r') as file:
lines =... | null |
26,076 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def test_threshold_based(threshold, score_file):
with open(score_file, 'r') as fil... | null |
26,077 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def get_err_threhold(fpr, tpr, threshold):
RightIndex = (tpr + (1 - fpr) - 1)
r... | null |
26,078 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def get_err_threhold(fpr, tpr, threshold):
RightIndex = (tpr + (1 - fpr) - 1)
r... | null |
26,079 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def get_err_threhold_CASIA_Replay(fpr, tpr, threshold):
RightIndex = (tpr + (1 - fp... | null |
26,080 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def get_err_threhold_CASIA_Replay(fpr, tpr, threshold):
RightIndex = (tpr + (1 - fp... | null |
26,081 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def count_parameters_in_MB(model):
return np.sum(np.prod(v.size()) for name, v in ... | null |
26,082 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def save_checkpoint(state, is_best, save):
filename = os.path.join(save, 'checkpoi... | null |
26,083 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def load(model, model_path):
model.load_state_dict(torch.load(model_path)) | null |
26,084 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def drop_path(x, drop_prob):
if drop_prob > 0.:
keep_prob = 1. - drop_prob... | null |
26,085 | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
import sklearn
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
import pdb
def create_exp_dir(path, scripts_to_save=None):
if not os.path.exists(path):
... | null |
26,086 | import math
import torch
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch import nn
from torch.nn import Parameter
import pdb
import numpy as np
class ResidualBlock(nn.Module):
def __init__(self, inchannel, outchannel, stride=1):
def forward(self, x):
class ResNet(nn.Module... | null |
26,088 | import sys
import math
import torch
import torch.nn.functional as F
from torch.nn import Module, Parameter
import torch.nn as nn
from backbones.resnet import ResNet, BasicBlock, Bottleneck
from backbones.resnet_ibn_a import resnet50_ibn_a
def l2_norm(input, axis=1):
norm = torch.norm(input, 2, axis, True)
outp... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.