id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
180,912 | import torch
import torch.nn as nn
from torch.nn import init
import functools
import numpy as np
from . import resnet
def get_norm_layer(norm_type='instance'):
if norm_type == 'batch':
norm_layer = functools.partial(nn.BatchNorm2d, affine=True)
elif norm_type == 'instance':
norm_layer = functoo... | null |
180,913 | import torch
import torch.nn as nn
from torch.nn import init
import functools
import numpy as np
from . import resnet
def print_network(net):
num_params = 0
for param in net.parameters():
num_params += param.numel()
print(net)
print('Total number of parameters: %d' % num_params) | null |
180,914 | import torch
import torch.nn as nn
from torch.nn import init
import functools
import numpy as np
from . import resnet
def get_model(arch):
if hasattr(resnet, arch):
network = getattr(resnet, arch)
return network(pretrained=True, num_classes=512)
else:
raise ValueError("Invalid Backbone ... | null |
180,915 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x... | 3x3 convolution with padding |
180,916 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.o... | null |
180,917 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.o... | Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
180,918 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.o... | Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
180,919 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.o... | Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
180,920 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.o... | Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
180,921 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | null |
180,922 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Convert the seconds to human readable string with days, hours, minutes and seconds. |
180,923 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Convert the seconds to human readable string with days, hours, minutes and seconds. |
180,924 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Ask the user the question until the user inputs a valid answer. |
180,925 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Calculate the product of the tuple elements. |
180,926 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes. |
180,927 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | null |
180,928 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Finds the python class with the given name and constructs it with the given arguments. |
180,929 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Get the directory path of the module containing the given object name. |
180,930 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Return the fully-qualified name of a top-level function. |
180,931 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | List all files recursively in a given directory while ignoring given file and directory names. Returns list of tuples containing both absolute and relative paths. |
180,932 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Takes in a list of tuples of (src, dst) paths and copies files. Will create all necessary directories. |
180,933 | import ctypes
import fnmatch
import importlib
import inspect
import os
import sys
import types
import io
import pickle
import re
import requests
import html
import hashlib
import glob
import tempfile
import urllib
import urllib.request
import uuid
from typing import Any, List, Tuple, Union, Optional
from distutils.util... | Download the given URL and return a binary-mode file object to access the data. |
180,934 | import os
import re
import json
from pathlib import Path
from typing import Union
from glob import glob
import torch
import click
import dnnlib
from training import training_loop
from metrics import metric_main
from torch_utils import distributed as dist
from torch_utils import custom_ops
def parse_comma_separated_lis... | null |
180,935 | import os
import re
import json
from pathlib import Path
from typing import Union
from glob import glob
import torch
import click
import dnnlib
from training import training_loop
from metrics import metric_main
from torch_utils import distributed as dist
from torch_utils import custom_ops
def is_power_of_two(n: int) ->... | null |
180,936 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
_metric_dict = dict()
def register_metric(fn: C... | null |
180,937 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
def fid50k_full(opts):
opts.dataset_kwargs.... | null |
180,938 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
def fid10k_full(opts):
opts.dataset_kwargs.... | null |
180,939 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
def cs10k(opts):
assert opts.G.c_dim > 1, '... | null |
180,940 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
def pr50k3_full(opts):
opts.dataset_kwargs.... | null |
180,941 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
def get_coco_path(original_path: str) -> str:
... | null |
180,942 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
def get_coco_path(original_path: str) -> str:
... | null |
180,943 | import os
import time
import json
from pathlib import Path
from typing import Optional, Callable
import torch
import dnnlib
from metrics import metric_utils
from metrics import frechet_inception_distance
from metrics import precision_recall
from metrics import clip_score
def get_coco_path(original_path: str) -> str:
... | null |
180,944 | import os
import json
import copy
import torch
import dill
import click
import dnnlib
from metrics import metric_main
from metrics import metric_utils
from torch_utils import misc
from torch_utils import custom_ops
from torch_utils import distributed as dist
from torch_utils.ops import conv2d_gradfix
def parse_comma_s... | null |
180,945 | import os
import json
import copy
import torch
import dill
import click
import dnnlib
from metrics import metric_main
from metrics import metric_utils
from torch_utils import misc
from torch_utils import custom_ops
from torch_utils import distributed as dist
from torch_utils.ops import conv2d_gradfix
The provided code... | Calculate quality metrics for previous training run or pretrained network pickle. Examples: \b # Previous training run: look up options automatically, save result to JSONL file. python calc_metrics.py --metrics=cs10k,fid50k_full \\ --network=~/training-runs/00000-mydataset@512-custom-gpus1-b4-bgpu2/network-snapshot-000... |
180,946 | import os
import re
from typing import List, Optional, Union
import PIL.Image
import numpy as np
import torch
import click
import dill
from tqdm import tqdm
import dnnlib
The provided code snippet includes necessary dependencies for implementing the `parse_range` function. Write a Python function `def parse_range(s: U... | Parse a comma separated list of numbers or ranges and return a list of ints. Example: '1,2,5-10' returns [1, 2, 5, 6, 7] |
180,947 | import os
import re
from typing import List, Optional, Union
import PIL.Image
import numpy as np
import torch
import click
import dill
from tqdm import tqdm
import dnnlib
The provided code snippet includes necessary dependencies for implementing the `parse_vec2` function. Write a Python function `def parse_vec2(s: Uni... | Parse a floating point 2-vector of syntax 'a,b'. Example: '0,1' returns (0,1) |
180,948 | import os
import re
from typing import List, Optional, Union
import PIL.Image
import numpy as np
import torch
import click
import dill
from tqdm import tqdm
import dnnlib
def make_transform(translate: tuple[float,float], angle: float) -> np.ndarray:
def generate_images(
network_pkl: str,
seeds: List[int],
... | null |
180,949 | import numpy as np
import torch
import torch.nn.functional as F
AUGMENT_FNS = {
'color': [rand_brightness, rand_saturation, rand_contrast],
'translation': [rand_translation],
'resize': [rand_resize],
'cutout': [rand_cutout],
}
def DiffAugment(x: torch.Tensor, policy: str = '', channels_first: bool = Tr... | null |
180,950 | import numpy as np
import torch
import torch.nn.functional as F
def rand_brightness(x: torch.Tensor) -> torch.Tensor:
x = x + (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5)
return x | null |
180,951 | import numpy as np
import torch
import torch.nn.functional as F
def rand_saturation(x: torch.Tensor) -> torch.Tensor:
x_mean = x.mean(dim=1, keepdim=True)
x = (x - x_mean) * (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) * 2) + x_mean
return x | null |
180,952 | import numpy as np
import torch
import torch.nn.functional as F
def rand_contrast(x: torch.Tensor) -> torch.Tensor:
x_mean = x.mean(dim=[1, 2, 3], keepdim=True)
x = (x - x_mean) * (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) + 0.5) + x_mean
return x | null |
180,953 | import numpy as np
import torch
import torch.nn.functional as F
def rand_translation(x: torch.Tensor, ratio: float = 0.125) -> torch.Tensor:
shift_x, shift_y = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
translation_x = torch.randint(-shift_x, shift_x + 1, size=[x.size(0), 1, 1], device=x.device... | null |
180,954 | import numpy as np
import torch
import torch.nn.functional as F
def rand_cutout(x: torch.Tensor, ratio: float = 0.2) -> torch.Tensor:
cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
offset_x = torch.randint(0, x.size(2) + (1 - cutout_size[0] % 2), size=[x.size(0), 1, 1], device=x.devic... | null |
180,955 | import numpy as np
import torch
import torch.nn.functional as F
def rand_resize(x: torch.Tensor, min_ratio: float = 0.8, max_ratio: float = 1.2) -> torch.Tensor:
resize_ratio = np.random.rand()*(max_ratio-min_ratio) + min_ratio
resized_img = F.interpolate(x, size=int(resize_ratio*x.shape[3]), mode='bilinear')
... | null |
180,956 | import os
import math
import time
import copy
import json
import PIL.Image
from typing import Union, Iterator, Optional, Any
import dill
import psutil
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.utils.tensorboard as tensorboard
import dnnlib
from torch_utils import... | null |
180,957 | import types
import math
from typing import Callable
import torch
import torch.nn as nn
import torch.nn.functional as F
def forward_flex(self, x: torch.Tensor) -> torch.Tensor:
# patch proj and dynamically resize
B, C, H, W = x.size()
x = self.patch_embed.proj(x).flatten(2).transpose(1, 2)
pos_embed = s... | null |
180,958 | import types
import math
from typing import Callable
import torch
import torch.nn as nn
import torch.nn.functional as F
class AddReadout(nn.Module):
def __init__(self, start_index: bool = 1):
def forward(self, x: torch.Tensor) -> torch.Tensor:
class Transpose(nn.Module):
def __init__(self, dim0: int, dim... | null |
180,959 | from typing import Union, Any, Optional
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch_utils import misc
from torch_utils.ops import upfirdn2d, conv2d_resample, bias_act, fma
from networks.shared import FullyConnectedLayer, MLP
f... | null |
180,960 | from typing import Union, Any, Optional
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch_utils import misc
from torch_utils.ops import upfirdn2d, conv2d_resample, bias_act, fma
from networks.shared import FullyConnectedLayer, MLP
f... | null |
180,961 | from typing import Union, Any, Optional
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch_utils import misc
from torch_utils.ops import upfirdn2d, conv2d_resample, bias_act, fma
from networks.shared import FullyConnectedLayer, MLP
f... | null |
180,962 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.spectral_norm import SpectralNorm
from torchvision.transforms import RandomCrop, Normalize
import timm
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from torch_utils import misc
from networks.sh... | null |
180,964 | import sys
import dill
import io
import inspect
import copy
import uuid
import types
import dnnlib
_import_hooks = []
The provided code snippet includes necessary dependencies for implementing the `import_hook` function. Write a Python function `def import_hook(hook)` to solve the following problem:
r"""Register... | r"""Register an import hook that is called whenever a persistent object is being unpickled. A typical use case is to patch the pickled source code to avoid errors and inconsistencies when the API of some imported module has changed. The hook should have the following signature: hook(meta) -> modified meta `meta` is an ... |
180,965 | import torch
from pkg_resources import parse_version
def _should_use_custom_op():
class _GridSample2dForward(torch.autograd.Function):
def forward(ctx, input, grid):
def backward(ctx, grad_output):
def grid_sample(input, grid):
if _should_use_custom_op():
return _GridSample2dForward.apply(input, ... | null |
180,972 | import re
import contextlib
import numpy as np
import torch
import warnings
import dnnlib
_constant_cache = dict()
def constant(value, shape=None, dtype=None, device=None, memory_format=None):
value = np.asarray(value)
if shape is not None:
shape = tuple(shape)
if dtype is None:
dtype = tor... | null |
180,974 | import re
import contextlib
import numpy as np
import torch
import warnings
import dnnlib
def get_children(model: torch.nn.Module):
children = list(model.children())
flatt_children = []
if children == []:
return model
else:
for child in children:
try:
flatt_chi... | null |
180,976 | import os
import torch
from . import training_stats
def should_stop():
return False | null |
180,977 | import os
import torch
from . import training_stats
def update_progress(cur, total):
_ = cur, total | null |
180,978 | import functools
import PIL.Image
import gzip
import io
import json
import os
import pickle
import re
import sys
import tarfile
import zipfile
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import requests
import numpy as np
import click
from tqdm import tqdm
The provided code snippet inc... | Parse a 'M,N' or 'MxN' integer tuple. Example: '4x2' returns (4,2) |
180,979 | import functools
import PIL.Image
import gzip
import io
import json
import os
import pickle
import re
import sys
import tarfile
import zipfile
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import requests
import numpy as np
import click
from tqdm import tqdm
def make_transform(
trans... | null |
180,980 | import functools
import PIL.Image
import gzip
import io
import json
import os
import pickle
import re
import sys
import tarfile
import zipfile
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import requests
import numpy as np
import click
from tqdm import tqdm
def file_ext(name: Union[str, ... | null |
180,981 | import functools
import PIL.Image
import gzip
import io
import json
import os
import pickle
import re
import sys
import tarfile
import zipfile
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import requests
import numpy as np
import click
from tqdm import tqdm
def file_ext(name: Union[str, ... | null |
180,982 | import tensorflow as tf
from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
import cv2
from core.yolov4 import YOLOv4, YOLOv3, YOLOv3_tiny, decode
import core.utils as utils
import os
from core.config import cfg
def representative_data_gen():
fimage = open(FLAGS.dataset).read().split(... | null |
180,983 | import tensorflow as tf
from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
import cv2
from core.yolov4 import YOLOv4, YOLOv3, YOLOv3_tiny, decode
import core.utils as utils
import os
from core.config import cfg
def demo():
interpreter = tf.lite.Interpreter(model_path=FLAGS.output)
... | null |
180,984 | import sys
import os
import glob
import argparse
The provided code snippet includes necessary dependencies for implementing the `query_yes_no` function. Write a Python function `def query_yes_no(question, default="yes", bypass=False)` to solve the following problem:
Ask a yes/no question via raw_input() and return the... | Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or Fa... |
180,985 | import sys
import os
import glob
import argparse
with open('../../data/classes/coco.names') as f:
for line in f:
current_class_name = line.rstrip("\n")
new_class_name = line.replace(' ', args.delimiter).rstrip("\n")
if current_class_name == new_class_name:
continue
y_n_me... | null |
180,986 | import sys
import os
import glob
os.chdir(path_to_gt)
os.chdir(path_to_pred)
print('total ground-truth files:', len(gt_files))
print('total predicted files:', len(pred_files))
print()
print('total intersected files:', len(intersection))
print("Intersection completed!")
def backup(src_folder, backup_files, backup_folde... | null |
180,987 | import glob
import json
import os
import shutil
import operator
import sys
import argparse
from absl import app, flags, logging
from absl.flags import FLAGS
def error(msg):
print(msg)
sys.exit(0) | null |
180,988 | import glob
import json
import os
import shutil
import operator
import sys
import argparse
from absl import app, flags, logging
from absl.flags import FLAGS
def is_float_between_0_and_1(value):
try:
val = float(value)
if val > 0.0 and val < 1.0:
return True
else:
return False
except ValueEr... | null |
180,989 | import glob
import json
import os
import shutil
import operator
import sys
import argparse
from absl import app, flags, logging
from absl.flags import FLAGS
if len(ground_truth_files_list) == 0:
error("Error: No ground-truth files found!")
The provided code snippet includes necessary dependencies for implementing th... | --- Official matlab code VOC2012--- mrec=[0 ; rec ; 1]; mpre=[0 ; prec ; 0]; for i=numel(mpre)-1:-1:1 mpre(i)=max(mpre(i),mpre(i+1)); end i=find(mrec(2:end)~=mrec(1:end-1))+1; ap=sum((mrec(i)-mrec(i-1)).*mpre(i)); |
180,990 | import glob
import json
import os
import shutil
import operator
import sys
import argparse
from absl import app, flags, logging
from absl.flags import FLAGS
with open(results_files_path + "/results.txt", 'w') as results_file:
results_file.write("# AP and precision/recall per class\n")
count_true_positives = {}
fo... | null |
180,991 | import glob
import json
import os
import shutil
import operator
import sys
import argparse
from absl import app, flags, logging
from absl.flags import FLAGS
def draw_text_in_image(img, text, pos, color, line_width):
font = cv2.FONT_HERSHEY_PLAIN
fontScale = 1
lineType = 1
bottomLeftCornerOfText = pos
cv2.put... | null |
180,992 | import glob
import json
import os
import shutil
import operator
import sys
import argparse
from absl import app, flags, logging
from absl.flags import FLAGS
def adjust_axes(r, t, fig, axes):
# get text width for re-scaling
bb = t.get_window_extent(renderer=r)
text_width_inches = bb.width / fig.dpi
# get axis wi... | Re-scale height accordingly |
180,993 | import cv2
import random
import colorsys
import numpy as np
import tensorflow as tf
from core.config import cfg
def load_freeze_layer(model='yolov4', tiny=False):
if tiny:
if model == 'yolov3':
freeze_layouts = ['conv2d_9', 'conv2d_12']
else:
freeze_layouts = ['conv2d_17', '... | null |
180,994 | import cv2
import random
import colorsys
import numpy as np
import tensorflow as tf
from core.config import cfg
def read_class_names(class_file_name):
names = {}
with open(class_file_name, 'r') as data:
for ID, name in enumerate(data):
names[ID] = name.strip('\n')
return names
cfg ... | null |
180,995 | import cv2
import random
import colorsys
import numpy as np
import tensorflow as tf
from core.config import cfg
The provided code snippet includes necessary dependencies for implementing the `bbox_ciou` function. Write a Python function `def bbox_ciou(bboxes1, bboxes2)` to solve the following problem:
Complete IoU @pa... | Complete IoU @param bboxes1: (a, b, ..., 4) @param bboxes2: (A, B, ..., 4) x:X is 1:n or n:n or n:1 @return (max(a,A), max(b,B), ...) ex) (4,):(3,4) -> (3,) (2,1,4):(2,3,4) -> (2,3) |
180,996 | import cv2
import random
import colorsys
import numpy as np
import tensorflow as tf
from core.config import cfg
def bbox_iou(bboxes1, bboxes2):
"""
x:X is 1:n or n:n or n:1
ex) (4,):(3,4) -> (3,)
(2,1,4):(2,3,4) -> (2,3)
"""
bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]
bboxes2_ar... | :param bboxes: (xmin, ymin, xmax, ymax, score, class) Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf https://github.com/bharatsingh430/soft-nms |
180,997 | import cv2
import random
import colorsys
import numpy as np
import tensorflow as tf
from core.config import cfg
def freeze_all(model, frozen=True):
model.trainable = not frozen
if isinstance(model, tf.keras.Model):
for l in model.layers:
freeze_all(l, frozen) | null |
180,998 | import cv2
import random
import colorsys
import numpy as np
import tensorflow as tf
from core.config import cfg
def unfreeze_all(model, frozen=False):
model.trainable = not frozen
if isinstance(model, tf.keras.Model):
for l in model.layers:
unfreeze_all(l, frozen) | null |
180,999 | import numpy as np
import tensorflow as tf
import core.utils as utils
import core.common as common
import core.backbone as backbone
from core.config import cfg
def decode_train(conv_output, output_size, NUM_CLASS, STRIDES, ANCHORS, i=0, XYSCALE=[1, 1, 1]):
conv_output = tf.reshape(conv_output,
... | null |
181,000 | import numpy as np
import tensorflow as tf
import core.utils as utils
import core.common as common
import core.backbone as backbone
from core.config import cfg
def compute_loss(pred, conv, label, bboxes, STRIDES, NUM_CLASS, IOU_LOSS_THRESH, i=0):
conv_shape = tf.shape(conv)
batch_size = conv_shape[0]
out... | null |
181,001 | import tensorflow as tf
from absl import app, flags, logging
from absl.flags import FLAGS
from core.yolov4 import YOLO, decode, filter_boxes
import core.utils as utils
from core.config import cfg
def YOLO(input_layer, NUM_CLASS, model='yolov4', is_tiny=False):
if is_tiny:
if model == 'yolov4':
... | null |
181,002 | import sys
import os
from absl import app, flags
from absl.flags import FLAGS
from lxml import etree
def convert_annotation(list_txt, output_path, image_dir, anno_dir, class_names):
IMAGE_EXT = '.jpg'
ANNO_EXT = '.xml'
with open(list_txt, 'r') as f, open(output_path, 'w') as wf:
while True:
... | null |
181,003 | import sys
import os
from absl import app, flags
from absl.flags import FLAGS
from lxml import etree
def make_names(anno_dir, output):
labels_dict = {}
anno_list = os.listdir(anno_dir)
for anno_file in anno_list:
p = os.path.join(anno_dir, anno_file)
# Get annotation.
roo... | null |
181,004 | from absl import app, flags, logging
import os
import pickle
from os import listdir
from os.path import isfile, join
from absl.flags import FLAGS
import cv2
def convert_annotation(output, data, data_type = "val"):
class_names = [c.strip() for c in open(FLAGS.classes).readlines()]
replace_dict = {"couch": "sofa... | null |
181,005 | import os
import time
def gdrive_download(id='1HaXkef9z6y5l4vUnCYgdmEAj61c6bfWO', name='coco.zip'):
# https://gist.github.com/tanaikech/f0f2d122e05bf5f971611258c22c110f
# Downloads a file from Google Drive, accepting presented query
# from utils.google_utils import *; gdrive_download()
t = time.time()
... | null |
181,006 | import os
import argparse
import xml.etree.ElementTree as ET
def convert_voc_annotation(data_path, data_type, anno_path, use_difficult_bbox=True):
classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',
'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse',
'motorbi... | null |
181,007 | from absl import app, flags, logging
from absl.flags import FLAGS
import tensorflow as tf
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
import numpy as np
import cv2
from tensorflow.python.compiler.tensorrt import trt_convert as trt
import core.utils as utils
from... | null |
181,008 | from backtesting.test import EURUSD, SMA
upper, lower = BBANDS(data, 20, 2)
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from backtesting import Backtest, Strategy
The provided code snippet includes necessary dependencies... | Bollinger bands indicator |
181,009 | from backtesting.test import EURUSD, SMA
import numpy as np
def get_X(data):
"""Return model design matrix X"""
return data.filter(like='X').values
def get_y(data):
"""Return dependent variable y"""
y = data.Close.pct_change(48).shift(-48) # Returns after roughly two days
y[y.between(-.004, .004)] ... | Return (X, y) cleaned of NaN values |
181,010 | from backtesting.test import GOOG
import pandas as pd
from backtesting import Strategy
from backtesting.lib import crossover
from backtesting import Backtest
The provided code snippet includes necessary dependencies for implementing the `SMA` function. Write a Python function `def SMA(values, n)` to solve the followin... | Return simple moving average of `values`, at each step taking into account `n` previous values. |
181,011 | import pandas as pd
from backtesting import Strategy, Backtest
from backtesting.lib import resample_apply
from backtesting.test import GOOG
The provided code snippet includes necessary dependencies for implementing the `SMA` function. Write a Python function `def SMA(array, n)` to solve the following problem:
Simple m... | Simple moving average |
181,012 | import pandas as pd
from backtesting import Strategy, Backtest
from backtesting.lib import resample_apply
from backtesting.test import GOOG
The provided code snippet includes necessary dependencies for implementing the `RSI` function. Write a Python function `def RSI(array, n)` to solve the following problem:
Relative... | Relative strength index |
181,013 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 保存cookies |
181,014 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 读取保存的cookies |
181,015 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 登录大麦网 :param login_id: :param login_password: :param login_type: 选择哪种方式进行登录 :return: |
181,016 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 获取请求大麦API所必须的一些参数, 可能大麦网js代码更新后需要修改此函数内的代码以重新获得参数信息 |
181,017 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 获取座位信息的必备参数 |
181,018 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 获取 standId, 用于获取所有座位信息 |
181,019 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 得到请求所有座位信息的api地址 |
181,020 | import re
import os
import json
import execjs
import pickle
import platform
import requests
from datetime import datetime
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support... | 获取可用的座位信息 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.