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 |
|---|---|---|---|---|---|---|
keras | keras-master/keras/applications/mobilenet_v2.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 20,697 | 38.05283 | 87 | py |
keras | keras-master/keras/applications/efficientnet.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 25,089 | 31.5 | 87 | py |
keras | keras-master/keras/applications/resnet.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 21,207 | 35.191126 | 87 | py |
keras | keras-master/keras/applications/vgg16.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 9,586 | 37.971545 | 87 | py |
keras | keras-master/keras/applications/densenet.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 16,084 | 36.320186 | 87 | py |
keras | keras-master/keras/applications/imagenet_utils.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 15,197 | 33.778032 | 80 | py |
keras | keras-master/keras/applications/resnet_v2.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 6,741 | 32.879397 | 87 | py |
keras | keras-master/keras/applications/vgg19.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 9,818 | 38.276 | 87 | py |
keras | keras-master/keras/applications/inception_v3.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 16,038 | 36.562061 | 87 | py |
keras | keras-master/keras/applications/mobilenet_v3.py | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 23,489 | 38.412752 | 87 | py |
keras | keras-master/keras/applications/nasnet.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 30,441 | 36.215159 | 87 | py |
keras | keras-master/keras/applications/imagenet_utils_test.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 9,851 | 32.39661 | 80 | py |
keras | keras-master/keras/applications/applications_load_weight_test.py | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 4,840 | 40.732759 | 80 | py |
keras | keras-master/keras/applications/xception.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 13,000 | 38.159639 | 87 | py |
keras | keras-master/keras/applications/inception_resnet_v2.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 15,195 | 37.470886 | 87 | py |
keras | keras-master/keras/applications/mobilenet.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 19,722 | 42.157549 | 87 | py |
keras | keras-master/keras/applications/applications_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 5,219 | 34.27027 | 80 | py |
keras | keras-master/keras/applications/efficientnet_weight_update_util.py | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | 13,222 | 34.834688 | 80 | py |
ReCO | ReCO-master/test.py | # -*- coding: utf-8 -*-
"""
@Time : 2020/6/23 下午1:43
@FileName: test.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import argparse
import torch
from model import Bert4ReCO
from utils import *
parser = argparse.ArgumentParser()
parser.add_argument("--model_type", type=str, default='bert-base-chinese... | 1,629 | 30.346154 | 110 | py |
ReCO | ReCO-master/model.py | # -*- coding: utf-8 -*-
"""
@Time : 2020/6/23 上午10:13
@FileName: model.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoModel
class Bert4ReCO(nn.Module):
def __init__(self, model_type):
super().... | 1,073 | 28.833333 | 93 | py |
ReCO | ReCO-master/train.py | # -*- coding: utf-8 -*-
"""
@Time : 2019/11/21 下午7:14
@FileName: train.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import argparse
import torch
from model import Bert4ReCO
from prepare_data import prepare_bert_data
from utils import *
import torch.distributed as dist
torch.manual_seed(100)
np.rand... | 5,074 | 33.290541 | 114 | py |
ReCO | ReCO-master/BiDAF/inference.py | # -*- coding: utf-8 -*-
import argparse
import cPickle
import codecs
import torch
from utils import *
from preprocess import seg_data, transform_data_to_id
parser = argparse.ArgumentParser(description='inference procedure, note you should train the data at first')
parser.add_argument('--data', type=str,
... | 2,636 | 34.635135 | 113 | py |
ReCO | ReCO-master/BiDAF/MwAN.py | # -*- coding: utf-8 -*-
import torch
from torch import nn
from torch.nn import functional as F
class MwAN(nn.Module):
def __init__(self, vocab_size, embedding_size, encoder_size, drop_out=0.2):
super(MwAN, self).__init__()
self.drop_out=drop_out
self.embedding = nn.Embedding(vocab_size + 1... | 4,704 | 44.679612 | 108 | py |
ReCO | ReCO-master/BiDAF/train.py | # -*- coding: utf-8 -*-
import argparse
import cPickle
import torch
from MwAN import MwAN
from preprocess import process_data
from utils import *
parser = argparse.ArgumentParser(description='PyTorch implementation for Multiway Attention Networks for Modeling '
'Sentence P... | 4,466 | 38.184211 | 120 | py |
ReCO | ReCO-master/BiDAF/BiDAF.py | # -*- coding: utf-8 -*-
"""
@Time : 2019/11/21 下午4:42
@FileName: BiDAF.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class BiDAF(nn.Module):
def __init__(self, vocab_size, embedding_size, encoder_size, drop_out=0.2):
supe... | 4,904 | 40.923077 | 109 | py |
ReCO | ReCO-master/InHouseBert/model.py | # -*- coding: utf-8 -*-
"""
@Time : 2020/6/24 下午6:18
@FileName: model.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import warnings
import apex
import torch
import torch.nn as nn
from apex.contrib.multihead_attn import SelfMultiheadAttn
from apex.mlp import MLP
from torch.nn import functional as F
w... | 4,192 | 37.118182 | 119 | py |
ReCO | ReCO-master/InHouseBert/train.py | # -*- coding: utf-8 -*-
"""
@Time : 2020/6/24 下午6:16
@FileName: train.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import argparse
import sys
sys.path.append("../..")
sys.path.append("..")
from tasks.ReCO.model import BERT
from utils import *
import torch.distributed as dist
torch.manual_seed(100)... | 5,292 | 32.713376 | 114 | py |
mining-legal-arguments | mining-legal-arguments-main/evaluate.py | #!/usr/bin/env python
# coding: utf-8
from collections import Counter
from prettytable import PrettyTable
import os
from transformers import AutoTokenizer
import torch
from torch.utils.data import Dataset
import pandas as pd
from datasets import load_dataset, load_metric
import csv
from ast import literal_eval
impor... | 20,634 | 44.855556 | 227 | py |
mining-legal-arguments | mining-legal-arguments-main/multiTaskModel.py | #!/usr/bin/env python
# coding: utf-8
from collections import Counter
from prettytable import PrettyTable
import os
from transformers import AutoTokenizer
import torch
from torch.utils.data import Dataset
import pandas as pd
from datasets import load_dataset, load_metric
import csv
from ast import literal_eval
import... | 25,615 | 37.232836 | 144 | py |
imbalanced-learn | imbalanced-learn-master/conftest.py | # This file is here so that when running from the root folder
# ./imblearn is added to sys.path by pytest.
# See https://docs.pytest.org/en/latest/pythonpath.html for more details.
# For example, this allows to build extensions in place and run pytest
# doc/modules/clustering.rst and use imblearn from the local folder
... | 798 | 32.291667 | 73 | py |
imbalanced-learn | imbalanced-learn-master/examples/applications/porto_seguro_keras_under_sampling.py | """
==========================================================
Porto Seguro: balancing samples in mini-batches with Keras
==========================================================
This example compares two strategies to train a neural-network on the Porto
Seguro Kaggle data set [1]_. The data set is imbalanced and we... | 8,747 | 32.776062 | 88 | py |
imbalanced-learn | imbalanced-learn-master/imblearn/_min_dependencies.py | """All minimum dependencies for imbalanced-learn."""
import argparse
NUMPY_MIN_VERSION = "1.17.3"
SCIPY_MIN_VERSION = "1.5.0"
PANDAS_MIN_VERSION = "1.0.5"
SKLEARN_MIN_VERSION = "1.0.2"
TENSORFLOW_MIN_VERSION = "2.4.3"
KERAS_MIN_VERSION = "2.4.3"
JOBLIB_MIN_VERSION = "1.1.1"
THREADPOOLCTL_MIN_VERSION = "2.0.0"
PYTEST_M... | 2,240 | 36.35 | 86 | py |
imbalanced-learn | imbalanced-learn-master/imblearn/__init__.py | """Toolbox for imbalanced dataset in machine learning.
``imbalanced-learn`` is a set of python methods to deal with imbalanced
datset in machine learning and pattern recognition.
Subpackages
-----------
combine
Module which provides methods based on over-sampling and under-sampling.
ensemble
Module which prov... | 3,963 | 30.967742 | 83 | py |
imbalanced-learn | imbalanced-learn-master/imblearn/keras/_generator.py | """Implement generators for ``keras`` which will balance the data."""
# This is a trick to avoid an error during tests collection with pytest. We
# avoid the error when importing the package raise the error at the moment of
# creating the instance.
# This is a trick to avoid an error during tests collection with pyte... | 10,276 | 33.719595 | 87 | py |
imbalanced-learn | imbalanced-learn-master/imblearn/keras/__init__.py | """The :mod:`imblearn.keras` provides utilities to deal with imbalanced dataset
in keras."""
from ._generator import BalancedBatchGenerator, balanced_batch_generator
__all__ = ["BalancedBatchGenerator", "balanced_batch_generator"]
| 233 | 32.428571 | 79 | py |
imbalanced-learn | imbalanced-learn-master/imblearn/keras/tests/test_generator.py | import numpy as np
import pytest
from scipy import sparse
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
from sklearn.preprocessing import LabelBinarizer
keras = pytest.importorskip("keras")
from keras.layers import Dense # noqa: E402
from keras.models import Sequential # noqa: E402
from ... | 4,289 | 27.986486 | 86 | py |
imbalanced-learn | imbalanced-learn-master/imblearn/utils/_show_versions.py | """
Utility method which prints system info to help with debugging,
and filing issues on GitHub.
Adapted from :func:`sklearn.show_versions`,
which was adapted from :func:`pandas.show_versions`
"""
# Author: Alexander L. Hayes <hayesall@iu.edu>
# License: MIT
from .. import __version__
def _get_deps_info():
"""O... | 2,176 | 22.408602 | 64 | py |
imbalanced-learn | imbalanced-learn-master/imblearn/utils/tests/test_show_versions.py | """Test for the show_versions helper. Based on the sklearn tests."""
# Author: Alexander L. Hayes <hayesall@iu.edu>
# License: MIT
from imblearn.utils._show_versions import _get_deps_info, show_versions
def test_get_deps_info():
_deps_info = _get_deps_info()
assert "pip" in _deps_info
assert "setuptools"... | 1,818 | 28.819672 | 78 | py |
ML-Doctor | ML-Doctor-main/demo.py | import os
import sys
import torch
import argparse
import torch.nn as nn
import torchvision.models as models
from doctor.meminf import *
from doctor.modinv import *
from doctor.attrinf import *
from doctor.modsteal import *
from demoloader.train import *
from demoloader.DCGAN import *
from utils.define_models import *
... | 10,614 | 41.290837 | 183 | py |
ML-Doctor | ML-Doctor-main/demoloader/dataloader.py | import os
import torch
import pandas
import torchvision
torch.manual_seed(0)
import torch.nn as nn
import PIL.Image as Image
import torchvision.transforms as transforms
from functools import partial
from typing import Any, Callable, List, Optional, Union, Tuple
class CNN(nn.Module):
def __init__(self, input_chann... | 9,806 | 33.900356 | 184 | py |
ML-Doctor | ML-Doctor-main/demoloader/train.py | import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
np.set_printoptions(threshold=np.inf)
from opacus import PrivacyEngine
from torch.optim import lr_scheduler
def GAN_init(m):
classname = m.__class__.__name__
... | 11,748 | 37.270358 | 120 | py |
ML-Doctor | ML-Doctor-main/demoloader/DCGAN.py | import torch.nn as nn
class Generator(nn.Module):
def __init__(self, ngpu=1, nc=3, nz=100, ngf=64):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=Fals... | 4,237 | 29.934307 | 82 | py |
ML-Doctor | ML-Doctor-main/utils/define_models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class attrinf_attack_model(nn.Module):
def __init__(self, inputs, outputs):
super(attrinf_attack_model, self).__init__()
self.classifier = nn.Linear(inputs, outputs)
def forward(self, x):
x = torch.flatten(x, 1)
... | 4,227 | 24.017751 | 130 | py |
ML-Doctor | ML-Doctor-main/doctor/modsteal.py | import torch
import torch.nn.functional as F
from math import *
from tqdm import tqdm
class train_steal_model():
def __init__(self, train_loader, test_loader, target_model, attack_model, TARGET_PATH, ATTACK_PATH, device, batch_size, loss, optimizer):
self.device = device
self.batch_size = batch_si... | 4,341 | 33.188976 | 141 | py |
ML-Doctor | ML-Doctor-main/doctor/attrinf.py | import torch
import pickle
import torch.nn as nn
import torch.optim as optim
from utils.define_models import *
from sklearn.metrics import f1_score
class attack_training():
def __init__(self, device, attack_trainloader, attack_testloader, target_model, TARGET_PATH, ATTACK_PATH):
self.device = device
... | 6,547 | 34.978022 | 120 | py |
ML-Doctor | ML-Doctor-main/doctor/modinv.py | import time
import torch
import random
import numpy as np
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
class ccs_inversion(object):
'''
Model inversion is a kind of data reconstruct attack.
This class we implement the attack on neural network,
the attack goal is t... | 8,409 | 36.713004 | 148 | py |
ML-Doctor | ML-Doctor-main/doctor/meminf.py | import os
import glob
import torch
import pickle
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
np.set_printoptions(threshold=np.inf)
from opacus import PrivacyEngine
from torch.optim import lr_scheduler
from sklearn.metrics imp... | 31,612 | 37.042118 | 183 | py |
IVOS-ATNet | IVOS-ATNet-master/eval_real-world.py | from davisinteractive.session import DavisInteractiveSession
from davisinteractive import utils as interactive_utils
from davisinteractive.dataset import Davis
from davisinteractive.metrics import batched_jaccard
from libs import custom_transforms as tr, davis2017_torchdataset
import os
import numpy as np
from PIL im... | 17,873 | 50.2149 | 147 | py |
IVOS-ATNet | IVOS-ATNet-master/eval_davis-framework.py | from davisinteractive.session import DavisInteractiveSession
from davisinteractive import utils as interactive_utils
from davisinteractive.dataset import Davis
from davisinteractive.metrics import batched_jaccard
from libs import custom_transforms as tr, davis2017_torchdataset
import os
import numpy as np
from PIL im... | 17,800 | 50.005731 | 147 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/ltm_transfer.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
class LTM_transfer(nn.Module):
def __init__(self,md=4, stride=1):
super(LTM_transfer, self).__init__()
self.md = md #displacement (default = 4pixels)
self.range = (md*2 + 1) ** 2 #(default = (4x2+1)**2 = 81)
self.... | 3,767 | 38.25 | 153 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/atnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from networks.deeplab.aspp import ASPP
from networks.deeplab.backbone.resnet import SEResNet50
from networks.correlation_package.correlation import Correlation
from networks.ltm_transfer import LTM_transfer
class ATnet(nn.Module):
def __init__(se... | 16,091 | 38.153285 | 144 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/aspp.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from networks.deeplab.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm, pretrained):
super(_ASPPModule, self).__... | 4,257 | 38.425926 | 139 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/decoder.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from networks.deeplab.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
class Decoder(nn.Module):
def __init__(self, num_classes, backbone, BatchNorm):
super(Decoder, self).__init__()
if backbone == 'resnet' or bac... | 2,280 | 39.017544 | 107 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/deeplab.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from networks.deeplab.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
from networks.deeplab.aspp import build_aspp
from networks.deeplab.decoder import build_decoder
from networks.deeplab.backbone import build_backbone
class DeepLab(nn.Module):... | 2,493 | 33.638889 | 93 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/backbone/resnet.py | import math
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from networks.deeplab.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None):
super(Bottle... | 9,076 | 36.979079 | 130 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/backbone/drn.py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
from networks.deeplab.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
webroot = 'https://tigress-web.princeton.edu/~fy/drn/models/'
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'drn-c... | 14,657 | 35.372208 | 100 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/backbone/xception.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from networks.deeplab.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
def fixed_padding(inputs, kernel_size, dilation):
kernel_size_effective = kernel_size + (kernel_size - 1) * (dilatio... | 11,561 | 39.145833 | 116 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/backbone/mobilenet.py | import torch
import torch.nn.functional as F
import torch.nn as nn
import math
from networks.deeplab.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
import torch.utils.model_zoo as model_zoo
def conv_bn(inp, oup, stride, BatchNorm):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False... | 5,398 | 34.519737 | 110 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/sync_batchnorm/replicate.py | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.dat... | 3,218 | 35.579545 | 115 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/sync_batchnorm/unittest.py | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from torc... | 834 | 26.833333 | 157 | py |
IVOS-ATNet | IVOS-ATNet-master/networks/deeplab/sync_batchnorm/batchnorm.py | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import torc... | 12,932 | 44.861702 | 116 | py |
IVOS-ATNet | IVOS-ATNet-master/libs/custom_transforms.py | import numpy as np
import torch
class Normalize_ApplymeanvarImage(object):
def __init__(self, mean, var, change_channels=False):
self.mean = mean
self.var = var
self.change_channels = change_channels
def __call__(self, sample):
for elem in sample.keys():
if 'image'... | 1,272 | 25.520833 | 132 | py |
IVOS-ATNet | IVOS-ATNet-master/libs/utils_torch.py | import torch
def combine_masks_with_batch(masks, n_obj, th=0.5, return_as_onehot = False):
""" Combine mask for different objects.
Different methods are the following:
* `max_per_pixel`: Computes the final mask taking the pixel with the highest
probability for every object.
# ... | 1,315 | 34.567568 | 84 | py |
IVOS-ATNet | IVOS-ATNet-master/libs/davis2017_torchdataset.py | from __future__ import division
import os
import numpy as np
import cv2
from libs import utils
from torch.utils.data import Dataset
import json
from PIL import Image
class DAVIS2017(Dataset):
"""DAVIS 2017 dataset constructed using the PyTorch built-in functionalities"""
def __init__(self,
... | 13,111 | 42.417219 | 153 | py |
GraphLoG | GraphLoG-main/pretrain_graphlog.py | import argparse
from loader import MoleculeDataset
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm
import numpy as np
import os, sys
import pdb
import copy
import random
from model import GNN, ProjectNet
from sklearn.metrics import roc_auc_score
... | 22,536 | 43.364173 | 118 | py |
GraphLoG | GraphLoG-main/batch.py | import torch
from torch_geometric.data import Data, Batch
class BatchMasking(Data):
r"""A plain old python object modeling a batch of graphs as one big
(dicconnected) graph. With :class:`torch_geometric.data.Data` being the
base class, all its methods can also be used here.
In addition, single graphs c... | 8,940 | 38.043668 | 190 | py |
GraphLoG | GraphLoG-main/dataloader.py | import torch.utils.data
from torch.utils.data.dataloader import default_collate
from batch import BatchSubstructContext, BatchMasking, BatchAE
class DataLoaderSubstructContext(torch.utils.data.DataLoader):
r"""Data loader which merges data objects from a
:class:`torch_geometric.data.dataset` to a mini-batch.
... | 2,503 | 36.939394 | 89 | py |
GraphLoG | GraphLoG-main/model.py | import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree, softmax
from torch_geometric.nn import global_add_pool, global_mean_pool, global_max_pool, GlobalAttention, Set2Set
import torch.nn.functional as F
from torch_scatter import scatter_add
from torch_geomet... | 15,224 | 36.967581 | 129 | py |
GraphLoG | GraphLoG-main/finetune.py | import argparse
from loader import MoleculeDataset
from torch_geometric.data import DataLoader
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from tqdm import tqdm
import os, sys
import numpy as np
import random
from model i... | 11,223 | 40.724907 | 129 | py |
GraphLoG | GraphLoG-main/splitters.py | import torch
import random
import numpy as np
from itertools import compress
from rdkit.Chem.Scaffolds import MurckoScaffold
from collections import defaultdict
from sklearn.model_selection import StratifiedKFold
# splitter function
def generate_scaffold(smiles, include_chirality=False):
"""
Obtain Bemis-Murc... | 14,949 | 41.351275 | 179 | py |
GraphLoG | GraphLoG-main/util.py | import torch
import copy
import random
import networkx as nx
import numpy as np
from torch_geometric.utils import convert
from loader import graph_data_obj_to_nx_simple, nx_to_graph_data_obj_simple
from rdkit import Chem
from rdkit.Chem import AllChem
from loader import mol_to_graph_data_obj_simple, \
graph_data_ob... | 11,865 | 41.378571 | 100 | py |
GraphLoG | GraphLoG-main/loader.py | import os
import torch
import pickle
import collections
import math
import pandas as pd
import numpy as np
import networkx as nx
from rdkit import Chem
from rdkit.Chem import Descriptors
from rdkit.Chem import AllChem
from rdkit import DataStructs
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect
fr... | 56,150 | 41.250564 | 165 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/run_test_ensemble.py | """Script to launch ensemble on test set results."""
import argparse
import json
from collections import defaultdict
from functools import partial
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np
import pandas as pd
import SimpleITK as sitk # noqa: N813
from absl import logging
from omeg... | 7,072 | 31.296804 | 80 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/run_test.py | """Script to launch evaluation on test sets."""
import argparse
import json
from pathlib import Path
import jax
import numpy as np
from absl import logging
from omegaconf import OmegaConf
from imgx import TEST_SPLIT
from imgx.device import broadcast_to_local_devices
from imgx.exp import Experiment
from imgx.exp.train... | 5,684 | 30.236264 | 80 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/math_util.py | """Module for math functions."""
import jax
import jax.numpy as jnp
def logits_to_mask(x: jnp.ndarray, axis: int) -> jnp.ndarray:
"""Transform logits to one hot mask.
The one will be on the class having largest logit.
Args:
x: logits.
axis: axis of num_classes.
Returns:
One... | 471 | 18.666667 | 61 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/run_valid.py | """Script to launch evaluation on validation tests."""
import argparse
from pathlib import Path
from typing import List
import jax
from absl import logging
from omegaconf import OmegaConf
from imgx import VALID_SPLIT
from imgx.device import broadcast_to_local_devices
from imgx.exp import Experiment
from imgx.exp.trai... | 3,106 | 24.891667 | 74 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/__init__.py | """A Jax-based DL toolkit for biomedical and bioinformatics applications."""
from pathlib import Path
# machine error
EPS = 1.0e-5
NAN_MASK = "nan_mask"
# path for all non-tensorflow-dataset data sets
DIR_DATA = Path("datasets")
# splits
TRAIN_SPLIT = "train"
VALID_SPLIT = "valid"
TEST_SPLIT = "test"
# jax device
... | 657 | 21.689655 | 76 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/run_train.py | """Script to launch training."""
from pathlib import Path
import hydra
import jax
import wandb
from absl import logging
from omegaconf import DictConfig, OmegaConf
from imgx import VALID_SPLIT
from imgx.config import flatten_dict
from imgx.exp import Experiment
from imgx.exp.train_state import get_eval_params_and_sta... | 5,235 | 29.619883 | 76 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/device.py | """Module to handle multi-devices."""
from typing import Optional, Tuple, Union
import chex
import jax
import jax.numpy as jnp
def broadcast_to_local_devices(value: chex.ArrayTree) -> chex.ArrayTree:
"""Broadcasts an object to all local devices.
Args:
value: value to be broadcast.
Returns:
... | 3,095 | 25.689655 | 92 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/metric/area.py | """Metrics to measure foreground area."""
import jax.numpy as jnp
def class_proportion(mask: jnp.ndarray) -> jnp.ndarray:
"""Calculate proportion per class.
Args:
mask: shape = (batch, d1, ..., dn, num_classes).
Returns:
Proportion, shape = (batch, num_classes).
"""
reduce_axes ... | 590 | 27.142857 | 70 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/metric/distribution.py | """Metric functions for probability distributions."""
import jax.numpy as jnp
def normal_kl(
p_mean: jnp.ndarray,
p_log_variance: jnp.ndarray,
q_mean: jnp.ndarray,
q_log_variance: jnp.ndarray,
) -> jnp.ndarray:
"""Compute the KL divergence between two 1D normal distributions.
Although the inp... | 3,097 | 29.07767 | 75 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/metric/dice.py | """Metric functions for image segmentation."""
import jax.numpy as jnp
def dice_score(
mask_pred: jnp.ndarray,
mask_true: jnp.ndarray,
) -> jnp.ndarray:
"""Soft Dice score, larger is better.
Args:
mask_pred: soft mask with probabilities, (batch, ..., num_classes).
mask_true: one hot t... | 1,407 | 28.333333 | 75 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/metric/centroid.py | """Metric centroid distance."""
from typing import Optional, Tuple
import jax.numpy as jnp
def get_coordinate_grid(shape: Tuple[int, ...]) -> jnp.ndarray:
"""Generate a grid with given shape.
This function is not jittable as the output depends on the value of shapes.
Args:
shape: shape of the g... | 3,160 | 28.542056 | 80 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/datasets/augmentation.py | """Image augmentation functions."""
from functools import partial
from typing import Callable, Dict, Sequence
import jax
import numpy as np
from jax import numpy as jnp
from jax.scipy.ndimage import map_coordinates
from omegaconf import DictConfig
from imgx import IMAGE, LABEL
from imgx.datasets import FOREGROUND_RAN... | 12,812 | 26.793926 | 77 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/datasets/iterator.py | """Dataset related classes and functions."""
from functools import partial
from typing import Callable, Dict, Iterator, Optional, Tuple
import jax
import jax.numpy as jnp
import jax.scipy
import jmp
import tensorflow as tf
import tensorflow_datasets as tfds
from absl import logging
from omegaconf import DictConfig
fr... | 8,041 | 31.297189 | 91 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/datasets/util.py | """Util functions for image.
Some are adapted from
https://github.com/google-research/scenic/blob/03735eb81f64fd1241c4efdb946ea6de3d326fe1/scenic/dataset_lib/dataset_utils.py
"""
import functools
import queue
import threading
from typing import Any, Callable, Dict, Generator, Iterable, Tuple
import chex
import jax
im... | 11,835 | 32.247191 | 123 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/diffusion/variance_schedule.py | """Variance schedule for diffusion models."""
from __future__ import annotations
import enum
import numpy as np
from jax import numpy as jnp
class DiffusionBetaSchedule(enum.Enum):
"""Class to define beta schedule."""
LINEAR = enum.auto()
QUADRADIC = enum.auto()
COSINE = enum.auto()
WARMUP10 = ... | 4,844 | 29.093168 | 77 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/diffusion/gaussian_diffusion.py | """Gaussian diffusion related functions.
https://github.com/WuJunde/MedSegDiff/blob/master/guided_diffusion/gaussian_diffusion.py
https://github.com/hojonathanho/diffusion/blob/master/diffusion_tf/diffusion_utils_2.py
"""
import dataclasses
import enum
from typing import Callable, Iterator, Sequence, Tuple, Union
imp... | 27,736 | 33.413151 | 92 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/loss/cross_entropy.py | """Loss functions for classification."""
import jax
import jax.numpy as jnp
import optax
def mean_cross_entropy(
logits: jnp.ndarray,
mask_true: jnp.ndarray,
) -> jnp.ndarray:
"""Cross entropy.
Args:
logits: unscaled prediction, (batch, ..., num_classes).
mask_true: one hot targets, (... | 1,352 | 26.06 | 72 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/loss/dice.py | """Loss functions for image segmentation."""
import jax
import jax.numpy as jnp
def mean_with_background(batch_cls_loss: jnp.ndarray) -> jnp.ndarray:
"""Return average with background class.
Args:
batch_cls_loss: shape (batch, num_classes).
Returns:
Mean loss of shape (1,).
"""
r... | 2,386 | 27.082353 | 75 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/model/unet_3d_slice_time.py | """UNet for segmentation."""
import dataclasses
from typing import Callable, List, Tuple
import haiku as hk
import jax
from jax import numpy as jnp
from imgx.model.basic import instance_norm, sinusoidal_positional_embedding
from imgx.model.unet_3d_slice import Conv2dNormAct, Conv2dPool
@dataclasses.dataclass
class ... | 7,105 | 31.153846 | 95 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/model/unet_3d_time.py | """UNet for segmentation."""
import dataclasses
from typing import Callable, List, Tuple
import haiku as hk
import jax
from jax import numpy as jnp
from imgx.model.basic import instance_norm, sinusoidal_positional_embedding
from imgx.model.unet_3d import Conv3dNormAct, Conv3dPool
@dataclasses.dataclass
class TimeCo... | 6,438 | 30.10628 | 95 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/model/unet_3d_slice.py | """UNet for segmentation."""
import dataclasses
from typing import Callable, List, Tuple
import haiku as hk
import jax
from jax import numpy as jnp
from imgx.model.basic import instance_norm
@dataclasses.dataclass
class Conv2dNormAct(hk.Module):
"""Block with conv2d-norm-act."""
out_channels: int
kerne... | 7,387 | 27.635659 | 85 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/model/unet_3d.py | """UNet for segmentation."""
import dataclasses
from typing import Callable, List, Tuple
import haiku as hk
import jax
from jax import numpy as jnp
from imgx.model.basic import instance_norm
@dataclasses.dataclass
class Conv3dNormAct(hk.Module):
"""Block with conv3d-norm-act."""
out_channels: int
kerne... | 6,811 | 26.691057 | 85 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/model/basic.py | """Basic functions and modules."""
import haiku as hk
from jax import numpy as jnp
def layer_norm(x: jnp.ndarray) -> jnp.ndarray:
"""Applies a unique LayerNorm at the last axis.
Args:
x: input
Returns:
Normalised input.
"""
return hk.LayerNorm(axis=-1, create_scale=True, create_o... | 2,088 | 26.486842 | 74 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/exp/train_state.py | """Training state and checkpoints."""
import pickle
from pathlib import Path
from typing import Optional, Tuple
import chex
import haiku as hk
import jax
import jax.numpy as jnp
import jmp
import numpy as np
import optax
from imgx.device import broadcast_to_local_devices, get_first_replica_values
CHECKPOINT_ATTRS = ... | 6,560 | 30.695652 | 80 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/exp/optim.py | """Module for optimization."""
import logging
from typing import Tuple
import jax
import jax.numpy as jnp
import optax
from omegaconf import DictConfig
def ema_update(
ema_value: jnp.ndarray,
current_value: jnp.ndarray,
decay: float,
step: jnp.ndarray,
) -> jnp.ndarray:
"""Implements exponential ... | 3,308 | 30.216981 | 79 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/exp/experiment.py | """Module for launching experiments."""
import logging
from functools import partial
from pathlib import Path
from typing import Callable, Dict, Mapping, Optional, Tuple, Union
import chex
import haiku as hk
import jax
import jax.numpy as jnp
import jmp
import optax
import tensorflow as tf
from omegaconf import DictCo... | 13,642 | 30.801865 | 79 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/exp/loss.py | """Module for building models and losses."""
from typing import Callable, Dict, Tuple
import haiku as hk
import jax
import jax.numpy as jnp
from omegaconf import DictConfig
from imgx import IMAGE, LABEL
from imgx.datasets import NUM_CLASSES_MAP
from imgx.diffusion.gaussian_diffusion import (
DiffusionModelOutputT... | 11,245 | 30.858357 | 80 | py |
ImgX-DiffSeg | ImgX-DiffSeg-main/imgx/exp/model.py | """Module for building models."""
import haiku as hk
from omegaconf import DictConfig
from imgx.datasets import IMAGE_SHAPE_MAP, NUM_CLASSES_MAP
from imgx.diffusion.gaussian_diffusion import (
DiffusionBetaSchedule,
DiffusionModelOutputType,
DiffusionModelVarianceType,
DiffusionSpace,
GaussianDiffu... | 3,969 | 32.644068 | 75 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.