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 |
|---|---|---|---|---|---|---|
grabnel | grabnel-master/src/attack/grad_arg_max.py | import dgl
import torch
from tqdm import tqdm
from copy import deepcopy
from .base_attack import BaseAttack
import pandas as pd
import numpy as np
from itertools import product
from functools import lru_cache
class GradArgMax(BaseAttack):
def __init__(self, classifier, loss_fn, mode='flip', **kwargs):
su... | 6,190 | 35.417647 | 117 | py |
grabnel | grabnel-master/src/attack/bayesopt_attack.py | from .base_attack import BaseAttack
from .genetic import Genetic
import torch
import dgl
import pandas as pd
import numpy as np
from bayesopt.bayesopt.predictors import GPWL, BayesianLinearRegression, NullSurrogate
from .utils import correct_predictions, random_sample_flip, random_sample_rewire_swap, population_graphs,... | 19,657 | 54.064426 | 156 | py |
grabnel | grabnel-master/src/models/gin.py | """
Adapted from https://github.com/dmlc/dgl/blob/9a0511c8e91a7f633c9c3292fccbcbad5281d1f5/examples/mxnet/gin/gin.py.
The only change is in the forward we take a graph and extract the features, rather than accept a graph and features as
two separate inputs.
How Powerful are Graph Neural Networks
https://arxiv.org/abs/... | 6,275 | 34.061453 | 118 | py |
grabnel | grabnel-master/src/models/base.py | """Base model"""
import dgl
import torch
import torch.nn as nn
class BaseGraphClassifier(nn.Module):
"""Base class."""
def __init__(self, input_dim: int, number_of_labels: int, **kwargs):
"""
Args:
input_dim: Number of feature maps
number_of_labels: Number of labels i... | 728 | 23.3 | 81 | py |
grabnel | grabnel-master/src/models/chebygin.py | # Implementation of the ChebyGIN model from
# implemented here because the author provides the pre-trained model upon which we can attack directly (MNIST-75sp). We
# might also train this model on other datasets
# Xingchen Wan <xwan@robots.ox.ac.uk>
import sys
sys.path.append('..')
import torch.sparse
# sorry about t... | 17,326 | 42.755051 | 132 | py |
grabnel | grabnel-master/src/models/s2v.py | import torch.nn as nn
import dgl
import torch
import torch.nn.functional as F
from .base import BaseGraphClassifier
from pytorch_structure2vec.s2v_lib.embedding import EmbedMeanField, EmbedLoopyBP
#from pytorch_structure2vec.graph_classification.util import S2VGraph
import numpy as np
import networkx as nx
class S2VG... | 3,722 | 34.798077 | 119 | py |
grabnel | grabnel-master/src/models/utils.py | from . import GCNGraphClassifier, GINGraphClassifier, ChebyGIN
try:
from pytorch_structure2vec.s2v_lib.embedding import EmbedMeanField, EmbedLoopyBP
from . import S2VClassifier
s2v_available = True
except:
print('Failed to import S2V surrogate!')
s2v_available = False
def get_model_class(model_nam... | 744 | 30.041667 | 84 | py |
grabnel | grabnel-master/src/models/gcn.py | """GCN based classification model."""
import dgl
import torch
import torch.nn as nn
from dgl.nn.pytorch.conv import GraphConv
from dgl.nn.pytorch.glob import MaxPooling
from .base import BaseGraphClassifier
class GCNGraphClassifier(BaseGraphClassifier):
"""A GCN based graph classifier. Outputs are logits.
... | 1,532 | 34.651163 | 87 | py |
grabnel | grabnel-master/src/models/gunet/network.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from src.models.gunet.utils.ops import GCN, GraphUnet, Initializer, norm_g
from src.models.base import BaseGraphClassifier
import dgl
import numpy as np
def parse_dgl_graph(graph):
"""Parse the dgl graph"""
if isinstance(graph, list):
... | 4,086 | 32.5 | 97 | py |
grabnel | grabnel-master/src/models/gunet/trainer.py | import torch
from tqdm import tqdm
import torch.optim as optim
from src.models.gunet.utils.dataset import GraphData
import pandas as pd
class Trainer:
def __init__(self, args, net, G_data, save_path, log_path):
self.args = args
self.net = net
self.feat_dim = G_data.feat_dim
self.fo... | 3,465 | 39.776471 | 123 | py |
grabnel | grabnel-master/src/models/gunet/utils/data_loader.py | import torch
from tqdm import tqdm
import networkx as nx
import numpy as np
import torch.nn.functional as F
from sklearn.model_selection import StratifiedKFold
from functools import partial
import os
import pickle
class G_data(object):
def __init__(self, num_class, feat_dim, g_list, seed, task_name, split_save_pa... | 4,790 | 35.295455 | 131 | py |
grabnel | grabnel-master/src/models/gunet/utils/dataset.py | import random
import torch
import networkx as nx
import dgl
class GraphData(object):
def __init__(self, data, feat_dim):
super(GraphData, self).__init__()
self.data = data
self.feat_dim = feat_dim
self.idx = list(range(len(data)))
self.pos = 0
def __reset__(self):
... | 1,677 | 25.634921 | 85 | py |
grabnel | grabnel-master/src/models/gunet/utils/ops.py | import torch
import torch.nn as nn
import numpy as np
class GraphUnet(nn.Module):
def __init__(self, ks, in_dim, out_dim, dim, act, drop_p):
super(GraphUnet, self).__init__()
self.ks = ks
self.bottom_gcn = GCN(dim, dim, act, drop_p)
self.down_gcns = nn.ModuleList()
self.up... | 4,097 | 27.068493 | 65 | py |
grabnel | grabnel-master/src/models/chebygin_base/graphdata.py | import numpy as np
import os
from os.path import join as pjoin
import pickle
import copy
import torch
import torch.utils
import torch.utils.data
import torch.nn.functional as F
import torchvision
from scipy.spatial.distance import cdist
from .utils import *
def compute_adjacency_matrix_images(coord, sigma=0.1):
c... | 29,129 | 42.155556 | 147 | py |
grabnel | grabnel-master/src/models/chebygin_base/utils.py | import numpy as np
import os
import torch
import copy
from .graphdata import *
import torch.nn.functional as F
from torchvision import datasets, transforms
from sklearn.metrics import roc_auc_score
import numbers
import random
def load_save_noise(f, noise_shape):
if os.path.isfile(f):
print('loading noise... | 8,523 | 33.934426 | 134 | py |
grabnel | grabnel-master/src/models/chebygin_base/attention_pooling.py | import torch.nn as nn
import torch.sparse
from .utils import *
class AttentionPooling(nn.Module):
"""
Graph pooling layer implementing top-k and threshold-based pooling.
"""
def __init__(self,
in_features, # feature dimensionality in the current graph layer
in_featu... | 12,358 | 48.634538 | 165 | py |
grabnel | grabnel-master/scripts/run_bo_image_classification.py | import sys
sys.path.append('../')
import argparse
import os
import torch
from functools import partial
from src.attack.data import Data
from src.attack.bayesopt_attack import BayesOptAttack
from src.attack.utils import (classification_loss, get_dataset_split, get_device,
setseed, nettac... | 8,092 | 46.605882 | 149 | py |
grabnel | grabnel-master/scripts/run_bo_gunet.py | import sys
sys.path.append('../')
from src.models.gunet.network import GNet, GUNet
import numpy as np
import pickle
import argparse
import os
import torch
from src.attack.genetic import Genetic
from src.attack.bayesopt_attack import BayesOptAttack
from src.attack.randomattack import RandomFlip
from src.attack.utils i... | 8,227 | 51.74359 | 123 | py |
grabnel | grabnel-master/scripts/run_bo_tu.py | import sys
sys.path.append('../')
sys.path.append('../pytorch_structure2vec/s2v_lib') # if doing s2v attack on er graphs.
import argparse
import os
from os.path import join
import pandas as pd
import torch
from src.attack.data import Data, ERData
from src.attack.bayesopt_attack import BayesOptAttack
from src.att... | 9,603 | 44.733333 | 165 | py |
grabnel | grabnel-master/bayesopt/bayesopt/acquisitions.py | import torch
from torch.distributions import Normal
def graph_expected_improvement(x_star: list, predictor, xi: float = 0.0, in_fill: str = 'best',
augmented=False,
bias=None):
mean, variance = predictor.predict(x_star)
std = torch.sqrt(variance)
... | 1,533 | 33.088889 | 107 | py |
grabnel | grabnel-master/bayesopt/bayesopt/utils.py | # Xingchen Wan | 5 March 2020
import networkx as nx
from grakel.utils import graph_from_networkx
from typing import List
import dgl
import torch
import numpy as np
def dgl2networkx(g_list: List[dgl.DGLGraph], attr_name='node_attr'):
"""Convert a list of dgl graphs to a networkx graph"""
def convert_single_gr... | 5,127 | 32.298701 | 117 | py |
grabnel | grabnel-master/bayesopt/bayesopt/predictors/gp_predictor.py | import gpytorch
import torch
from bayesopt.bayesopt.wl_extractor import WeisfeilerLehmanExtractor
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.constraints.constraints import Interval
import numpy as np
from copy import deepcopy
from bayesopt.bayesopt.utils import to_unit_cube, from_unit_normal, to_... | 9,679 | 46.219512 | 132 | py |
grabnel | grabnel-master/bayesopt/bayesopt/predictors/bayes_linregress_predictor.py | from .base_predictor import BasePredictor
import torch
from copy import deepcopy
from bayesopt.bayesopt.utils import to_unit_cube, to_unit_normal, from_unit_normal
from bayesopt.bayesopt.wl_extractor import WeisfeilerLehmanExtractor
from sklearn import linear_model
import numpy as np
class BayesianLinearRegression(Ba... | 7,359 | 48.395973 | 121 | py |
grabnel | grabnel-master/bayesopt/bayesopt/predictors/base_predictor.py | import torch
from abc import abstractmethod
from bayesopt.bayesopt.acquisitions import graph_expected_improvement, graph_ucb, best_mean
import dgl
class BasePredictor:
def __init__(self, h: int = 1):
"""
The base class for predictors based on WL feature extractor.
:param h: int. Number of... | 3,094 | 43.855072 | 114 | py |
grabnel | grabnel-master/bayesopt/bayesopt/predictors/null_surrogate.py | # null surrogate
from .base_predictor import BasePredictor
import torch
from copy import deepcopy
class NullSurrogate(BasePredictor):
def __init__(self, h: int = None, ):
"""
Null surrogate
:param h: not required or used. For consistency of APi
"""
super().__init__(h=h)
... | 778 | 26.821429 | 78 | py |
grabnel | grabnel-master/data/utils.py | import numpy as np
import random
import torch
def setseed(seed):
"""Sets the seed for rng."""
np.random.seed(seed)
random.seed(seed)
if seed is not None:
torch.random.manual_seed(seed) | 210 | 18.181818 | 38 | py |
grabnel | grabnel-master/data/build_mnist.py | # generate the MNIST-75sp data in DGL format
from torchvision import datasets
import scipy.ndimage
from skimage.segmentation import slic
from scipy.spatial.distance import cdist
import argparse
import numpy as np
import datetime
import os
import random
import pickle
import multiprocessing as mp
import networkx as nx
im... | 8,186 | 44.994382 | 155 | py |
grabnel | grabnel-master/data/generate_er.py | """Generate partitions of erdos-renyi graphs (following methodologies of Dai et al 2018).
The data is stored as a list of tuples where each tuple is of the form (x, y) where x is a DGLGraph and y is a torch
tensor containing the label."""
import argparse
import os
import pickle
from os.path import join
import dgl
im... | 4,169 | 45.333333 | 116 | py |
clam | clam-main/baselines.py | import numpy as np
import scipy.io
import time
from collections import Counter
import math
import json
from scipy.spatial import distance
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from parser import *
from helper import *
from result_helper import *
from draw_helper import *
from hyper_params imp... | 15,147 | 50.699659 | 248 | py |
clam | clam-main/plot_2d_cluster.py | import numpy as np;
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d
import tensorflow as tf
from tensorflow.keras.initializers import RandomNormal, RandomUniform
from tensorflow.keras.layers import Input, Dense, Lambda
from tensorflow.keras import Model
from scipy.spatial import di... | 7,822 | 30.292 | 138 | py |
clam | clam-main/plot_gaussian.py | import numpy as np;
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d
import tensorflow as tf
from tensorflow.keras.initializers import RandomNormal, RandomUniform
from tensorflow.keras.layers import Input, Dense, Lambda
from tensorflow.keras import Model
from tensorflow.keras.optimi... | 22,110 | 34.491172 | 148 | py |
clam | clam-main/mhn.py | import tensorflow as tf
from tensorflow.keras.initializers import RandomNormal, RandomUniform
from hyper_params import *
import numpy as np
class MHN_WITH_1_HIDDEN_LAYER(tf.keras.layers.Layer):
def __init__(self, N1, N2, beta, alpha, init_mem=None, c=1, **kwargs):
super().__init__(**kwargs)
self.N1... | 2,017 | 33.20339 | 90 | py |
clam | clam-main/s_kmeans.py | # from time import time
import numpy as np
import keras.backend as K
from tensorflow.keras.layers import Input, Layer, InputSpec
from keras.models import Model
from keras.utils.vis_utils import plot_model
from sklearn.cluster import KMeans
import tensorflow as tf
from helper import *
class ClusteringLayer(Layer):
... | 6,577 | 38.866667 | 148 | py |
clam | clam-main/amc_t.py | import numpy as np
import scipy.io
import time
from collections import Counter
import math
import tensorflow as tf
# import tensorflow_addons as tfa
from tensorflow.keras.layers import Input, Dense, Lambda
from tensorflow.keras import Model
from tensorflow.keras.optimizers import Adam
# from tensorflow.keras.callbacks... | 17,473 | 56.669967 | 180 | py |
DenseUnet_Esophagus_Segmentation | DenseUnet_Esophagus_Segmentation-master/functions/networks/dense_unet2_attention.py | import tensorflow as tf
import SimpleITK as sitk
# import math as math
import numpy as np
import os
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
import time
# !!
class _densenet_unet:
def __init__(self, densnet_unet_config,compression_coefficient, growth_rate, class_no=... | 21,684 | 48.965438 | 131 | py |
DenseUnet_Esophagus_Segmentation | DenseUnet_Esophagus_Segmentation-master/functions/networks/dense_unet2_attention_spatial.py | import tensorflow as tf
import SimpleITK as sitk
# import math as math
import numpy as np
import os
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
import time
# !!
class _densenet_unet:
def __init__(self, densnet_unet_config,compression_coefficient, growth_rate, class_no=... | 22,489 | 49.313199 | 140 | py |
DenseUnet_Esophagus_Segmentation | DenseUnet_Esophagus_Segmentation-master/functions/networks/dense_unet2_attention_spatial_skip_ch_attention.py | import tensorflow as tf
import SimpleITK as sitk
# import math as math
import numpy as np
import os
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
import time
# !!
class _densenet_unet:
def __init__(self, densnet_unet_config,compression_coefficient, growth_rate, class_no=... | 24,155 | 49.962025 | 140 | py |
DenseUnet_Esophagus_Segmentation | DenseUnet_Esophagus_Segmentation-master/functions/networks/dense_unet2_attention_spatial_skip_attention.py | import tensorflow as tf
import SimpleITK as sitk
# import math as math
import numpy as np
import os
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
import time
# !!
class _densenet_unet:
def __init__(self, densnet_unet_config,compression_coefficient, growth_rate, class_no=... | 23,677 | 49.811159 | 140 | py |
DenseUnet_Esophagus_Segmentation | DenseUnet_Esophagus_Segmentation-master/functions/networks/dense_unet2_attention_channel_spatial.py | import tensorflow as tf
import SimpleITK as sitk
# import math as math
import numpy as np
import os
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
import time
# !!
class _densenet_unet:
def __init__(self, densnet_unet_config,compression_coefficient, growth_rate, class_no=... | 24,091 | 48.368852 | 138 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
import math
import os
import random
from collections import deque
import gym
import numpy as np
import torch
import torch.nn.functional as F
from dm_control import suite
from numpy import linalg as LA
from torch import distributions as pyd
from torch import nn
impor... | 4,694 | 26.296512 | 85 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/encoder.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
def tie_weights(src, trg):
assert type(src) == type(trg)
trg.weight = src.weight
trg.bias = src.bias
OUT_DIM = {2: 39, 4: 35, 6: 31}
class PixelEncoder(nn.Module):
"""Convolutional encoder of pixels observations... | 5,700 | 26.541063 | 87 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/logger.py | # Copyright (c) Facebook, Inc. and its affiliates.
import csv
import json
import os
import shutil
from collections import defaultdict
import numpy as np
import torch
from termcolor import colored
from torch.utils.tensorboard import SummaryWriter
COMMON_TRAIN_FORMAT = [
("episode", "E", "int"),
("step", "S", ... | 7,709 | 32.815789 | 81 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/decoder.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
from encoder import OUT_DIM
class PixelDecoder(nn.Module):
def __init__(self, obs_shape, feature_dim, num_layers=2, num_filters=32):
super().__init__()
self.num_layers = num_layers
self.num_filters = n... | 2,728 | 28.344086 | 88 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/replay_buffer.py | # Copyright (c) Facebook, Inc. and its affiliates.
import random
from typing import List, Optional, Union
import numpy as np
import torch
class MultiEnvReplayBuffer(object):
"""Buffer to store environment transitions for multiple environments"""
def __init__(self, obs_shape, action_shape, capacity, device,... | 3,900 | 36.509615 | 87 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/train.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import copy
import math
import os
import pickle as pkl
import sys
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dmc2gym
import hydra
import utils
from logger import Logger
from replay... | 6,586 | 33.851852 | 88 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/agent/sac.py | # Copyright (c) Facebook, Inc. and its affiliates.
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import autograd, optim
import hydra
import utils
from agent import Agent
from decoder import make_decoder
from encoder import make_encoder
def make_dynamic... | 25,968 | 33.90457 | 88 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/agent/actor.py | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import torch
import math
from torch import nn
import torch.nn.functional as F
from torch import distributions as pyd
import utils
class TanhTransform(pyd.transforms.Transform):
domain = pyd.constraints.real
codomain = pyd.constraints.inte... | 3,183 | 30.215686 | 137 | py |
icp-block-mdp | icp-block-mdp-master/reinforcement_learning/agent/critic.py | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn.functional as F
import utils
class DoubleQCritic(nn.Module):
"""Critic network, employes double Q-learning."""
def __init__(self, obs_dim, action_dim, hidden_dim, hidden_depth)... | 1,620 | 30.173077 | 78 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/utils.py | # The different vectorized envs have been taken from: https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail/blob/master/a2c_ppo_acktr/envs.py
import glob
import os
import random
from collections import defaultdict, deque
from random import sample
from typing import List, Optional, Union
import gym
import numpy as ... | 16,718 | 30.545283 | 144 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/collect_data_using_expert_policy.py | # Copyright (c) Facebook, Inc. and its affiliates.
"""Method to train the one encoder baseline for imitation learning"""
import json
import os
from argparse import Namespace
from time import time
import torch
import utils
from argument_parser import parse_args
from model_utils.bootstrap.common import create_multi_env... | 4,838 | 26.185393 | 86 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
import os
import random
from collections import deque
import gym
import numpy as np
import torch
import torch.nn as nn
class eval_mode(object):
def __init__(self, *models):
self.models = models
def __enter__(self):
self.prev_states = []
... | 5,490 | 31.3 | 87 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae/encoder.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
def tie_weights(src, trg):
assert type(src) == type(trg)
trg.weight = src.weight
trg.bias = src.bias
OUT_DIM = {2: 39, 4: 35, 6: 31}
class PixelEncoder(nn.Module):
"""Convolutional encoder of pixels observations.... | 5,688 | 27.445 | 87 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae/logger.py | # Copyright (c) Facebook, Inc. and its affiliates.
import json
import os
import shutil
from collections import defaultdict
import numpy as np
import torch
import torchvision
from termcolor import colored
from torch.utils.tensorboard import SummaryWriter
FORMAT_CONFIG = {
"rl": {
"train": [
("e... | 5,597 | 32.12426 | 88 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae/sacae.py | # Copyright (c) Facebook, Inc. and its affiliates.
import copy
import math
from typing import Optional
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import sacae.utils as utils
from sacae.decoder import make_decoder
from sacae.encoder import make_encoder
LOG_FREQ = 10000
def... | 16,040 | 30.890656 | 87 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae/decoder.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
from sacae.encoder import OUT_DIM
class PixelDecoder(nn.Module):
def __init__(self, obs_shape, feature_dim, num_layers=2, num_filters=32):
super().__init__()
self.num_layers = num_layers
self.num_filter... | 3,455 | 30.418182 | 88 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae/vec_logger.py | # Copyright (c) Facebook, Inc. and its affiliates.
import os
import shutil
from typing import Optional
import numpy as np
import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from sacae.logger import MetersGroup
FORMAT_CONFIG = {
"rl": {
"train": [
("env_idx", "EN... | 5,190 | 34.312925 | 86 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae/sacae_vec.py | # Copyright (c) Facebook, Inc. and its affiliates.
from typing import Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
import sacae.utils as utils
from sacae import sacae
from sacae.decoder import make_vec_decoder
from sacae.encoder import make_vec_encoder
from sacae.logger import Logge... | 11,471 | 31.590909 | 87 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/rl/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import glob
import json
import os
from typing import Optional, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from torch import autograd, nn, optim
from torch.utils.data import DataLoader, Dataset
import argument_parser
import u... | 4,741 | 29.792208 | 86 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/rl/logger.py | # Copyright (c) Facebook, Inc. and its affiliates.
import json
import os
import shutil
from collections import defaultdict
import numpy as np
import torch
import torchvision
from termcolor import colored
FORMAT_CONFIG = {
"rl": {
"train": [
("episode", "E", "int"),
("step", "S", "i... | 6,941 | 33.197044 | 88 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/model_utils/utils_baseline.py | # Copyright (c) Facebook, Inc. and its affiliates.
from argparse import Namespace
from typing import Dict, List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import utils
from ml_logger.logbook import LogBook
Envs_Type = Union[List[utils.FrameStack], utils.VecPyTorch]
def train_model(
a... | 8,130 | 30.153257 | 87 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/model_utils/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
import os
from argparse import Namespace
from typing import Dict, List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import nn
import utils
from ml_logger.logbook import LogBook
Envs_Type = Union[List[utils.FrameStack], utils.VecPyT... | 11,782 | 31.821727 | 148 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/model_utils/model.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
class DynamicsModel(nn.Module):
def __init__(self, representation_size, action_shape):
super().__init__()
self.action_linear = nn.Linear(action_shape, representation_size)
self.trunk = nn.Sequential(
... | 2,125 | 26.61039 | 73 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/model_utils/bootstrap/common.py | # Copyright (c) Facebook, Inc. and its affiliates.
import argparse
from argparse import Namespace
import torch
import utils
from ml_logger.logbook import LogBook
from ml_logger.logbook import make_config as make_logbook_config
def make_logbook(args: Namespace) -> LogBook:
logbook_config = make_logbook_config(
... | 1,375 | 27.666667 | 88 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/model_utils/bootstrap/basic_model.py | # Copyright (c) Facebook, Inc. and its affiliates.
import json
import os
from argparse import Namespace
from typing import Tuple
import numpy as np
import torch
import utils
from model_utils.bootstrap.common import create_multi_env_replay_buffer, make_logbook
from model_utils.env import make_train_and_eval_envs
from ... | 3,179 | 27.648649 | 88 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/model_utils/bootstrap/model_with_aux_loss.py | # Copyright (c) Facebook, Inc. and its affiliates.
import os
from argparse import Namespace
from typing import Optional, Tuple
import torch
import utils
from ml_logger.logbook import LogBook
from model_utils.bootstrap import basic_model as basic_bootstrap
from model_utils.bootstrap.common import create_multi_env_repl... | 7,253 | 31.675676 | 108 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/model_utils/bootstrap/model_with_aux_loss_vec.py | # Copyright (c) Facebook, Inc. and its affiliates.
import json
import os
from argparse import Namespace
import torch
import utils
from model_utils.bootstrap.common import (create_multi_env_replay_buffer,
make_logbook)
from model_utils.env import make_fns_to_make_train_and_eva... | 2,445 | 27.44186 | 77 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae_utils/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
import time
from argparse import Namespace
from typing import Optional
import numpy as np
import torch
import utils
from sacae.sacae_vec import SacAeAgent
from sacae.vec_logger import VecLogger
# def evaluate_one_env_from_list_of_envs(
# env: utils.FrameStack,
#... | 9,022 | 28.680921 | 105 | py |
icp-block-mdp | icp-block-mdp-master/imitation_learning/sacae_utils/bootstrap.py | # Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import json
import os
from argparse import Namespace
from typing import Optional, Union
import torch
from torch import nn
import dmc2gym
import utils
from ml_logger.logbook import LogBook
from ml_logger.logbook import make_config as make_logbook_confi... | 4,898 | 27.988166 | 84 | py |
icp-block-mdp | icp-block-mdp-master/model_learning/main.py | # Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import json
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch import autograd, nn, optim
from torch.utils.data import DataLoader, Dataset
import utils
from model import Decoder, DynamicsModel, Encoder
def parse_arg... | 7,094 | 37.145161 | 136 | py |
icp-block-mdp | icp-block-mdp-master/model_learning/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
import os
import random
from collections import defaultdict, deque
import gym
import numpy as np
import skvideo.io
import torch
import torch.nn as nn
import dmc2gym
def make_env(bg, args):
env = dmc2gym.make(
domain_name=args.domain_name,
task_n... | 7,067 | 31.422018 | 87 | py |
icp-block-mdp | icp-block-mdp-master/model_learning/model.py | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
def tie_weights(src, trg):
assert type(src) == type(trg)
trg.weight = src.weight
trg.bias = src.bias
OUT_DIM = {2: 39, 4: 35, 6: 31}
class Encoder(nn.Module):
"""Convolutional encoder of pixels observations."""
... | 4,649 | 28.807692 | 88 | py |
SlothSpeech | SlothSpeech-main/main.py | import logging
import warnings
from datetime import datetime
from pathlib import Path
from time import time
import torch
from attasr.attack_loop import EnergyAttack, EnergyAttackConfig
from attasr.attack_losses import l2_norm, linf_norm
from attasr.experiment_datasets import ExprDataset
from attasr.experiment_models ... | 2,172 | 23.977011 | 72 | py |
SlothSpeech | SlothSpeech-main/setup.py | from setuptools import find_packages, setup
setup(
name="attasr",
version="1.1.0",
package_dir=find_packages(),
include_package_data=True,
install_requires=[
"datasets>=2.10.1",
"pandas>=1.5.3",
"setuptools>=65.5.0",
"tqdm>=4.64.1",
"transformers>=4.26.1",
... | 439 | 19.952381 | 43 | py |
SlothSpeech | SlothSpeech-main/src/attasr/noise.py | import torch
def get_white_noise(
signal_embedding: torch.Tensor, signal_to_noise_ratio: float
) -> torch.Tensor:
rms_signal = torch.sqrt(torch.mean(signal_embedding**2))
rms_noise = torch.sqrt(
rms_signal**2
/ torch.pow(torch.tensor(10), signal_to_noise_ratio / 10)
)
std_noise =... | 447 | 25.352941 | 74 | py |
SlothSpeech | SlothSpeech-main/src/attasr/attack_losses.py | from typing import Callable, Protocol
import torch
def linf_norm(x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return torch.linalg.norm((target - x), ord=float("inf"), dim=1).sum(dim=-1)
def l2_norm(x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
return torch.sum((target - x) ** 2, dim=-1... | 1,493 | 27.188679 | 79 | py |
SlothSpeech | SlothSpeech-main/src/attasr/attack_loop.py | import logging
from dataclasses import dataclass
from pathlib import Path
from time import time
from typing import Any, Callable, Optional, Type
import datasets
import pandas as pd
import torch
from torch.autograd import Variable
from tqdm.auto import tqdm
from attasr.attack_losses import AttackLossProtocol, get_atta... | 13,276 | 32.69797 | 77 | py |
eda_nlp | eda_nlp-master/experiments/d_2_tsne.py | from methods import *
from numpy.random import seed
from keras import backend as K
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
seed(0)
################################
#### get dense layer output ####
################################
#getting the x and y inputs in numpy array form from the text ... | 4,213 | 26.187097 | 99 | py |
eda_nlp | eda_nlp-master/experiments/methods.py | from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.layers import Bidirectional
import keras.layers as layers
from keras.models import Sequential
from keras.models import load_model
from keras.callbacks import EarlyStopping
from sklearn.utils import shuffle
from ... | 9,650 | 33.223404 | 117 | py |
Graft-PSMNet | Graft-PSMNet-main/test_kitti.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
from torch.autograd import grad as Grad
from torchvision import transforms
import skimage.io
import os
import copy
from collections import OrderedDict
from tqdm import tqdm, trange
from PIL import Image
import numpy a... | 3,733 | 33.897196 | 107 | py |
Graft-PSMNet | Graft-PSMNet-main/test_middlebury.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from torch.autograd import Variable
from torch.autograd import grad as Grad
import skimage.io
import os
import copy
from collections import OrderedDict
from tqdm import tqdm, trange
from PIL import Image
import numpy a... | 4,011 | 31.617886 | 106 | py |
Graft-PSMNet | Graft-PSMNet-main/loss_functions.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import cv2
from PIL import Image
import matplotlib.pyplot as plt
def disp2distribute(disp_gt, max_disp, b=2):
disp_gt = disp_gt.unsqueeze(1)
disp_range = torch.arange(0, max_disp).view(1, -1, 1, 1).float().cuda()
gt_dist... | 6,062 | 32.497238 | 106 | py |
Graft-PSMNet | Graft-PSMNet-main/retrain_CostAggregation.py | import torch
import torch.utils.data
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
import os
import copy
from tqdm import tqdm, trange
import matplotlib.pyplot as plt
import argparse
from dataloader import sceneflow_loader as sf
import networks.Aggregator as Agg
import networks.subm... | 4,896 | 32.312925 | 117 | py |
Graft-PSMNet | Graft-PSMNet-main/train_adaptor.py | import torch
import torch.utils.data
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
import os
import copy
from tqdm import tqdm
import matplotlib.pyplot as plt
import argparse
from dataloader import sceneflow_loader as sf
import networks.Aggregator as Agg
import networks.U_net as un
... | 4,861 | 32.531034 | 117 | py |
Graft-PSMNet | Graft-PSMNet-main/test_eth3d.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
from torch.autograd import grad as Grad
from torchvision import transforms
import os
import copy
import skimage.io
from collections import OrderedDict
from tqdm import tqdm, trange
from PIL import Image
import numpy a... | 3,559 | 32.904762 | 99 | py |
Graft-PSMNet | Graft-PSMNet-main/train_baseline.py | import argparse
import torch
import torch.utils.data
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
import os
import copy
from tqdm import tqdm
from dataloader import sceneflow_loader as sf
import networks.submodule as sm
import networks.U_net as un
import networks.Aggregator as Agg
... | 4,611 | 30.589041 | 117 | py |
Graft-PSMNet | Graft-PSMNet-main/networks/U_net.py | import torch
import torch.nn as nn
import math
class conv_block(nn.Module):
def __init__(self, ch_in, ch_out):
super(conv_block, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(ch_out),
... | 9,607 | 30.093851 | 86 | py |
Graft-PSMNet | Graft-PSMNet-main/networks/resnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dila... | 8,386 | 35.947137 | 106 | py |
Graft-PSMNet | Graft-PSMNet-main/networks/vgg.py | import torch
import torch.nn as nn
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=True):
super(VGG, self).__init__()
self.features = features
... | 6,388 | 37.257485 | 113 | py |
Graft-PSMNet | Graft-PSMNet-main/networks/stackhourglass.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import math
from networks.submodule import convbn, convbn_3d, DisparityRegression
class hourglass(nn.Module):
def __init__(self, inplanes):
s... | 3,858 | 40.053191 | 143 | py |
Graft-PSMNet | Graft-PSMNet-main/networks/submodule.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
from torchvision import models
import math
import numpy as np
import torchvision.transforms as transforms
import PIL
import os
import matplotlib.pyplot as ... | 6,460 | 37.921687 | 174 | py |
Graft-PSMNet | Graft-PSMNet-main/networks/Aggregator.py | import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import math
from networks.submodule import convbn, convbn_3d, DisparityRegression
from networks.stackhourglass import hourglass_gwcnet, hourglass
import matplotlib.pyplot as plt
import loss_fun... | 11,953 | 42 | 110 | py |
Graft-PSMNet | Graft-PSMNet-main/networks/feature_extraction.py | import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
from torchvision import models
import math
import numpy as np
import torchvision.transforms as transforms
import PIL
import os
import matplotlib.pyplot as plt
from networks.resnet import ResNet... | 3,225 | 24.401575 | 97 | py |
Graft-PSMNet | Graft-PSMNet-main/dataloader/ETH3D_loader.py | import os
from PIL import Image
from dataloader import readpfm as rp
import dataloader.preprocess
import torch.utils.data as data
import torchvision.transforms as transforms
import numpy as np
import random
IMG_EXTENSIONS= [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP'
]
d... | 3,410 | 28.405172 | 116 | py |
Graft-PSMNet | Graft-PSMNet-main/dataloader/KITTIloader.py | import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import os
from PIL import Image
import random
import numpy as np
IMG_EXTENSIONS= [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP'
]
def is_image_file(filename):
return any(filename.... | 4,371 | 28.540541 | 108 | py |
Graft-PSMNet | Graft-PSMNet-main/dataloader/KITTI2012loader.py | import torch.utils.data as data
import torchvision.transforms as transforms
import os
from PIL import Image
import random
import numpy as np
IMG_EXTENSIONS= [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP'
]
def is_image_file(filename):
return any(filename.endswith(exte... | 3,118 | 26.848214 | 108 | py |
Graft-PSMNet | Graft-PSMNet-main/dataloader/sceneflow_loader.py | import os
from PIL import Image
from dataloader import readpfm as rp
import dataloader.preprocess
import torch.utils.data as data
import torchvision.transforms as transforms
import numpy as np
import random
IMG_EXTENSIONS= [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP'
]
d... | 8,270 | 36.425339 | 119 | py |
Graft-PSMNet | Graft-PSMNet-main/dataloader/middlebury_loader.py | import os
from PIL import Image
from dataloader import readpfm as rp
import torch.utils.data as data
import torchvision.transforms as transforms
import numpy as np
import random
def mb_loader(filepath, res):
train_path = os.path.join(filepath, 'training' + res)
test_path = os.path.join(filepath, 'test' + res... | 4,193 | 30.298507 | 108 | py |
Graft-PSMNet | Graft-PSMNet-main/dataloader/vKITTI_loader.py | import torch.utils.data as data
import torchvision.transforms as transforms
import os
from PIL import Image
import random
import numpy as np
def vkt_loader(filepath):
all_limg = []
all_rimg = []
all_disp = []
img_path = os.path.join(filepath, 'vkitti_2.0.3_rgb')
depth_path = os.path.join(filepath... | 3,671 | 29.6 | 108 | py |
contextualLoss | contextualLoss-master/CX/CX_distance.py | # import tensorflow as tf
import torch
import numpy as np
import sklearn.manifold.t_sne
class TensorAxis:
N = 0
H = 1
W = 2
C = 3
class CSFlow:
def __init__(self, sigma=float(0.1), b=float(1.0)):
self.b = b
self.sigma = sigma
def __calculate_CS(self, scaled_distances, axis_fo... | 9,761 | 38.362903 | 117 | py |
fastai | fastai-master/setup.py | from pkg_resources import parse_version
from configparser import ConfigParser
import setuptools,re,sys
assert parse_version(setuptools.__version__)>=parse_version('36.2')
# note: all settings are in settings.ini; edit there, not here
config = ConfigParser(delimiters=['='])
config.read('settings.ini')
cfg = config['DEF... | 2,822 | 43.109375 | 193 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.