id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
165,766 | from typing import Optional, List, Dict, Any
import base64
import zlib
import json
from pydantic import BaseModel, Field
from pygwalker.utils.encode import DataFrameEncoder
from pygwalker.utils.display import display_html
from pygwalker.utils.randoms import generate_hash_code
from pygwalker.services.render import jinja... | Render html for previewing gwalker(use purerenderer mode of graphic-wlaker, not png preview) |
165,767 | from typing import Optional
import streamlit as st
import streamlit.components.v1 as components
from pygwalker.utils.randoms import rand_str
def render_modal(html: str, key: Optional[str] = None):
"""
show a modal dialog.
css style and hack way reference: https://github.com/teamtv/streamlit_modal
"""
... | render explore modal button |
165,768 | import os
import json
from typing import List, Optional, Dict
from functools import lru_cache
from pygwalker.utils.randoms import generate_hash_code
from appdirs import user_config_dir
config_items = [privacy_item, kanati_token_item]
def get_config_params_help() -> str:
help_str = ""
help_str += "Available con... | null |
165,769 | import os
import json
from typing import List, Optional, Dict
from functools import lru_cache
from pygwalker.utils.randoms import generate_hash_code
from appdirs import user_config_dir
DEFAULT_CONFIG = {
"privacy": "events",
"kanaries_token": "",
}
CONFIG_PATH = os.path.join(APP_DIR, "config.json")
def _read_an... | Get configuration. Args: key (str, optional): Defaults to None. default (any, optional): Defaults to None. Returns: value, default_value: value of the key |
165,770 | import os
import json
from typing import List, Optional, Dict
from functools import lru_cache
from pygwalker.utils.randoms import generate_hash_code
from appdirs import user_config_dir
DEFAULT_CONFIG = {
"privacy": "events",
"kanaries_token": "",
}
CONFIG_PATH = os.path.join(APP_DIR, "config.json")
def _read_an... | null |
165,771 | import os
import json
import base64
from typing import Dict, List, Any
from jinja2 import Environment, PackageLoader
from pygwalker._constants import ROOT_DIR
from pygwalker.utils.encode import DataFrameEncoder
from pygwalker.utils.estimate_tools import estimate_average_data_size
def estimate_average_data_size(datas: ... | null |
165,772 | import os
import json
import base64
from typing import Dict, List, Any
from jinja2 import Environment, PackageLoader
from pygwalker._constants import ROOT_DIR
from pygwalker.utils.encode import DataFrameEncoder
from pygwalker.utils.estimate_tools import estimate_average_data_size
jinja_env = Environment(
loader=Pac... | null |
165,773 | import os
import json
import base64
from typing import Dict, List, Any
from jinja2 import Environment, PackageLoader
from pygwalker._constants import ROOT_DIR
from pygwalker.utils.encode import DataFrameEncoder
from pygwalker.utils.estimate_tools import estimate_average_data_size
jinja_env = Environment(
loader=Pac... | null |
165,774 | from typing import Dict, Any, Coroutine
from urllib import request
from threading import Thread
import asyncio
import logging
import sys
import json
from .config import get_local_user_id
from pygwalker import __version__
from pygwalker.services.global_var import GlobalVarManager
def _check_update() -> Dict[str, Any]:
... | null |
165,775 | from typing import List, Dict, Any, Optional
from datetime import datetime
from urllib.parse import urlencode
from typing_extensions import Literal
import logging
import io
import json
import hashlib
import requests
from .global_var import GlobalVarManager
from pygwalker.services.data_parsers import BaseDataParser
from... | null |
165,776 | from typing import List, Dict, Any, Optional
from datetime import datetime
from urllib.parse import urlencode
from typing_extensions import Literal
import logging
import io
import json
import hashlib
import requests
from .global_var import GlobalVarManager
from pygwalker.services.data_parsers import BaseDataParser
from... | null |
165,777 | from typing import List, Dict, Any, Optional
from datetime import datetime
from urllib.parse import urlencode
from typing_extensions import Literal
import logging
import io
import json
import hashlib
import requests
from .global_var import GlobalVarManager
from pygwalker.services.data_parsers import BaseDataParser
from... | null |
165,778 | from functools import lru_cache
from pygwalker.services.global_var import GlobalVarManager
from pygwalker.utils.display import display_html
def display_html(
html: Union[str, HTML, ipywidgets.Widget],
*,
slot_id: str = None
):
"""Judge the presentation method to be used based on the context
Args:
... | Whether has set kanaries api key. |
165,779 | import json
import gc
from fastapi import FastAPI
from starlette.routing import Route
from starlette.responses import JSONResponse, Response
from starlette.requests import Request
from pygwalker.utils.encode import DataFrameEncoder
from .base import BaseCommunication
gradio_comm_map = {}
class DataFrameEncoder(json.JS... | null |
165,780 | import json
import gc
from fastapi import FastAPI
from starlette.routing import Route
from starlette.responses import JSONResponse, Response
from starlette.requests import Request
from pygwalker.utils.encode import DataFrameEncoder
from .base import BaseCommunication
PYGWALKER_ROUTE = Route(
"/_pygwalker/comm/{gid}... | null |
165,781 | from typing import Dict, List, Any
def get_sql_from_payload(
table_name: str,
payload: Dict[str, Any],
field_meta: List[Dict[str, str]] = None
) -> str:
try:
from gw_dsl_parser import get_sql_from_payload as __get_sql_from_payload
except ImportError as exc:
raise ImportError("gw_dsl... | null |
165,782 | from sqlglot.dialects.duckdb import DuckDB as DuckdbDialect
from sqlglot.dialects.postgres import Postgres as PostgresDialect
from sqlglot import exp
from sqlglot.helper import seq_get
def _postgres_round_generator(e: exp.Round) -> str:
e = e.copy()
e.set("this", exp.Cast(this=e.this.pop(), to="numeric"))
... | null |
165,783 | import logging
def init_logging():
logger = logging.getLogger("pygwalker")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter("%(levelname)s: %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler) | null |
165,784 | from pygwalker.api.streamlit import StreamlitRenderer
import pandas as pd
import streamlit as st
class StreamlitRenderer:
"""Streamlit Renderer"""
def __init__(
self,
dataset: Union[DataFrame, Connector],
gid: Union[int, str] = None,
*,
field_specs: Optional[Dict[str, Fi... | null |
165,785 | from typing import Dict, Any, Tuple, List
import sqlglot.expressions as exp
import sqlglot
METRICS_DEFINITIONS = {
"pv": {
"name": "pv",
"description": "Page Views",
"fields": ["date"],
"dimensions": ["date"],
"params": [],
"depends": [],
"sql": """
... | get help text |
165,786 | from typing import List, Dict, Any, Union, Optional
from decimal import Decimal
import json
import pandas as pd
from pygwalker._typing import DataFrame
from pygwalker.data_parsers.database_parser import Connector
from pygwalker.services.data_parsers import get_parser
from pygwalker.api.html import to_chart_html
from .c... | Example: get 1 day retention datas ```python from pygwalker_tools.metrics import get_metrics_datas datas = get_metrics_datas( dataset=dataset, metrics_name="retention", field_map={ "date": "your_date_field", "user_id": "your_user_id_field", "user_signup_date": "your_user_signup_date_field" }, params={ "time_unit": "day... |
165,787 | from typing import Tuple
import argparse
from pygwalker.services.config import (
reset_all_config,
set_config,
get_config_params_help,
reset_config,
get_all_config_str,
CONFIG_PATH
)
from pygwalker.services.kanaries_cli_login import kanaries_login
def set_config(new_config: Dict[str, str]):
... | null |
165,788 | from typing import Tuple
import argparse
from pygwalker.services.config import (
reset_all_config,
set_config,
get_config_params_help,
reset_config,
get_all_config_str,
CONFIG_PATH
)
from pygwalker.services.kanaries_cli_login import kanaries_login
def reset_config(keys: List[str]):
"""Unset... | null |
165,789 | from typing import Tuple
import argparse
from pygwalker.services.config import (
reset_all_config,
set_config,
get_config_params_help,
reset_config,
get_all_config_str,
CONFIG_PATH
)
from pygwalker.services.kanaries_cli_login import kanaries_login
def reset_all_config():
"""Unset all user c... | null |
165,790 | from typing import Tuple
import argparse
from pygwalker.services.config import (
reset_all_config,
set_config,
get_config_params_help,
reset_config,
get_all_config_str,
CONFIG_PATH
)
from pygwalker.services.kanaries_cli_login import kanaries_login
def get_all_config_str() -> str:
config = _... | null |
165,791 | import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join
classes = []
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2... | null |
165,792 | def box_iou_for_nms(box1, box2, GIoU=False, DIoU=False, CIoU=False, SIoU=False, EIou=False, eps=1e-7):
# Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
w1, h1 = b1_x2 - b1_x1, (b1_y2 - b1_y1).c... | null |
165,793 | import numpy as np
import torch, math
class WIoU_Scale:
''' monotonous: {
None: origin v1
True: monotonic FM v2
False: non-monotonic FM v3
}
momentum: The momentum of running mean'''
iou_mean = 1.
monotonous = False
_momentum = 1 - 0.5 ** (1 / 7000)
... | null |
165,794 | class IDetect_Decoupled(nn.Module):
def __init__(self, nc=80, anchors=(), ch=()):
def forward(self, x):
def fuseforward(self, x):
def fuse(self):
def _make_grid(nx=20, ny=20):
def convert(self, z):
if isinstance(m, IDetect_Decoupled):
s = 256 # 2x min stride
m.stride = torch.tenso... | null |
165,795 |
def __call__(self, p, targets): # predictions, targets
lcls = torch.zeros(1, device=self.device) # class loss
lbox = torch.zeros(1, device=self.device) # box loss
lobj = torch.zeros(1, device=self.device) # object loss
tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
#... | null |
165,796 | import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `conv_bn` function. Write a Python function `def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1)` to solve the following problem:
Basic cell for r... | Basic cell for rep-style block, including conv and bn |
165,797 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Swish(nn.Module):
def __init__(self, inplace=True):
super(Swish, self).__init__()
self.inplace = inplace
def forward(self, x):
if self.inplace:
x.mul_(F.sigmoid(x))
return x
else:
... | null |
165,798 | import torch
import torch.nn as nn
import torch.nn.functional as F
def get_norm(name, out_channels, inplace=True):
if name == 'bn':
module = nn.BatchNorm2d(out_channels)
else:
raise NotImplementedError
return module | null |
165,799 |
The provided code snippet includes necessary dependencies for implementing the `wasserstein_loss` function. Write a Python function `def wasserstein_loss(pred, target, eps=1e-7, constant=12.8)` to solve the following problem:
r"""`Implementation of paper `Enhancing Geometric Factors into Model Learning and Inference ... | r"""`Implementation of paper `Enhancing Geometric Factors into Model Learning and Inference for Object Detection and Instance Segmentation <https://arxiv.org/abs/2005.03572>`_. Code is modified from https://github.com/Zzh-tju/CIoU. Args: pred (Tensor): Predicted bboxes of format (x_center, y_center, w, h), shape (n, 4)... |
165,800 | def box_iou_for_nms(box1, box2, GIoU=False, DIoU=False, CIoU=False, SIoU=False, EIou=False, eps=1e-7): # IoU
def soft_nms(bboxes, scores, iou_thresh=0.5,sigma=0.5,score_threshold=0.25):
order = scores.argsort(descending=True).to(bboxes.device)
keep = []
while order.numel() > 1:
if order.numel... | null |
165,802 | class Decoupled_Detect(nn.Module):
# YOLOv5 Detect head for detection models
stride = None # strides computed during build
dynamic = False # force grid reconstruction
export = False # export mode
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
super().__init... | null |
165,803 | import torch.nn.functional as F
def transI_fusebn(kernel, bn):
gamma = bn.weight
std = (bn.running_var + bn.eps).sqrt()
return kernel * ((gamma / std).reshape(-1, 1, 1, 1)), bn.bias - bn.running_mean * gamma / std | null |
165,804 | import torch.nn.functional as F
def transII_addbranch(kernels, biases):
return sum(kernels), sum(biases) | null |
165,805 | import torch.nn.functional as F
def transIV_depthconcat(kernels, biases):
return torch.cat(kernels, dim=0), torch.cat(biases)
def transIII_1x1_kxk(k1, b1, k2, b2, groups):
if groups == 1:
k = F.conv2d(k2, k1.permute(1, 0, 2, 3)) #
b_hat = (k2 * b1.reshape(1, -1, 1, 1)).sum((1, 2, 3))
e... | null |
165,806 | import torch.nn.functional as F
def transV_avg(channels, kernel_size, groups):
input_dim = channels // groups
k = torch.zeros((channels, input_dim, kernel_size, kernel_size))
k[np.arange(channels), np.tile(np.arange(input_dim), groups), :, :] = 1.0 / kernel_size ** 2
return k | null |
165,807 | import torch.nn.functional as F
def transVI_multiscale(kernel, target_kernel_size):
H_pixels_to_pad = (target_kernel_size - kernel.size(2)) // 2
W_pixels_to_pad = (target_kernel_size - kernel.size(3)) // 2
return F.pad(kernel, [H_pixels_to_pad, H_pixels_to_pad, W_pixels_to_pad, W_pixels_to_pad]) | null |
165,808 | import torch.nn.functional as F
def conv_bn(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1,
padding_mode='zeros'):
conv_layer = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, padd... | null |
165,809 | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_activation_layer, build_norm_layer
from mmcv.ops.modulated_deform_conv import ModulatedDeformConv2d
from mmengine.model import constant_init, normal_init
def _make_divisible(v, divisor, min_value=None):
if min_value is No... | null |
165,816 | import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `conv_bn` function. Write a Python function `def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1, bias=False)` to solve the following problem:
Basic cell for rep-style block, includi... | Basic cell for rep-style block, including conv and bn |
165,817 | import torch.nn.functional as F
def onnx_AdaptiveAvgPool2d(x, output_size):
stride_size = np.floor(np.array(x.shape[-2:]) / output_size).astype(np.int32)
kernel_size = np.array(x.shape[-2:]) - (output_size - 1) * stride_size
avg = nn.AvgPool2d(kernel_size=list(kernel_size), stride=list(stride_size))
x =... | null |
165,818 | import torch.nn.functional as F
def get_shape(tensor):
shape = tensor.shape
if torch.onnx.is_in_onnx_export():
shape = [i.cpu().numpy() for i in shape]
return shape | null |
165,819 | import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `drop_path` function. Write a Python function `def drop_path(x, drop_prob: float = 0., training: bool = False)` to solve the following problem:
Drop paths (Stochastic Depth) per sample (when applied in main p... | Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I 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.com/... |
165,820 | from einops import rearrange
class TSCODE_Detect(nn.Module):
# YOLOv5 Detect head for detection models
stride = None # strides computed during build
dynamic = False # force grid reconstruction
export = False # export mode
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection la... | null |
165,821 | import numpy as np
import torch, math
class WIoU_Scale:
def __init__(self, iou):
def _update(cls, self):
def _scaled_loss(cls, self, gamma=1.9, delta=3):
def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, SIoU=False, EIoU=False, WIoU=False, Focal=False, alpha=1, gamma=0.5, scale... | null |
165,822 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import warnings
from torch import nn
import torch.nn.functional as F
from torch.nn.init import xavier_uniform_, constant_
from ..functions import DCNv3Function, dcnv3_core_pytorch
def autopad(k, p=None, d=1): ... | null |
165,823 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import warnings
from torch import nn
import torch.nn.functional as F
from torch.nn.init import xavier_uniform_, constant_
from ..functions import DCNv3Function, dcnv3_core_pytorch
def _is_power_of_2(n):
if ... | null |
165,826 | import argparse
import contextlib
import json
import os
import platform
import re
import subprocess
import sys
import time
import warnings
from pathlib import Path
import pandas as pd
import torch
from torch.utils.mobile_optimizer import optimize_for_mobile
from models.experimental import attempt_load
from models.yolo ... | null |
165,827 | import argparse
import platform
import sys
import time
from pathlib import Path
import pandas as pd
ROOT = FILE.parents[0]
import export
from models.experimental import attempt_load
from models.yolo import SegmentationModel
from segment.val import run as val_seg
from utils import notebook_init
from utils.general impor... | null |
165,828 | import argparse
import os
import platform
import sys
from pathlib import Path
import torch
ROOT = FILE.parents[0]
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))
from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.gene... | null |
165,829 | import argparse
import os
import platform
import sys
from pathlib import Path
import torch
ROOT = FILE.parents[0]
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))
from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.gene... | null |
165,830 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,831 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,832 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,833 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,834 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,835 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,836 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
# YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
return _create('yolov5n6', pretrain... | null |
165,837 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,838 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,839 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
"""Creates or loads a YOLOv5 model
Arguments:
name (str): model name 'yolov5s' or path 'path/to/best.pt'
pretrained (bool): load pretrained weights into the model
channels ... | null |
165,840 | import torch
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
# YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
return _create('yolov5x6', pretra... | null |
165,841 | import argparse
import contextlib
import os
import platform
import sys
from copy import deepcopy
from pathlib import Path
from models.common import *
from models.experimental import *
from utils.autoanchor import check_anchor_order
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
... | null |
165,842 | import ast
import contextlib
import json
import math
import platform
import warnings
import zipfile
from collections import OrderedDict, namedtuple
from copy import copy
from pathlib import Path
from urllib.parse import urlparse
import cv2
import numpy as np
import pandas as pd
import requests
import torch
import torch... | null |
165,843 | import argparse
import sys
from copy import deepcopy
from pathlib import Path
import numpy as np
import tensorflow as tf
import torch
import torch.nn as nn
from tensorflow import keras
from models.common import (C3, SPP, SPPF, Bottleneck, BottleneckCSP, C3x, Concat, Conv, CrossConv, DWConv,
D... | null |
165,845 | import argparse
import sys
from copy import deepcopy
from pathlib import Path
ROOT = FILE.parents[1]
import numpy as np
import tensorflow as tf
import torch
import torch.nn as nn
from tensorflow import keras
from models.common import (C3, SPP, SPPF, Bottleneck, BottleneckCSP, C3x, Concat, Conv, CrossConv, DWConv,
... | null |
165,847 | import math
import random
import cv2
import numpy as np
from ..augmentations import box_candidates
from ..general import resample_segments, segment2box
def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
# Compute candidate boxes: box1 before augment, box2 after a... | null |
165,848 | import contextlib
import math
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from .. import threaded
from ..general import xywh2xyxy
from ..plots import Annotator, colors
def xywh2xyxy(x):
# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2,... | null |
165,849 | import contextlib
import math
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from .. import threaded
from ..general import xywh2xyxy
from ..plots import Annotator, colors
def plot_results_with_masks(file='path/to/results.csv', dir='', best=True):... | null |
165,850 | import os
import random
import cv2
import numpy as np
import torch
from torch.utils.data import DataLoader, distributed
from ..augmentations import augment_hsv, copy_paste, letterbox
from ..dataloaders import InfiniteDataLoader, LoadImagesAndLabels, seed_worker
from ..general import LOGGER, xyn2xy, xywhn2xyxy, xyxy2xyw... | null |
165,853 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
def crop_mask(masks, boxes):
"""
"Crop" predicted masks by zeroing out everything not in the predicted bbox.
Vectorized by Chong (thanks Chong).
Args:
- masks should be a size [h, w, n] tensor of masks
- boxes sho... | Crop after upsample. protos: [mask_dim, mask_h, mask_w] masks_in: [n, mask_dim], n is number of masks after nms bboxes: [n, 4], n is number of masks after nms shape: input_image_size, (h, w) return: h, w, n |
165,854 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
def crop_mask(masks, boxes):
"""
"Crop" predicted masks by zeroing out everything not in the predicted bbox.
Vectorized by Chong (thanks Chong).
Args:
- masks should be a size [h, w, n] tensor of masks
- boxes sho... | Crop before upsample. proto_out: [mask_dim, mask_h, mask_w] out_masks: [n, mask_dim], n is number of masks after nms bboxes: [n, 4], n is number of masks after nms shape:input_image_size, (h, w) return: h, w, n |
165,855 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
def crop_mask(masks, boxes):
"""
"Crop" predicted masks by zeroing out everything not in the predicted bbox.
Vectorized by Chong (thanks Chong).
Args:
- masks should be a size [h, w, n] tensor of masks
- boxes sho... | Crop after upsample. protos: [mask_dim, mask_h, mask_w] masks_in: [n, mask_dim], n is number of masks after nms bboxes: [n, 4], n is number of masks after nms shape: input_image_size, (h, w) return: h, w, n |
165,856 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `scale_image` function. Write a Python function `def scale_image(im1_shape, masks, im0_shape, ratio_pad=None)` to solve the following problem:
img1_shape: model inpu... | img1_shape: model input shape, [h, w] img0_shape: origin pic shape, [h, w, 3] masks: [h, w, num] |
165,857 | import cv2
import numpy as np
import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `mask_iou` function. Write a Python function `def mask_iou(mask1, mask2, eps=1e-7)` to solve the following problem:
mask1: [N, n] m1 means number of predicted object... | mask1: [N, n] m1 means number of predicted objects mask2: [M, n] m2 means number of gt objects Note: n means image_w x image_h return: masks iou, [N, M] |
165,860 | import numpy as np
from ..metrics import ap_per_class
def fitness(x):
# Model fitness as a weighted combination of metrics
w = [0.0, 0.0, 0.1, 0.9, 0.0, 0.0, 0.1, 0.9]
return (x[:, :8] * w).sum(1) | null |
165,861 | import numpy as np
from ..metrics import ap_per_class
def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16, prefix=''):
""" Compute the average precision, given the recall and precision curves.
Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
# Ar... | Args: tp_b: tp of boxes. tp_m: tp of masks. other arguments see `func: ap_per_class`. |
165,864 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,865 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,866 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,867 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,868 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,869 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,870 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,871 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,872 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,873 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,874 | import math
import os
import platform
import subprocess
import time
import warnings
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataPa... | null |
165,880 | import math
import random
import cv2
import numpy as np
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
from utils.metrics import bbox_ioa
def box_candidates(box1, box2, w... | null |
165,881 | import math
import random
import cv2
import numpy as np
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
from utils.metrics import bbox_ioa
def bbox_ioa(box1, box2, eps=1e... | null |
165,882 | import math
import random
import cv2
import numpy as np
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
from utils.metrics import bbox_ioa
def xywhn2xyxy(x, w=640, h=640,... | null |
165,884 | import math
import random
import cv2
import numpy as np
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
from utils.metrics import bbox_ioa
IMAGENET_MEAN = 0.485, 0.456, 0.... | null |
165,885 | import math
import random
import cv2
import numpy as np
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
from utils.metrics import bbox_ioa
IMAGENET_MEAN = 0.485, 0.456, 0.... | null |
165,886 | import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.metrics import bbox_iou, box_iou
from utils.torch_utils import de_parallel
from utils.general import xywh2xyxy
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
# return positive, negativ... | null |
165,887 | import contextlib
import math
import os
from copy import copy
from pathlib import Path
from urllib.error import URLError
import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sn
import torch
from PIL import Image, ImageDraw, ImageFont
from utils import Try... | null |
165,894 | import contextlib
import math
import os
from copy import copy
from pathlib import Path
from urllib.error import URLError
import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sn
import torch
from PIL import Image, ImageDraw, ImageFont
from utils import Try... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.