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 |
|---|---|---|---|---|---|---|
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/module_serde_test.py | # third party
import pytest
import torch as th
# syft absolute
import syft as sy
from syft.lib.python.collections import OrderedDict
@pytest.mark.slow
def test_linear_module() -> None:
alice = sy.VirtualMachine()
alice_client = alice.get_root_client()
# Linear
fc = th.nn.Linear(4, 2)
# send
... | 1,305 | 21.912281 | 56 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/weight_bias_test.py | # third party
import pytest
import torch
# syft absolute
import syft as sy
input_list = [torch.nn.Linear(100, 10)]
@pytest.mark.parametrize("target_layer", input_list)
def test_weights_and_bias(
root_client: sy.VirtualMachineClient, target_layer: torch.nn.Module
) -> None:
original_bias = target_layer.bias
... | 1,011 | 28.764706 | 71 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/device_test.py | # stdlib
from typing import Any
# third party
import pytest
import torch as th
# syft absolute
import syft as sy
from syft.core.common.uid import UID
from syft.lib.python import String
def test_device() -> None:
device = th.device("cuda")
assert device.type == "cuda"
assert device.index is None
def te... | 1,037 | 24.317073 | 87 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/tensor_util_test.py | # third party
import pytest
import torch as th
# syft absolute
import syft as sy
@pytest.fixture(scope="function")
def tensor() -> th.Tensor:
t1 = th.tensor([[1.0, -1.0], [1.0, -1.0]])
scale, zero_point = 1e-4, 2
dtype = th.qint32
tensor = th.quantize_per_tensor(t1, scale, zero_point, dtype)
retu... | 771 | 29.88 | 83 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/parameter_test.py | # stdlib
import gc
# third party
import pytest
import torch as th
# syft absolute
import syft as sy
@pytest.mark.slow
def test_parameter_vm_remote_operation(
node: sy.VirtualMachine, client: sy.VirtualMachineClient
) -> None:
x = th.nn.Parameter(th.randn(3, 3))
xp = x.send(client, pointable=False)
... | 1,967 | 20.626374 | 84 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/client_torch_test.py | # stdlib
from typing import List as TypeList
from typing import Type as TypeType
# third party
import pytest
import torch as th
# syft absolute
import syft as sy
@pytest.mark.slow
def test_torch_function(client: sy.VirtualMachineClient) -> None:
x = th.tensor([[-0.1, 0.1], [0.2, 0.3]])
ptr_x = x.send(client... | 990 | 24.410256 | 65 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/tensor/grad_test.py | # third party
import torch
# syft absolute
import syft as sy
def torch_grad_test(client: sy.VirtualMachineClient) -> None:
x = client.torch.Tensor([[1, 1], [1, 1]])
x.requires_grad = True
gt = client.torch.Tensor([[1, 1], [1, 1]]) * 16 - 0.5
loss_fn = client.torch.nn.MSELoss()
v = x + 2
y =... | 516 | 21.478261 | 77 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torch/tensor/tensor_remote_and_serde_test.py | # stdlib
import gc
# third party
import pytest
import torch as th
# syft absolute
import syft as sy
from syft.core.node.common.service.auth import AuthorizationException
@pytest.mark.slow
def test_torch_remote_tensor_register(
node: sy.VirtualMachine, client: sy.VirtualMachineClient
) -> None:
"""Test if se... | 2,785 | 23.017241 | 94 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/python/list/list_serde_test.py | # third party
import torch as th
# syft absolute
import syft as sy
from syft.lib.python.list import List
from syft.proto.lib.python.list_pb2 import List as List_PB
def test_list_serde() -> None:
t1 = th.tensor([1, 2])
t2 = th.tensor([1, 3])
syft_list = List([t1, t2])
serialized = syft_list._object2... | 1,059 | 24.853659 | 69 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/python/slice/slice_serde_test.py | # third party
import torch as th
# syft absolute
import syft as sy
from syft.lib.python.slice import Slice
from syft.proto.lib.python.slice_pb2 import Slice as Slice_PB
def test_slice_serde() -> None:
syft_slice = Slice(1, 3, -1)
serialized = syft_slice._object2proto()
assert isinstance(serialized, Slic... | 1,462 | 23.79661 | 61 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/python/dict/dict_serde_test.py | # stdlib
from collections import UserDict
# third party
import pytest
import torch as th
# syft absolute
import syft as sy
from syft.core.common.uid import UID
from syft.lib.python.dict import Dict
from syft.lib.python.int import Int
from syft.lib.python.string import String
from syft.proto.lib.python.dict_pb2 import... | 2,602 | 28.247191 | 97 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/python/collections/ordered_dict/ordered_dict_serde_test.py | # stdlib
from collections import OrderedDict as PyOrderectDict
# third party
import pytest
import torch as th
# syft absolute
import syft as sy
from syft.core.common.uid import UID
from syft.lib.python.collections.ordered_dict import OrderedDict
from syft.lib.python.int import Int
from syft.lib.python.string import S... | 2,475 | 28.129412 | 72 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/xgboost/model_test.py | # stdlib
from sys import platform
# third party
import pytest
# syft absolute
import syft as sy
try:
np = pytest.importorskip("numpy")
xgb = pytest.importorskip("xgboost")
sy.load("xgboost")
sy.load("numpy")
_SKIP_XGB = platform == "darwin"
except Exception:
_SKIP_XGB = True
# this current... | 2,945 | 29.371134 | 88 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/torchvision/allowlist_test.py | # stdlib
import json
import os
from os import path
from typing import Any
from typing import Dict
from typing import Union
# third party
from packaging import version
import pytest
import torch
import torchvision as tv
# syft absolute
import syft as sy
from syft.lib.torchvision.allowlist import allowlist
TORCHVISION... | 2,946 | 27.892157 | 80 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/pytorch_lightning/boring_test.py | # stdlib
from typing import Any
from typing import List
from typing import Optional
# third party
import pytest
import torch
# syft absolute
import syft as sy
SyTensorProxyType = Any # Union[torch.Tensor, Any]
# cant use lib_ast during test search time
DataLoaderPointerType = Any # sy.lib_ast.torch.utils.data.Data... | 2,636 | 30.771084 | 88 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/tensor/tensorbase_test.py | # stdlib
from typing import Any
from typing import List
# third party
import torch
# syft absolute
from syft.lib.tensor.tensorbase import DataTensor
from syft.lib.tensor.tensorbase import FloatTensor
from syft.lib.tensor.tensorbase import SyftTensor
def get_children_types(t: Any, types: Any = None) -> List[Any]:
... | 2,678 | 30.151163 | 87 | py |
PySyft | PySyft-master/packages/syft/tests/syft/lib/sympc/sympc_test.py | # third party
import pytest
import torch as th
# syft absolute
import syft as sy
sympc = pytest.importorskip("sympc")
Session = sympc.session.Session
SessionManager = sympc.session.SessionManager
MPCTensor = sympc.tensor.MPCTensor
sy.load("sympc")
@pytest.mark.asyncio
@pytest.mark.vendor(lib="sympc")
def test_load... | 798 | 23.96875 | 85 | py |
PySyft | PySyft-master/packages/syft/docs/conf.py | # -*- coding: utf-8 -*-
#
# 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 have a default; values that are commented out
# serve to show the default.
# stdlib
impor... | 10,687 | 31.096096 | 84 | py |
PySyft | PySyft-master/packages/grid/apps/worker/src/main/core/database/store_disk.py | # stdlib
from copy import deepcopy
from io import StringIO
from json import loads
from os.path import getsize
from typing import Iterable
from typing import Optional
# third party
from flask import current_app as app
from loguru import logger
import numpy as np
import pandas as pd
from syft import deserialize
from syf... | 8,985 | 32.405204 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/worker/src/main/core/services/transfer_service.py | # stdlib
import secrets
from threading import Thread
import traceback
from typing import List
from typing import Type
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import VerifyKey
from syft.core.common.message import ImmediateSyftMessageWithReply
from syft.core.common.s... | 3,826 | 31.159664 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/worker/src/main/core/services/tensor_service.py | # stdlib
import secrets
from typing import List
from typing import Type
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import SigningKey
from nacl.signing import VerifyKey
# syft relative
from syft.core.common.group import VerifyAll
from syft.core.common.message import I... | 7,678 | 29.351779 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/network/src/main/core/database/store_disk.py | # stdlib
from copy import deepcopy
from io import StringIO
from json import loads
from os.path import getsize
from typing import Iterable
from typing import Optional
# third party
from flask import current_app as app
from loguru import logger
import numpy as np
import pandas as pd
from syft import deserialize
from syf... | 8,985 | 32.405204 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/network/src/main/core/services/transfer_service.py | # stdlib
import secrets
from threading import Thread
import traceback
from typing import List
from typing import Type
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import VerifyKey
from syft.core.common.message import ImmediateSyftMessageWithReply
from syft.core.common.s... | 3,630 | 30.573913 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/network/src/main/core/services/tensor_service.py | # stdlib
import secrets
from typing import List
from typing import Type
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import SigningKey
from nacl.signing import VerifyKey
# syft relative
from syft.core.common.group import VerifyAll
from syft.core.common.message import I... | 7,678 | 29.351779 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/database/store_disk.py | # stdlib
from typing import Iterable
from typing import KeysView
from typing import Optional
from typing import ValuesView
# third party
from flask import current_app as app
from nacl.encoding import HexEncoder
from nacl.signing import VerifyKey
import syft
from syft.core.common.group import VERIFYALL
from syft.core.c... | 4,762 | 30.543046 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/database/bin_storage/bin_obj.py | # third party
from syft import deserialize
from syft import serialize
from syft.proto.lib.pandas.frame_pb2 import PandasDataFrame as PandasDataFrame_PB
from syft.proto.lib.torch.tensor_pb2 import TensorProto as TensorProto_PB
# grid relative
from .. import BaseModel
from .. import db
bin_to_proto = {
TensorProto_... | 1,414 | 29.106383 | 81 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/model_centric/cycles/cycle_manager.py | # stdlib
from datetime import datetime
from datetime import timedelta
from functools import reduce
import json
import logging
# third party
import torch as th
# grid relative
from ...exceptions import CycleNotFoundError
from ...manager.database_manager import DatabaseManager
from ..models import model_manager
from ..... | 12,498 | 35.020173 | 139 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/model_centric/syft_assets/plan.py | # grid relative
from ...database import BaseModel
from ...database import db
class Plan(BaseModel):
"""Plan table that represents Syft Plans.
Columns:
id (Integer, Primary Key): Plan ID.
name (String): Plan name.
value (Binary): String (List of operations)
value_ts (Binary): ... | 1,052 | 31.90625 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/model_centric/syft_assets/protocol.py | # grid relative
from ...database import BaseModel
from ...database import db
class Protocol(BaseModel):
"""Protocol table that represents Syft Protocols.
Columns:
id (Integer, Primary Key): Protocol ID.
name (String): protocol name.
value: String (List of operations)
value_ts... | 905 | 31.357143 | 94 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/services/transfer_service.py | # stdlib
import secrets
from threading import Thread
import traceback
from typing import List
from typing import Type
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import VerifyKey
from syft.core.common.message import ImmediateSyftMessageWithReply
from syft.core.common.s... | 3,630 | 30.573913 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/services/tensor_service.py | # stdlib
import secrets
from typing import List
from typing import Type
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import SigningKey
from nacl.signing import VerifyKey
# syft relative
from syft.core.common.group import VerifyAll
from syft.core.common.message import I... | 7,678 | 29.351779 | 87 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/core/datasets/dataset_ops.py | # stdlib
from copy import deepcopy
import csv
from io import StringIO
import tarfile
from typing import Iterable
from typing import Optional
# third party
from nacl.encoding import HexEncoder
from nacl.signing import SigningKey
import numpy as np
import pandas as pd
from pandas import DataFrame
from syft.core.common.g... | 7,525 | 30.889831 | 88 | py |
PySyft | PySyft-master/packages/grid/apps/domain/src/main/routes/model_centric/routes.py | # stdlib
import io
import json
import logging
from math import floor
from random import random
# third party
from flask import Response
from flask import current_app
from flask import render_template
from flask import request
from flask import send_file
import numpy as np
from requests_toolbelt import MultipartEncoder... | 20,059 | 37.875969 | 159 | py |
PySyft | PySyft-master/packages/grid/apps/domain/tests/test_database/test_disk_store.py | # stdlib
from json import dumps
from json import loads
# third party
import pytest
import numpy as np
import torch as th
from flask import current_app as app
from syft.core.common.uid import UID
from sqlalchemy.exc import NoResultFound
from syft.core.store.storeable_object import StorableObject
from src.main.core.dat... | 9,583 | 28.763975 | 82 | py |
MRNet | MRNet-master/src/criteria.py | import torch
import torch.nn.functional as F
def calculate_acc(output, target):
pred = output.data.max(1)[1]
correct = pred.eq(target.data).cpu().sum().numpy()
return correct * 100.0 / target.size()[0]
def calculate_correct(output, target):
pred = output.data.max(1)[1]
correct = pred.eq(target.d... | 902 | 30.137931 | 98 | py |
MRNet | MRNet-master/src/train.py | import argparse
import os
import sys
import time
import numpy as np
import torch
from trainer import Trainer
parser = argparse.ArgumentParser(description='baseline')
parser.add_argument('--data_dir', type=str)
parser.add_argument('--exp_dir', type=str, default='./experiments')
parser.add_argument('--exp_name', type=... | 3,987 | 35.587156 | 90 | py |
MRNet | MRNet-master/src/trainer.py | import os
import pickle
import shutil
import numpy as np
import torch
import torch.optim as optim
import yaml
from torch import nn
from tqdm import tqdm
import criteria
from data.data_utils import get_data
from networks.mrnet import MRNet
from report_acc_regime import init_acc_regime, update_acc_regime
torch.backend... | 20,099 | 41.948718 | 213 | py |
MRNet | MRNet-master/src/networks/mrnet.py | import torch
import torch.nn.functional as F
from .blocks import *
def conv1x1(in_channel, out_channel, stride=1):
return nn.Conv2d(in_channel, out_channel, kernel_size=1, stride=stride, bias=False)
def conv3x3(in_channel, out_channel, stride=1):
return nn.Conv2d(in_channel, out_channel, kernel_size=3, str... | 20,978 | 48.131148 | 119 | py |
MRNet | MRNet-master/src/networks/blocks.py | import torch.nn as nn
def conv1x1(in_channel, out_channel, stride=1):
return nn.Conv2d(in_channel, out_channel, kernel_size=1, stride=stride, bias=False)
def conv3x3(in_channel, out_channel, stride=1):
return nn.Conv2d(in_channel, out_channel, kernel_size=3, stride=stride, padding=1, bias=False)
class Res... | 1,545 | 32.608696 | 98 | py |
MRNet | MRNet-master/src/data/raven_dataset.py | import os
import random
import glob
import numpy as np
import skimage.transform
import skimage.io
import torch
from torch.utils.data import Dataset
import warnings
class ToTensor(object):
def __call__(self, sample):
to_tensor(sample)
def to_tensor(sample):
return torch.tensor(sample, dtype=torch.f... | 7,020 | 35.952632 | 114 | py |
MRNet | MRNet-master/src/data/pgm_dataset.py | import os
import random
import glob
import numpy as np
import skimage.transform
import skimage.io
import torch
from torch.utils.data import Dataset
import warnings
class ToTensor(object):
def __call__(self, sample):
to_tensor(sample)
def to_tensor(sample):
return torch.tensor(sample, dtype=torch.f... | 7,995 | 38.004878 | 114 | py |
MRNet | MRNet-master/src/data/data_utils.py | import os
import random
import torch
import warnings
import torch.utils.data
def get_data_path(data_root, dataname: str):
if data_root is None:
return None # using cached data
if os.path.isdir(os.path.join(data_root, dataname)):
return os.path.join(data_root, dataname)
if os.path.isdir(o... | 2,461 | 41.448276 | 114 | py |
LaBo | LaBo-main/main.py | import os
import utils
import json
import argparse
import pytorch_lightning as pl
import torch as th
import numpy as np
from sklearn.metrics import confusion_matrix
import random
proj_name = 'Food-Fixed-Seed'
check_interval = 10
def linear_probe_sklearn_main(cfg):
"Adapted from: https://github.com/KaiyangZhou/CoO... | 15,353 | 42.868571 | 148 | py |
LaBo | LaBo-main/data_lp.py | import utils
import random
import torch as th
from PIL import Image
from pathlib import Path
import pytorch_lightning as pl
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from torchvision.transforms import InterpolationMode
try:
... | 7,223 | 35.301508 | 99 | py |
LaBo | LaBo-main/utils.py | import mmcv
from mmcv import Config
import os
import os.path as osp
import time
import glob
import argparse
import pickle
import torch
import tqdm
import numpy as np
import clip
from PIL import Image
"""
Start an experiment
"""
def pre_exp(cfg_file, work_dir):
"""
Load the config from cfg_file, create a folder... | 5,311 | 29.528736 | 105 | py |
LaBo | LaBo-main/data.py | """
This is a cleaned version of data loader for new interfaces;
The datamodule here handles all data processing including concept selection.
For the model, it only loads data processed and save in data_root.
"""
import torch as th
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pytorch_ligh... | 15,970 | 39.535533 | 212 | py |
LaBo | LaBo-main/models/select_concept/select_algo.py | import torch as th
import random
from tqdm import tqdm
import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
def get_tSNE_embed(x):
tSNE = TSNE(n_components=2, init='random')
return tSNE.fit_transform(x)
def clip_score(img_feat, concept_feat, n_shots, num_images_per_class):
... | 7,542 | 39.12234 | 167 | py |
LaBo | LaBo-main/models/linear_probe/linear_probe.py | """
Linear probing following example in https://github.com/openai/CLIP
"""
import clip
import torch
import torch.nn as nn
import torch.nn.functional as F
import pickle
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
import numpy as np
import pytorch_lightning as pl
from pytorch_lightning.callback... | 5,986 | 34.636905 | 94 | py |
LaBo | LaBo-main/models/asso_opt/asso_opt.py | import torchmetrics
import wandb
import torch as th
import pytorch_lightning as pl
import torch.nn.functional as F
import numpy as np
from pathlib import Path
class AssoConcept(pl.LightningModule):
def init_weight_concept(self, concept2cls):
self.init_weight = th.zeros((self.cfg.num_cls, len(self.select_i... | 8,883 | 37.293103 | 124 | py |
LaBo | LaBo-main/cfg/linear_probe/ImageNet.py | steps = 8
n_runs = 1
img_path = 'datasets/ImageNet/images/'
data_root = 'exp/linear_probe/ImageNet'
img_split_path = 'datasets/ImageNet/splits'
num_cls = 1000
unfreeze_clip = False
paper = True
clip_model='ViT-B/32' #['RN50', 'RN101', 'RN50x4', 'RN50x16', 'RN50x64', 'ViT-B/32', 'ViT-B/16', 'ViT-L/14', 'ViT-L/14@336px... | 14,762 | 67.032258 | 126 | py |
SPAA | SPAA-main/src/python/main.py | """
Set up ProCams and capture data
"""
import os
from os.path import join, abspath
import cv2 as cv
import numpy as np
import torch
from omegaconf import DictConfig, OmegaConf
import classifier
import utils as ut
import matplotlib.pyplot as plt
from classifier import query_multi_classifiers
from img_proc import checke... | 12,495 | 54.292035 | 217 | py |
SPAA | SPAA-main/src/python/reproduce_paper_results.py | """
Script to reproduce SPAA (IEEE VR'22) paper/supplementary results on the benchmark dataset (13 setups).
1. We start by setting the training environment to GPU (if any).
2. Setups are listed in 'setup_list', more setups can be found in SPAA/data/setups folder.
3. You need to start visdom first.
4. Run the script by... | 3,043 | 38.532468 | 151 | py |
SPAA | SPAA-main/src/python/test_digital_one_pixel_attack.py | """
Test digital one-pixel attacks
"""
import os
from os.path import join, abspath
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import torch
from classifier import Classifier, load_imagenet_labels
from one_pixel_attacker import DigitalOnePixelAttacker
import utils as ut
# %% Digital-based one-pixel attack
# set which GPU... | 1,784 | 37.804348 | 150 | py |
SPAA | SPAA-main/src/python/utils.py | '''
Useful helper functions
'''
import os
from os.path import join, abspath
import sys
import warnings
import platform
import math
import random
import pandas as pd
import skimage.util
import numpy as np
import cv2 as cv
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms
f... | 29,434 | 38.299065 | 262 | py |
SPAA | SPAA-main/src/python/classifier.py | """
A wrapper for image classification models
"""
import torch
import torch.nn.functional as F
from torch.hub import load_state_dict_from_url
from torchvision import models, transforms as T
from img_proc import resize, center_crop as cc, expand_4d
# A general classifier class, can be initialized by model name
class C... | 5,095 | 42.555556 | 169 | py |
SPAA | SPAA-main/src/python/img_proc.py | import sys
import numpy as np
import cv2 as cv
import torch
import torch.nn.functional as F
import copy
import torchvision.transforms
from PIL import ImageFont, ImageDraw, ImageOps
from skimage.filters import threshold_multiotsu
def threshold_im(im_in, compensation=False):
# find the direct light binary mask for... | 7,753 | 36.100478 | 134 | py |
SPAA | SPAA-main/src/python/pytorch_tps.py | # Obtained from https://github.com/cheind/py-thin-plate-spline/blob/master/thinplate/pytorch.py
# ============================================================
# MIT License
#
# Copyright (c) 2018 Christoph Heindl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and ass... | 7,316 | 30.813043 | 99 | py |
SPAA | SPAA-main/src/python/train_network.py | '''
PCNet and CompenNet++ training functions
'''
import os
from os.path import join
import warnings
import numpy as np
import cv2 as cv
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import time
import pytorch_ssim
import models
from img_proc im... | 37,120 | 49.573569 | 173 | py |
SPAA | SPAA-main/src/python/models.py | import numpy as np
import torch, math
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import copy
import pytorch_tps
# CompenNet
class CompenNet(nn.Module):
def __init__(self):
super(CompenNet, self).__init__()
self.name = 'CompenNet'
self.relu = nn.ReLU(... | 13,630 | 38.395954 | 158 | py |
SPAA | SPAA-main/src/python/projector_based_attack.py | """
Useful functions for projector-based adversarial attack
"""
import os
from os.path import join
import numpy as np
import cv2 as cv
import pandas as pd
import torch
from omegaconf import DictConfig
from torchvision.utils import make_grid
from train_network import load_setup_info, train_eval_pcnet, train_eval_compenn... | 35,019 | 55.850649 | 209 | py |
SPAA | SPAA-main/src/python/perc_al/__init__.py | # Original code obtained from https://github.com/ZhengyuZhao/PerC-Adversarial
# Zhengyu Zhao, Zhuoran Liu, Martha Larson, "Towards Large yet Imperceptible Adversarial Image Perturbations with Perceptual Color Distance", CVPR 2020.
# Extended to work for SPAA and PerC-AL+CompenNet++
# from typing import Tuple, Optional
... | 13,448 | 51.535156 | 200 | py |
SPAA | SPAA-main/src/python/perc_al/differential_color_functions.py | """
Code obtrained from https://github.com/ZhengyuZhao/PerC-Adversarial
Zhengyu Zhao, Zhuoran Liu, Martha Larson, "Towards Large yet Imperceptible Adversarial Image Perturbations with Perceptual Color Distance", CVPR 2020.
"""
import numpy as np
import torch
from img_proc import expand_4d
def rgb2xyz(rgb_image, dev... | 6,393 | 32.47644 | 150 | py |
SPAA | SPAA-main/src/python/one_pixel_attacker/__init__.py | '''
Digital and projector-based One-pixel adversarial attacker
code modified from: https://github.com/Hyperparticle/one-pixel-attack-keras/blob/92c8506acdcb7807c46dd7404c214ebaaa3d26ad/attack.py
'''
# Helper functions
import os
import torch
import numpy as np
import cv2 as cv
import pandas as pd
from scipy.optimize im... | 12,208 | 48.832653 | 165 | py |
SPAA | SPAA-main/src/python/pytorch_ssim/__init__.py | # Author: Po-Hsun Su (https://github.com/Po-Hsun-Su/pytorch-ssim)
# Modified by: Bingyao Huang
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from math import exp
def gaussian(window_size, sigma):
gauss = torch.Tensor(
[exp(-(x - window_size // 2) ** 2 / float(2 * sigma *... | 3,964 | 35.712963 | 114 | py |
m3ae_public | m3ae_public-master/m3ae/jax_utils.py | import os
import time
from typing import Any, Mapping, Text, Tuple, Union
from functools import partial
import dill
import flax
import jax
import jax.numpy as jnp
import numpy as np
from absl import logging
from flax import jax_utils
class JaxRNG(object):
""" A convenient stateful Jax RNG wrapper. Can be used to... | 7,059 | 31.237443 | 105 | py |
m3ae_public | m3ae_public-master/m3ae/mae_main.py | import dataclasses
import pprint
from functools import partial
import absl.app
import absl.flags
import flax
import jax
import jax.numpy as jnp
import numpy as np
import optax
import torch
import wandb
from flax import linen as nn
from flax.jax_utils import prefetch_to_device
from flax.training.train_state import Tr... | 12,141 | 35.136905 | 93 | py |
m3ae_public | m3ae_public-master/m3ae/utils.py | import os
import pprint
import random
import tempfile
import time
import uuid
from copy import copy
from socket import gethostname
import absl.flags
import cloudpickle as pickle
import gcsfs
import numpy as np
import wandb
from absl import logging
from ml_collections import ConfigDict
from ml_collections.config_dict i... | 7,097 | 28.823529 | 94 | py |
m3ae_public | m3ae_public-master/m3ae/model.py | from typing import Callable, Optional, Any
import flax
import flax.linen as nn
from flax.training.train_state import TrainState
import jax
import jax.numpy as jnp
from ml_collections import ConfigDict
from ml_collections.config_dict import config_dict
from functools import partial
def mask_union(mask1, mask2):
r... | 32,528 | 32.363077 | 104 | py |
m3ae_public | m3ae_public-master/m3ae/data.py | import threading
from io import BytesIO
from queue import Queue
import gcsfs
import h5py
import numpy as np
import skimage.io
import torch
import torchvision
import transformers
from ml_collections import ConfigDict
from PIL import Image
from skimage.color import gray2rgb, rgba2rgb
from timm.data import create_transfo... | 18,175 | 35.352 | 138 | py |
m3ae_public | m3ae_public-master/m3ae/vqgan.py | # This file is taken from https://github.com/google-research/maskgit with modifications.
# Copyright 2022 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... | 19,158 | 33.2125 | 123 | py |
m3ae_public | m3ae_public-master/m3ae/finetune_main.py | from typing import Callable, Optional, Any
import dataclasses
import os
import pprint
from functools import partial
from copy import deepcopy
import absl.app
import absl.flags
import flax
import jax
import jax.numpy as jnp
import numpy as np
import optax
import torch
import wandb
from flax import linen as nn
from fla... | 13,678 | 34.437824 | 120 | py |
m3ae_public | m3ae_public-master/m3ae/linear_main.py | from typing import Callable, Optional, Any
import dataclasses
import os
import pprint
from functools import partial
import absl.app
import absl.flags
import flax
import jax
import jax.numpy as jnp
import numpy as np
import optax
import torch
import wandb
from flax import linen as nn
from flax.jax_utils import prefetc... | 12,649 | 34.434174 | 93 | py |
m3ae_public | m3ae_public-master/m3ae/m3ae_main.py | import dataclasses
import pprint
from functools import partial
import absl.app
import absl.flags
import flax
import jax
import jax.numpy as jnp
import numpy as np
import optax
import torch
import wandb
from flax import linen as nn
from flax.jax_utils import prefetch_to_device
from tqdm.auto import tqdm, trange
from ... | 16,249 | 36.96729 | 108 | py |
PQsim | PQsim-master/pqsim/experimental/jaxQC.py | import jax.numpy as jnp
from jax import jit
import numpy as np
def do_circ(nq, names, qargs, parms, vec):
idx_parm = 0
idx_arr = jnp.arange(2**nq, dtype=int)
for idx, n in enumerate(names):
if n=='cz':
q0 = qargs[idx] % nq
q1 = ((qargs[idx] - q0)//nq) % nq
vec = ... | 2,441 | 26.438202 | 94 | py |
BDF | BDF-main/utils_filereader.py | import argparse
import json
import os
import pandas as pd
import time
import torch
import numpy as np
# ==============================================================================
# Utility Functions
# ==============================================================================
def format_config(args):
"""
... | 5,167 | 36.449275 | 142 | py |
BDF | BDF-main/query_methods.py | import argparse
import json
import os
import pandas as pd
import time
import torch
import numpy as np
from bhmtorch_cpu import BHM_VELOCITY_PYTORCH
from utils_filereader import read_frame_velocity
from utils_metrics import calc_scores_velocity
def load_mdl(args, path):
"""
@param path (str): path relative to... | 7,587 | 37.714286 | 124 | py |
BDF | BDF-main/train_methods.py | import argparse
import json
import os
import pandas as pd
import time
import torch
import numpy as np
from bhmtorch_cpu import BHM_VELOCITY_PYTORCH
def save_mdl(args, model, path, train_time):
"""
@param model: BHM Module to save
@param path (str): path relative to the mdl folder to save to
"""
md... | 2,897 | 31.931818 | 110 | py |
BDF | BDF-main/bhmtorch_cpu.py | """
# 3D Bayesian Dynamic Fields with pytorch
# Ransalu Senanayake, Jason Zheng, and Kyle Hatch
"""
import math
import numpy as np
import torch
import statsmodels.api as sm
from kernel import rbf_kernel_conv, rbf_kernel_wasserstein, rbf_kernel
class BHM_VELOCITY_PYTORCH:
def __init__(self, alpha=None, beta=None, ... | 11,871 | 39.657534 | 226 | py |
BDF | BDF-main/spatun.py | import argparse
import json
import os
import pandas as pd
import time
import torch
import numpy as np
import train_methods
import query_methods
import utils_filereader
from plot_methods import BHM_PLOTTER
def load_query_data(path):
"""
@param path (str): path relative to query_data folder to save data
""... | 8,424 | 51.329193 | 166 | py |
BDF | BDF-main/plot_methods.py | import argparse
import json
import os
import pandas as pd
import plotly
import plotly.graph_objects as go
import time
import torch
#vivian
import plotly.figure_factory as ff
import trimesh
import time
import torch
import numpy as np
from skimage import measure
import utils_filereader
from plotly.subplots import make_... | 14,818 | 42.078488 | 161 | py |
BDF | BDF-main/kernel.py | import math
import numpy as np
import torch
from sklearn.metrics.pairwise import euclidean_distances, rbf_kernel as sklearn_kernel
DEFAULT_DEVICE = torch.device("cpu")
# ==============================================================================
# Kernel Method Implementations using PyTorch
# ====================... | 2,832 | 36.773333 | 140 | py |
unlikelihood_training | unlikelihood_training-main/custom/baseline_cross_entropy.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
import torch.nn.functional as F
from fairseq import utils
from fairseq.criterions import FairseqCriterion, ... | 3,557 | 37.673913 | 111 | py |
unlikelihood_training | unlikelihood_training-main/custom/sequence_penalty_loss.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
import torch
from collections import defaultdict
from fairseq import utils
from fairseq.criterions import F... | 4,763 | 41.535714 | 124 | py |
unlikelihood_training | unlikelihood_training-main/custom/sequence_generator.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
import torch
import torch.nn.functional as F
class SequenceGenerator(object):
def __init__(self, tgt_d... | 6,709 | 42.012821 | 141 | py |
unlikelihood_training | unlikelihood_training-main/custom/candidate_penalty_ce_loss.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
import torch.nn.functional as F
import torch
from fairseq import utils
from fairseq.criterions import Fairs... | 4,827 | 38.252033 | 111 | py |
unlikelihood_training | unlikelihood_training-main/custom/evaluate_utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
from fairseq import checkpoint_utils, options, progress_bar, tasks, utils
from fairseq.meters import Stopwatc... | 6,679 | 37.171429 | 168 | py |
unlikelihood_training | unlikelihood_training-main/custom/metrics.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
import torch
import torch.nn.functional as F
from collections import defaultdict, Counter
from fairse... | 9,037 | 44.878173 | 156 | py |
unlikelihood_training | unlikelihood_training-main/custom/language_modeling_with_generation.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from fairseq.tasks import register_task
from fairseq.tasks.language_modeling import LanguageModelingTask
from fairseq.cus... | 5,069 | 44.675676 | 121 | py |
unlikelihood_training | unlikelihood_training-main/custom/gpt2/run_gpt2.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import logging
import json
import os
import re
import random
import torch
import torch.nn.functional as F... | 22,458 | 44.280242 | 136 | py |
TESAR-CDE | TESAR-CDE-main/main.py | # Adapted from: https://github.com/seedatnabeel/TE-CDE/blob/main/main.py
import argparse
import os
import traceback
import wandb
import numpy as np
import torch
from scipy.stats import sem
from src.utils.cancer_simulation import get_cancer_sim_data
from src.utils.data_utils import process_data, read_from_file, write_... | 11,489 | 42.688213 | 192 | py |
TESAR-CDE | TESAR-CDE-main/trainer.py | # Adapted from: https://github.com/seedatnabeel/TE-CDE/blob/main/trainer.py
import argparse
import logging
import os
import pickle
from copy import deepcopy
import numpy as np
import torch
import torch.nn as nn
import torchcde
from torch.nn import functional as F
from tqdm import tqdm
import matplotlib.pyplot as plt
... | 34,276 | 41.265105 | 154 | py |
TESAR-CDE | TESAR-CDE-main/src/models/CDE_model.py | # Adapted from: https://github.com/patrick-kidger/torchcde
# Adapted from: https://github.com/seedatnabeel/TE-CDE/blob/main/src/models/CDE_model.py
import logging
import torch
import torch.nn as nn
import torchcde
######################
# A CDE model is defined as
#
# z_t = z_0 + \int_0^t f_\theta(z_s) dX_s
#
# Whe... | 8,665 | 37.6875 | 117 | py |
TESAR-CDE | TESAR-CDE-main/src/utils/losses.py | # Adapted from: https://github.com/seedatnabeel/TE-CDE/blob/main/src/utils/losses.py
import torch
from torch.nn import functional as F
import math
def mse(ground_truth_outputs, predictions, active_entries, obs_prob=None, norm=1150):
"""
Computes normed MSE Loss
Args:
outputs (torch.tensor): list of ... | 1,556 | 28.377358 | 99 | py |
TESAR-CDE | TESAR-CDE-main/src/utils/training_tools.py | # Adapted from: https://github.com/seedatnabeel/TE-CDE/blob/main/src/utils/training_tools.py
import numpy as np
import torch
class EarlyStopping:
"""Early stopping: stop training if validation loss doesn't improve after n patience steps"""
def __init__(self, patience=5, delta=0.001, path="checkpoint.pt"):
... | 1,936 | 30.241935 | 105 | py |
TESAR-CDE | TESAR-CDE-main/src/utils/data_utils.py | # Adapted from: https://github.com/seedatnabeel/TE-CDE/blob/main/src/utils/data_utils.py
import pickle
import random
import numpy as np
import torch
import torchcde
from scipy.stats import boxcox
def get_processed_data(raw_sim_data, scaling_params):
"""
It takes the raw simulation data and the scaling parame... | 11,195 | 37.606897 | 115 | py |
NRG_AI_NeuroOnco_preproc | NRG_AI_NeuroOnco_preproc-master/src/classifier2_image.py | import warnings
warnings.simplefilter(action='ignore')
warnings.simplefilter(action='ignore', category=FutureWarning)
from tensorflow.keras.models import load_model
import numpy as np
import data_IO as data_IO
import tensorflow as tf
import yaml
import os
from pathlib import Path
import pandas as pd
import sys
from n... | 7,658 | 43.52907 | 153 | py |
NRG_AI_NeuroOnco_preproc | NRG_AI_NeuroOnco_preproc-master/src/classifier1_metadata.py | import warnings
warnings.simplefilter(action='ignore')
warnings.simplefilter(action='ignore', category=FutureWarning)
import csv
import glob
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import pickle
import pprint
import pydicom
import re
import sys
import tensorflow as ... | 15,259 | 45.666667 | 185 | py |
NRG_AI_NeuroOnco_preproc | NRG_AI_NeuroOnco_preproc-master/src/train_classifier2_image/train.py | import tensorflow as tf
from tensorflow.keras.callbacks import TensorBoard, ReduceLROnPlateau, EarlyStopping
import numpy as np
import yaml
import os
import datetime
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Input, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.... | 6,268 | 37.460123 | 163 | py |
NRG_AI_NeuroOnco_preproc | NRG_AI_NeuroOnco_preproc-master/src/train_classifier1_metadata/train.py | import csv
import os
import pickle
import re
from datetime import datetime
import numpy as np
import tensorflow
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
class HOF... | 5,459 | 39.746269 | 198 | py |
dtr-prototype | dtr-prototype-master/checkmate_comp/setup.py | from setuptools import setup
setup(
name='remat',
version='0.1.0',
description='Optimal tensor rematerialization research project',
packages=['remat'], # find_packages()
python_requires='>=3.6',
install_requires=[
"numpy",
"pandas",
"redis",
"matplotlib",
... | 647 | 23 | 136 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.