repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
torch-mlir | torch-mlir-main/test/python/importer/jit_ir/ivalue_import/annotations/export-recursive.py | # -*- Python -*-
# This file is licensed under a pytorch-style license
# See LICENSE.pytorch for license information.
import typing
import torch
from torch_mlir.dialects.torch.importer.jit_ir import ClassAnnotator, ModuleBuilder
# RUN: %PYTHON %s | torch-mlir-opt | FileCheck %s
mb = ModuleBuilder()
class Submodule... | 1,537 | 30.387755 | 109 | py |
torch-mlir | torch-mlir-main/externals/llvm-external-projects/torch-mlir-dialects/test/lit.cfg.py | # -*- Python -*-
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# Also available under a BSD-style license. See LICENSE.
import os
import platform
import re
import subp... | 2,451 | 34.028571 | 86 | py |
torch-mlir | torch-mlir-main/build_tools/autogen_ltc_backend.py | import argparse
import hashlib
import importlib.util
import logging
import os
import re
import subprocess
import warnings
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from shutil import which
from textwrap import dedent, indent
# PyTorch's LTC backend autogen script
im... | 19,326 | 35.260788 | 160 | py |
torch-mlir | torch-mlir-main/build_tools/scrape_releases.py | """Scrapes the github releases API to generate a static pip-install-able releases page.
See https://github.com/llvm/torch-mlir/issues/1374
"""
import argparse
import json
import requests
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('owner', type=str)
parser.add_argument('repo', type=str)
... | 833 | 22.166667 | 87 | py |
ASDNet | ASDNet-main/main.py | import os
import sys
import csv
import glob
import torch
from torch import nn
from torch import optim
from torch.utils.data import DataLoader
from torchvision import transforms
from core.opts import parse_opts
from core.dataset import *
from core.optimization import *
from core.io import *
from core.models import *
f... | 15,870 | 50.529221 | 156 | py |
ASDNet | ASDNet-main/calculate_FLOP.py | import torch.nn as nn
from thop import profile
from backbones_video import resnet_2d_v, resnet_3d, resnext, mobilenet, mobilenetv2, shufflenet, shufflenetv2
from backbones_audio import resnet_2d_a, sincdsnet
# %%%%%%%%--------------------- SELECT THE MODEL BELOW ---------------------%%%%%%%%
# model = resnet_2d_v.get_... | 1,161 | 43.692308 | 109 | py |
ASDNet | ASDNet-main/core/optimization.py | import os
import time
import copy
import torch
from sklearn.metrics import roc_auc_score
from sklearn.metrics import average_precision_score
def optimize_av_enc(model, dataloader_train, data_loader_val, device,
criterion, optimizer, scheduler, num_epochs,
models_out=None, log=... | 8,946 | 33.81323 | 104 | py |
ASDNet | ASDNet-main/core/dataset.py | import os
import math
import glob
import time
import random
import torch
from PIL import Image
from torch.utils import data
from torchvision.transforms import RandomCrop, ColorJitter
import numpy as np
import core.io as io
import core.clip_utils as cu
import multiprocessing as mp
class AV_Enc_BaseDataset(data.Datase... | 17,212 | 38.570115 | 127 | py |
ASDNet | ASDNet-main/core/util.py | import os
import csv
import glob
import torch
import pandas as pd
import numpy as np
from scipy.special import softmax
from scipy.signal import medfilt
class Logger():
def __init__(self, targetFile, separator=';'):
self.targetFile = targetFile
self.separator = separator
def writeHeaders(self,... | 2,941 | 30.297872 | 98 | py |
ASDNet | ASDNet-main/core/models.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parameter
import torch.nn.functional as F
from backbones_video import resnet_3d, resnext, mobilenet, mobilenetv2, shufflenet, shufflenetv2
from backbones_audio import sincdsnet
class ISRM(nn.Module):
def __init__(self, inplanes, ... | 7,952 | 34.346667 | 146 | py |
ASDNet | ASDNet-main/backbones_video/shufflenetv2.py | '''ShuffleNetV2 in PyTorch.
See the paper "ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from collections import OrderedDict
from torch.nn import init
import math
... | 6,654 | 32.611111 | 107 | py |
ASDNet | ASDNet-main/backbones_video/mobilenetv2.py | '''MobilenetV2 in PyTorch.
See the paper "MobileNetV2: Inverted Residuals and Linear Bottlenecks" for more details.
'''
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv3d(inp, ... | 5,284 | 30.458333 | 98 | py |
ASDNet | ASDNet-main/backbones_video/resnext.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from functools import partial
__all__ = ['ResNeXt', 'resnet50', 'resnet101']
def conv3x3x3(in_planes, out_planes, stride=1):
# 3x3x3 convolution with padding
return nn.Conv3d(
in_planes,... | 6,352 | 29.252381 | 95 | py |
ASDNet | ASDNet-main/backbones_video/shufflenet.py | '''ShuffleNet in PyTorch.
See the paper "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn... | 5,594 | 32.909091 | 129 | py |
ASDNet | ASDNet-main/backbones_video/resnet_3d.py | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_inplanes():
return [64, 128, 256, 512]
def conv3x3x3(in_planes, out_planes, stride=1):
return nn.Conv3d(in_planes,
out_planes,
kernel_size=3,
... | 12,206 | 35.768072 | 125 | py |
ASDNet | ASDNet-main/backbones_video/mobilenet.py | '''MobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv3d(inp, oup, kernel_size=3, stri... | 3,442 | 29.741071 | 123 | py |
ASDNet | ASDNet-main/thop/count_hooks.py | import argparse
import torch
import torch.nn as nn
multiply_adds = 1
def count_conv1d(m, x, y):
# TODO: add support for pad and dilation
x = x[0]
cin = m.in_channels
cout = m.out_channels
kl = m.kernel_size[0]
batch_size = x.size()[0]
out_l = y.size(2)
# ops per output element
# kernel_mul = kh * kw * c... | 3,402 | 21.388158 | 61 | py |
ASDNet | ASDNet-main/thop/utils.py | import logging
import torch
import torch.nn as nn
from .count_hooks import *
register_hooks = {
nn.Conv1d: count_conv1d,
nn.Conv2d: count_conv2d,
nn.Conv3d: count_conv3d,
nn.BatchNorm1d: count_bn2d,
nn.BatchNorm2d: count_bn2d,
nn.BatchNorm3d: count_bn2d,
nn.ReLU: count_relu,
nn.ReLU6: count_relu,
nn.MaxPool1... | 1,518 | 21.014493 | 63 | py |
ASDNet | ASDNet-main/backbones_audio/sincdsnet.py | import math
import numpy as np
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
def flip(x, dim):
xsize = x.size()
dim = x.dim() + dim if dim < 0 else dim
x = x.contiguous()
x = x.view(-1, *xsize[dim:])
x = x.view(x.size(0), x.size(1), -1)[:, getatt... | 7,229 | 30.434783 | 304 | py |
xarray | xarray-main/doc/conf.py | #
# xarray documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 6 18:57:54 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values h... | 14,699 | 31.166302 | 239 | py |
fit | fit-main/src/quickdraw_dataset.py | import torch.utils.data as data
from PIL import Image
import numpy as np
import torchvision.transforms as T
import os
import json
class QuickDrawDatasetFL(data.Dataset):
def __init__(self,
root,
num_clients,
num_classes,
num_shots,
... | 8,752 | 35.777311 | 120 | py |
fit | fit-main/src/naive_bayes.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import multivariate_normal
from utils import extract_class_indices
class NaiveBayesPredictor(nn.Module):
def __init__(self, args):
super(NaiveBayesPredictor, self).__init__()
self.args = args
if sel... | 3,539 | 39.689655 | 117 | py |
fit | fit-main/src/tf_dataset_reader.py | import tensorflow as tf
import tensorflow_datasets as tfds
import torch
import torchvision.transforms as T
from PIL import Image
import numpy as np
MAX_IN_MEMORY = 20000
class TfDatasetReader:
def __init__(self,
dataset,
task,
context_batch_size,
... | 11,369 | 40.801471 | 166 | py |
fit | fit-main/src/efficientnet_utils.py | """utils.py - Helper functions for building the model and for loading model parameters.
These helper functions are built to mirror those in the official TensorFlow implementation.
"""
# Author: lukemelas (github username)
# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch
# With adjustments and added ... | 24,956 | 39.51461 | 130 | py |
fit | fit-main/src/run_fit.py | # Note:
# Throughout this code, we use the nomenclature of context set and target set instead of
# support set and query set, respectively, that is used in the paper.
import os.path
import torch
import argparse
from dataset import vtab_datasets, few_shot_datasets
from utils import Logger, compute_accuracy, limit_tenso... | 7,463 | 45.65 | 127 | py |
fit | fit-main/src/features.py | import torch
import torch.nn as nn
import numpy as np
from efficientnet import film_efficientnet
from bit_resnet import KNOWN_MODELS
def create_feature_extractor(args):
if "efficientnet" in args.feature_extractor:
feature_extractor = film_efficientnet(args.feature_extractor)
else:
feature_extr... | 3,076 | 31.734043 | 94 | py |
fit | fit-main/src/efficientnet.py | """model.py - Model and module class for EfficientNet.
They are built to mirror those in the official TensorFlow implementation.
"""
# Author: lukemelas (github username)
# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch
# With adjustments and added comments by workingcoder (github username).
import... | 22,375 | 38.60354 | 107 | py |
fit | fit-main/src/utils.py | import os
import torch
import torch.nn.functional as F
import numpy as np
import tensorflow as tf
import csv
class Logger():
def __init__(self, checkpoint_dir, log_file_name):
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
log_file_path = os.path.join(checkpoint_dir... | 3,208 | 27.90991 | 109 | py |
fit | fit-main/src/model.py | import torch
import numpy as np
from utils import cross_entropy_loss, compute_accuracy, shuffle, predict_by_max_logit, compute_accuracy_from_predictions
from classifier import NaiveBayesClassifier
from features import create_feature_extractor
from dataset import TaskResampler
from torch.utils.data import DataLoader
c... | 16,168 | 53.258389 | 136 | py |
fit | fit-main/src/classifier.py | import torch
import torch.nn as nn
from features import create_film_adapter
from naive_bayes import NaiveBayesPredictor
import sys
class NaiveBayesClassifier(nn.Module):
def __init__(self, feature_extractor, args):
super(NaiveBayesClassifier, self).__init__()
self.feature_extractor = feature_extra... | 2,740 | 38.724638 | 111 | py |
fit | fit-main/src/dataset.py | import numpy as np
import math
import torch
from utils import shuffle
from utils import extract_class_indices
vtab_datasets = [
{'name': "caltech101", 'task': None, 'model_name': "caltech101", 'category': "natural",
'num_classes': 102, 'image_size': 384,'bit_image_size': 384, 'enabled': True},
{'name': "... | 10,791 | 60.318182 | 127 | py |
fit | fit-main/src/run_fed_avg.py | import os.path
import torch
import numpy as np
import argparse
from utils import Logger, compute_accuracy, limit_tensorflow_memory_usage, CsvWriter
from model import FiT
from cifar100_dataset import Cifar100FL, Cifar100FLTest
from quickdraw_dataset import QuickDrawDatasetFL, QuickDrawDatasetFLTest
from torchvision.data... | 9,464 | 53.085714 | 127 | py |
fit | fit-main/src/cifar100_dataset.py | import torch.utils.data as data
from PIL import Image
import numpy as np
import torchvision
from torchvision.datasets import CIFAR100
import torchvision.transforms as T
class Cifar100FL(data.Dataset):
def __init__(self,
root,
num_clients,
num_classes,
... | 7,125 | 34.277228 | 113 | py |
fit | fit-main/src/bit_resnet.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 11,695 | 40.622776 | 138 | py |
ImbalanceLearning | ImbalanceLearning-master/code/class.py | # -*- encoding:utf-8 -*-
#xgboostװ̳ ο http://blog.csdn.net/lht_okk/article/details/54311333
#xgboostԭο http://www.cnblogs.com/mfryf/p/6238185.html
#http://blog.csdn.net/bryan__/article/details/52056112
#xgboost ξ http://blog.csdn.net/u010414589/article/details/51153310
import xgboost as xgb
import numpy ... | 7,244 | 22 | 198 | py |
ImbalanceLearning | ImbalanceLearning-master/code/score.py | # -*- encoding:utf-8 -*-
#xgboostװ̳ ο http://blog.csdn.net/lht_okk/article/details/54311333
#xgboostԭο http://www.cnblogs.com/mfryf/p/6238185.html
#http://blog.csdn.net/bryan__/article/details/52056112
#xgboost ξ http://blog.csdn.net/u010414589/article/details/51153310
import xgboost as xgb
import numpy ... | 7,769 | 22.907692 | 198 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/eval.py | import os
import cv2
import argparse
import numpy as np
import torch
import torch.nn as nn
from config import config
from utils.pyt_utils import ensure_dir, link_file, load_model, parse_devices
from utils.visualize import print_iou, show_img
from engine.evaluator import Evaluator
from engine.logger import get_logger
... | 4,579 | 39.530973 | 107 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/train.py | import os.path as osp
import os
import sys
import time
import argparse
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.backends.cudnn as cudnn
from torch.nn.parallel import DistributedDataParallel
from config import config
from dataloader.dataloader import get_tr... | 6,275 | 36.807229 | 123 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/builder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.init_func import init_weight
from utils.load_utils import load_pretrain
from functools import partial
from engine.logger import get_logger
logger = get_logger()
class EncoderDecoder(nn.Module):
def __init__(self, cfg=None, criterion=n... | 5,829 | 45.64 | 154 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/net_utils.py | import torch
import torch.nn as nn
from timm.models.layers import trunc_normal_
import math
# Feature Rectify Module
class ChannelWeights(nn.Module):
def __init__(self, dim, reduction=1):
super(ChannelWeights, self).__init__()
self.dim = dim
self.avg_pool = nn.AdaptiveAvgPool2d(1)
... | 8,019 | 41.433862 | 163 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/decoders/UPernet.py | import numpy as np
import torch.nn as nn
import torch
from torch.nn.modules import module
import torch.nn.functional as F
class UPerHead(nn.Module):
"""Unified Perceptual Parsing for Scene Understanding.
This head is the implementation of `UPerNet
<https://arxiv.org/abs/1807.10221>`_.
Args:
po... | 5,294 | 35.267123 | 179 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/decoders/MLPDecoder.py | import numpy as np
import torch.nn as nn
import torch
from torch.nn.modules import module
import torch.nn.functional as F
class MLP(nn.Module):
"""
Linear Embedding:
"""
def __init__(self, input_dim=2048, embed_dim=768):
super().__init__()
self.proj = nn.Linear(input_dim, embed_dim)
... | 2,967 | 34.759036 | 110 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/decoders/deeplabv3plus.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class DeepLabV3Plus(nn.Module):
def __init__(self, in_channels=[256, 512, 1024, 2048], num_classes=40, norm_layer=nn.BatchNorm2d):
super(DeepLabV3Plus, self).__init__()
self.num_classes = num_classes
self.aspp = AS... | 3,563 | 35.367347 | 107 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/decoders/fcnhead.py | import numpy as np
import torch.nn as nn
import torch
from torch.nn.modules import module
import torch.nn.functional as F
class FCNHead(nn.Module):
def __init__(self, in_channels=384, channels=None, kernel_size=3, dilation=1,
num_classes=40, norm_layer=nn.BatchNorm2d):
super(FCNHead, sel... | 947 | 31.689655 | 94 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/encoders/dual_segformer.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from ..net_utils import FeatureFusionModule as FFM
from ..net_utils import FeatureRectifyModule as FRM
import math
import time
from engine.logger import get... | 21,504 | 40.595745 | 124 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/models/encoders/dual_swin.py | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu, Yutong Lin, Yixuan Wei
# --------------------------------------------------------
import functools
import time
import torch
import... | 30,230 | 39.578523 | 155 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/engine/engine.py | import os
import os.path as osp
import time
import argparse
import torch
import torch.distributed as dist
from .logger import get_logger
from utils.pyt_utils import load_model, parse_devices, extant_file, link_file, ensure_dir
logger = get_logger()
class State(object):
def __init__(self):
self.epoch = 1... | 5,782 | 34.262195 | 101 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/engine/evaluator.py | import os
import cv2
import numpy as np
import time
from tqdm import tqdm
from timm.models.layers import to_2tuple
import torch
import multiprocessing as mp
from engine.logger import get_logger
from utils.pyt_utils import load_model, link_file, ensure_dir
from utils.transforms import pad_image_to_shape, normalize
lo... | 17,381 | 39.236111 | 115 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/engine/dist_test.py | import os
import os.path as osp
import cv2
import numpy as np
import time
from tqdm import tqdm
import torch
import torch.nn.functional as F
import torch.multiprocessing as mp
from engine.logger import get_logger
from utils.pyt_utils import load_model, link_file, ensure_dir
from utils.transforms import pad_image_to_s... | 10,731 | 36.788732 | 80 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/utils/loss_opr.py | import numpy as np
import scipy.ndimage as nd
import torch
import torch.nn as nn
import torch.nn.functional as F
from engine.logger import get_logger
logger = get_logger()
class FocalLoss2d(nn.Module):
def __init__(self, gamma=0, weight=None, reduction='mean', ignore_index=255):
super(FocalLoss2d, self)... | 7,316 | 37.920213 | 98 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/utils/load_utils.py | import torch
import re
from torch import distributed as dist
def get_dist_info():
if dist.is_available():
initialized = dist.is_initialized()
else:
initialized = False
if initialized:
rank = dist.get_rank()
world_size = dist.get_world_size()
else:
rank = 0
... | 2,946 | 31.384615 | 78 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/utils/pyt_utils.py | # encoding: utf-8
import os
import sys
import time
import random
import argparse
import logging
from collections import OrderedDict, defaultdict
import torch
import torch.utils.model_zoo as model_zoo
import torch.distributed as dist
class LogFormatter(logging.Formatter):
log_fout = None
date_full = '[%(asctim... | 7,322 | 28.292 | 79 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/utils/init_func.py | #!/usr/bin/env python3
# encoding: utf-8
# @Time : 2018/9/28 下午12:13
# @Author : yuchangqian
# @Contact : changqian_yu@163.com
# @File : init_func.py.py
import torch
import torch.nn as nn
def __init_weight(feature, conv_init, norm_layer, bn_eps, bn_momentum,
**kwargs):
for name, m in featu... | 2,281 | 38.344828 | 111 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/utils/transforms.py | import warnings
import torch.nn as nn
import torch.nn.functional as F
import cv2
import numpy as np
import numbers
import random
import collections
def get_2dshape(shape, *, zero=True):
if not isinstance(shape, collections.Iterable):
shape = int(shape)
shape = (shape, shape)
else:
h, ... | 5,390 | 27.675532 | 79 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/dataloader/dataloader.py | import cv2
import torch
import numpy as np
from torch.utils import data
import random
from config import config
from utils.transforms import generate_random_crop_pos, random_crop_pad_to_shape, normalize
def random_mirror(rgb, gt, modal_x):
if random.random() >= 0.5:
rgb = cv2.flip(rgb, 1)
gt = cv2.... | 3,504 | 37.944444 | 113 | py |
RGBX_Semantic_Segmentation | RGBX_Semantic_Segmentation-main/dataloader/RGBXDataset.py | import os
from pickletools import uint8
import cv2
import torch
import numpy as np
import torch.utils.data as data
class RGBXDataset(data.Dataset):
def __init__(self, setting, split_name, preprocess=None, file_length=None):
super(RGBXDataset, self).__init__()
self._split_name = split_name
... | 4,490 | 33.546154 | 101 | py |
LASNet | LASNet-main/test_LASNet.py | import os
import time
from tqdm import tqdm
from PIL import Image
import json
import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
from toolbox import get_model
from toolbox import averageMeter, runningScore
from toolbox import class_to_RGB, load_ckpt, save_ckpt
from toolbox.datasets.... | 3,938 | 34.169643 | 111 | py |
LASNet | LASNet-main/sober.py | import cv2
import os
from torchvision import transforms
import numpy as np
with open(os.path.join('/home/user/EGFNet/dataset', f'all.txt'), 'r') as f:
image_labels = f.readlines()
for i in range(len(image_labels)):
label_path1 = image_labels[i].strip()
imgrgb= cv2.imread('/home/user/EGFNet/dataset/seperat... | 1,342 | 25.86 | 101 | py |
LASNet | LASNet-main/resnet.py | # import torchvision.models as models
# import torch.nn as nn
# # https://pytorch.org/docs/stable/torchvision/models.html#id3
#
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
model_urls = {
"resnet18": "https://download.pytorch.org/models/resnet18-5c106cde.pth",
"resnet34": "https... | 11,621 | 31.646067 | 115 | py |
LASNet | LASNet-main/train_LASNet.py | import os
import shutil
import json
import time
from apex import amp
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader
from toolbox import get_dataset # loss
from toolbox.optim.Ranger import Range... | 6,506 | 36.396552 | 153 | py |
LASNet | LASNet-main/toolbox/losses.py | """
Lovasz-Softmax and Jaccard hinge loss in PyTorch
Maxim Berman 2018 ESAT-PSI KU Leuven (MIT License)
"""
#https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytorch/lovasz_losses.py
from __future__ import print_function, division
import torch
from torch.autograd import Variable
import torch.nn.functional as F... | 8,433 | 32.736 | 118 | py |
LASNet | LASNet-main/toolbox/dual_self_att.py | ###########################################################################
# Created by: CASIA IVA
# Email: jliu@nlpr.ia.ac.cn
# Copyright (c) 2018
###########################################################################
import numpy as np
import torch
import math
from torch.nn import Module, Sequential, Conv2d, R... | 3,020 | 34.541176 | 117 | py |
LASNet | LASNet-main/toolbox/utils.py | import numpy as np
import torch
from tqdm import tqdm
import os
import math
import random
import time
import torch.backends.cudnn as cudnn
class ClassWeight(object):
def __init__(self, method):
assert method in ['no', 'enet', 'median_freq_balancing']
self.method = method
def get_weight(self... | 8,520 | 30.442804 | 89 | py |
LASNet | LASNet-main/toolbox/metrics.py | # https://github.com/meetshah1995/pytorch-semseg/blob/master/ptsemseg/metrics.py
import numpy as np
class runningScore(object):
'''
n_classes: database的类别,包括背景
ignore_index: 需要忽略的类别id,一般为未标注id, eg. CamVid.id_unlabel
'''
def __init__(self, n_classes, ignore_index=None):
self.n_cla... | 3,205 | 30.742574 | 96 | py |
LASNet | LASNet-main/toolbox/scheduler/lr_scheduler.py | import math
from torch.optim.lr_scheduler import MultiStepLR, _LRScheduler
class WarmupMultiStepLR(MultiStepLR):
def __init__(self, optimizer, milestones, gamma=0.1, warmup_factor=1.0 / 3,
warmup_iters=500, last_epoch=-1):
self.warmup_factor = warmup_factor
self.warmup_iters = war... | 4,673 | 39.643478 | 118 | py |
LASNet | LASNet-main/toolbox/models/LASNet.py | import os
import torch.nn as nn
import torch
from resnet import Backbone_ResNet152_in3
import torch.nn.functional as F
import numpy as np
from toolbox.dual_self_att import CAM_Module
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1):
supe... | 11,201 | 39.150538 | 137 | py |
LASNet | LASNet-main/toolbox/optim/Ranger.py | # Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer.
# https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer
# and/or
# https://github.com/lessw2020/Best-Deep-Learning-Optimizers
# Ranger has now been used to capture 12 records on the FastAI leaderboard.
... | 7,914 | 42.016304 | 169 | py |
LASNet | LASNet-main/toolbox/datasets/augmentations.py | from __future__ import division
import sys
import random
from PIL import Image
try:
import accimage
except ImportError:
accimage = None
import numbers
import collections
import torchvision.transforms.functional as F
__all__ = ["Compose",
"Resize", # 尺寸缩减到对应size, 如果给定size为int,尺寸缩减到(size * height /... | 9,519 | 33.492754 | 111 | py |
LASNet | LASNet-main/toolbox/datasets/irseg.py | import os
from PIL import Image
import numpy as np
from sklearn.model_selection import train_test_split
import torch
import torch.utils.data as data
from torchvision import transforms
from toolbox.datasets.augmentations import Resize, Compose, ColorJitter, RandomHorizontalFlip, RandomCrop, RandomScale, \
RandomRot... | 4,314 | 36.198276 | 121 | py |
LASNet | LASNet-main/toolbox/datasets/camvid.py | import os
from PIL import Image
import numpy as np
import torch
import torch.utils.data as data
from torchvision import transforms
from toolbox.datasets.augmentations import Resize, Compose, ColorJitter, RandomHorizontalFlip, RandomCrop, RandomScale
class Camvid(data.Dataset):
def __init__(self, cfg, mode='tra... | 5,656 | 32.276471 | 118 | py |
LASNet | LASNet-main/toolbox/datasets/pst900.py | import os
from PIL import Image
import numpy as np
from sklearn.model_selection import train_test_split
import torch
import torch.utils.data as data
from torchvision import transforms
from toolbox.datasets.augmentations import Resize, Compose, ColorJitter, RandomHorizontalFlip, RandomCrop, RandomScale, \
RandomRot... | 3,827 | 34.119266 | 121 | py |
DiffFashion | DiffFashion-main/id_loss.py | import torch
from torch import nn
# from configs.paths_config import model_paths
from id_model.model_irse import Backbone
class IDLoss(nn.Module):
def __init__(self):
super(IDLoss, self).__init__()
print('Loading ResNet ArcFace')
self.facenet = Backbone(input_size=112, num_layers=50, drop_... | 1,685 | 37.318182 | 92 | py |
DiffFashion | DiffFashion-main/src/vqc_core.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import math
import yaml
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as T
import clip
# sys.path.append('taming-transformers')
# from taming.models.vqgan import VQModel
from utils_flexit... | 5,174 | 36.5 | 124 | py |
DiffFashion | DiffFashion-main/id_model/model_irse.py | from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Dropout, Sequential, Module
from id_model.helpers import get_blocks, Flatten, bottleneck_IR, bottleneck_IR_SE, l2_norm
"""
Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
"""
class Backbone(Module):
... | 2,828 | 32.678571 | 97 | py |
DiffFashion | DiffFashion-main/id_model/helpers.py | from collections import namedtuple
import torch
from torch.nn import Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module
"""
ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
"""
class Flatten(Module):
def forward(self, input):
return inp... | 3,555 | 28.882353 | 112 | py |
DiffFashion | DiffFashion-main/utils_visualize/visualization.py | from pathlib import Path
from numpy.core.shape_base import block
import torch
import matplotlib.pyplot as plt
from torchvision.transforms import functional as TF
from typing import Optional, Union
import matplotlib.pyplot as plt
import numpy as np
from PIL.Image import Image
from pathlib import Path
def show_tensor... | 1,932 | 23.1625 | 95 | py |
DiffFashion | DiffFashion-main/utils_flexit/inception.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
try:
from torchvision.models.utils import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url... | 12,263 | 36.163636 | 140 | py |
DiffFashion | DiffFashion-main/utils_flexit/torch_utils.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
def monkey_typing(module):
def deco(f):
setattr(module, f.__name__, f)
return deco
@monkey_typing(torch.nn.Module)
def batch_forward(self, x, batch_size=16):
module_device = next(self.parameters()).device
... | 2,978 | 28.49505 | 107 | py |
DiffFashion | DiffFashion-main/utils_flexit/io.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import numpy as np
import json
import pandas as pd
import json
from PIL import Image
import yaml
def load(fname, **kwargs):
ext = str(fname).split('.')[-1]
if ext == 'pt':
return torch.load(fname, **kwargs)
elif ex... | 1,412 | 27.836735 | 53 | py |
DiffFashion | DiffFashion-main/optimization/losses.py | from torch.nn import functional as F
def d_clip_loss(x, y, use_cosine=False):
x = F.normalize(x, dim=-1)
y = F.normalize(y, dim=-1)
if use_cosine:
distance = 1 - (x @ y.t()).squeeze()
else:
distance = (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
return distance
def range_... | 396 | 21.055556 | 69 | py |
DiffFashion | DiffFashion-main/optimization/augmentations.py | import torch
from torch import nn
import kornia.augmentation as K
class ImageAugmentations(nn.Module):
def __init__(self, output_size, augmentations_number, p=0.7):
super().__init__()
self.output_size = output_size
self.augmentations_number = augmentations_number
self.augmentation... | 1,649 | 37.372093 | 100 | py |
DiffFashion | DiffFashion-main/optimization/image_editor.py | import os
from pathlib import Path
from optimization.constants import ASSETS_DIR_NAME, RANKED_RESULTS_DIR
from utils_visualize.metrics_accumulator import MetricsAccumulator
from utils_visualize.video import save_video
from numpy import random
from optimization.augmentations import ImageAugmentations
from PIL import ... | 22,553 | 40.156934 | 113 | py |
DiffFashion | DiffFashion-main/CLIP/clip/clip.py | import hashlib
import os
import urllib
import warnings
from typing import Any, Union, List
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenizer import SimpleTokenizer as _Token... | 8,433 | 36.484444 | 149 | py |
DiffFashion | DiffFashion-main/CLIP/clip/model.py | from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have strid... | 17,242 | 38.822171 | 178 | py |
DiffFashion | DiffFashion-main/CLIP/tests/test_consistency.py | import numpy as np
import pytest
import torch
from PIL import Image
import clip
@pytest.mark.parametrize('model_name', clip.available_models())
def test_consistency(model_name):
device = "cpu"
jit_model, transform = clip.load(model_name, device=device, jit=True)
py_model, _ = clip.load(model_name, device... | 812 | 30.269231 | 73 | py |
DiffFashion | DiffFashion-main/guided_diffusion/setup.py | from setuptools import setup
setup(
name="guided-diffusion",
py_modules=["guided_diffusion"],
install_requires=["blobfile>=1.0.5", "torch", "tqdm"],
)
| 164 | 19.625 | 58 | py |
DiffFashion | DiffFashion-main/guided_diffusion/scripts/image_sample.py | """
Generate a large batch of image samples from a model and save them as a large
numpy array. This can be used to produce samples for FID evaluation.
"""
import argparse
import os
import numpy as np
import torch as th
import torch.distributed as dist
from guided_diffusion import dist_util, logger
from guided_diffus... | 3,398 | 30.183486 | 88 | py |
DiffFashion | DiffFashion-main/guided_diffusion/scripts/super_res_sample.py | """
Generate a large batch of samples from a super resolution model, given a batch
of samples from a regular model from image_sample.py.
"""
import argparse
import os
import blobfile as bf
import numpy as np
import torch as th
import torch.distributed as dist
from guided_diffusion import dist_util, logger
from guide... | 3,725 | 30.05 | 84 | py |
DiffFashion | DiffFashion-main/guided_diffusion/scripts/classifier_sample.py | """
Like image_sample.py, but use a noisy image classifier to guide the sampling
process towards more realistic images.
"""
import argparse
import os
import numpy as np
import torch as th
import torch.distributed as dist
import torch.nn.functional as F
from guided_diffusion import dist_util, logger
from guided_diffu... | 4,266 | 31.325758 | 88 | py |
DiffFashion | DiffFashion-main/guided_diffusion/scripts/classifier_train.py | """
Train a noised image classifier on ImageNet.
"""
import argparse
import os
import blobfile as bf
import torch as th
import torch.distributed as dist
import torch.nn.functional as F
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
from torch.optim import AdamW
from guided_diffusion import ... | 7,313 | 31.220264 | 99 | py |
DiffFashion | DiffFashion-main/guided_diffusion/scripts/image_nll.py | """
Approximate the bits/dimension for an image model.
"""
import argparse
import os
import numpy as np
import torch.distributed as dist
from guided_diffusion import dist_util, logger
from guided_diffusion.image_datasets import load_data
from guided_diffusion.script_util import (
model_and_diffusion_defaults,
... | 2,934 | 29.257732 | 86 | py |
DiffFashion | DiffFashion-main/guided_diffusion/scripts/super_res_train.py | """
Train a super-resolution model.
"""
import argparse
import torch.nn.functional as F
from guided_diffusion import dist_util, logger
from guided_diffusion.image_datasets import load_data
from guided_diffusion.resample import create_named_schedule_sampler
from guided_diffusion.script_util import (
sr_model_and_... | 2,695 | 26.232323 | 87 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/resample.py | from abc import ABC, abstractmethod
import numpy as np
import torch as th
import torch.distributed as dist
def create_named_schedule_sampler(name, diffusion):
"""
Create a ScheduleSampler from a library of pre-defined samplers.
:param name: the name of the sampler.
:param diffusion: the diffusion ob... | 5,689 | 35.709677 | 87 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/losses.py | """
Helpers for various likelihood-based losses. These are ported from the original
Ho et al. diffusion models codebase:
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py
"""
import numpy as np
import torch as th
def normal_kl(mean1, logvar1, mean2, logvar... | 2,534 | 31.5 | 109 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/image_datasets.py | import math
import random
from PIL import Image
import blobfile as bf
from mpi4py import MPI
import numpy as np
from torch.utils.data import DataLoader, Dataset
def load_data(
*,
data_dir,
batch_size,
image_size,
class_cond=False,
deterministic=False,
random_crop=False,
random_flip=Tr... | 5,930 | 34.303571 | 88 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/nn.py | """
Various utilities for neural networks.
"""
import math
import torch as th
import torch.nn as nn
# PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
class SiLU(nn.Module):
def forward(self, x):
return x * th.sigmoid(x)
class GroupNorm32(nn.GroupNorm):
def forward(self, x):
return super(... | 5,020 | 28.362573 | 88 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/fp16_util.py | """
Helpers to train with 16-bit precision.
"""
import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from . import logger
INITIAL_LOG_LOSS_SCALE = 20.0
def convert_module_to_f16(l):
"""
Convert primitive modules to float16.
... | 7,941 | 32.510549 | 114 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/unet.py | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .fp16_util import convert_module_to_f16, convert_module_to_f32
from .nn import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
... | 31,283 | 33.876254 | 124 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/gaussian_diffusion.py | """
This code started out as a PyTorch port of Ho et al's diffusion models:
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py
Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules.
"""
import enum
import math... | 63,650 | 37.764312 | 129 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/train_util.py | import copy
import functools
import os
import blobfile as bf
import torch as th
import torch.distributed as dist
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
from torch.optim import AdamW
from . import dist_util, logger
from .fp16_util import MixedPrecisionTrainer
from .nn import update_em... | 10,604 | 34.115894 | 88 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.