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 |
|---|---|---|---|---|---|---|
TCGL | TCGL-main/models/s3dg.py | # modified from https://raw.githubusercontent.com/qijiezhao/s3d.pytorch/master/S3DG_Pytorch.py
import torch.nn as nn
import torch
## pytorch default: torch.nn.BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
## tensorflow s3d code: torch.nn.BatchNorm3d(num_features, eps=1e-3, ... | 9,470 | 38.794118 | 123 | py |
TCGL | TCGL-main/models/i3dv2.py | import math
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_padding_shape(filter_shape, stride):
def _pad_top_bottom(filter_dim, stride_val):
pad_along = max(filter_dim - stride_val, 0)
pad_top = pad_along // 2
pad_bottom = pad_along ... | 16,105 | 35.112108 | 122 | py |
TCGL | TCGL-main/models/r21d_v2.py | import math
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_padding_shape(filter_shape, stride):
def _pad_top_bottom(filter_dim, stride_val):
pad_along = max(filter_dim - stride_val, 0)
pad_top = pad_along // 2
pad_bottom = pad_along ... | 16,141 | 35.111857 | 121 | py |
TCGL | TCGL-main/models/model.py | from torch import nn
import torch.nn.functional as F
import torch
import numpy as np
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, input):
return input.view(input.size(0), -1)
class Normalize(nn.Module):
def __init__(self, power=2):
... | 1,885 | 27.575758 | 79 | py |
TCGL | TCGL-main/models/i3d.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# import scipy.io
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #close the warning
import math
import os
import torch.nn as nn
import numpy as np
import torch
import torch.nn.functional as F
from models.model import Flatten
from models.model import MotionEnhance
#f... | 20,559 | 37.358209 | 117 | py |
TCGL | TCGL-main/models/r21d.py | """R2plus1D"""
import math
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.nn.modules.utils import _triple
class SpatioTemporalConv(nn.Module):
"""Applies a factored 3D convolution over an input signal composed of several input
planes with distinct spatial and time axes, by ... | 10,059 | 44.520362 | 135 | py |
TCGL | TCGL-main/models/r3d.py | """R3D"""
import math
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.nn.modules.utils import _triple
class SpatioTemporalConv(nn.Module):
r"""Applies a factored 3D convolution over an input signal composed of several input
planes with distinct spatial and time axes, by perf... | 7,962 | 42.043243 | 135 | py |
TCGL | TCGL-main/models/opn.py | """OPN"""
import math
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.nn.modules.utils import _triple
class OPN(nn.Module):
"""Frame Order Prediction Network"""
def __init__(self, base_network, feature_size, tuple_len):
"""
Args:
feature_size (int... | 2,925 | 30.462366 | 123 | py |
TCGL | TCGL-main/models/r3d_50_v2.py | """
https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/models/resnet.py
Commit id: 4e2195c
"""
import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = [
'ResNet', 'resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152',... | 8,924 | 27.333333 | 95 | py |
TCGL | TCGL-main/models/vcopn.py | """VCOPN"""
import math
from collections import OrderedDict
import random
import torch
import torch.nn as nn
from torch.nn.modules.utils import _triple
from torch_geometric.nn import GCNConv
from torch_geometric.nn import GATConv
from torch_geometric.utils import dropout_adj
import torch.nn.functional as F
import numpy... | 127,957 | 47.560911 | 328 | py |
TCGL | TCGL-main/models/alexnet.py | """AlexNet"""
import math
from collections import OrderedDict
import torch
import torch.nn as nn
class AlexNet(nn.Module):
"""AlexNet with BN and pool5 to be AdaptiveAvgPool2d(1)"""
def __init__(self, with_classifier=False, return_conv=False, num_classes=1000):
super(AlexNet, self).__init__()
... | 2,257 | 26.876543 | 83 | py |
TCGL | TCGL-main/datasets/activitynet.py | """Dataset utils for NN."""
import os
import random
from glob import glob
from pprint import pprint
import uuid
import tempfile
import numpy as np
#import ffmpeg
import skvideo.io
import pandas as pd
from skvideo.io import ffprobe
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import tr... | 52,490 | 42.452815 | 129 | py |
TCGL | TCGL-main/datasets/sthv2.py | """Dataset utils for NN."""
import os
import random
from glob import glob
from pprint import pprint
import uuid
import tempfile
#import sh
import numpy as np
#import ffmpeg
import skvideo.io
import pandas as pd
from skvideo.io import ffprobe
import torch
from datasets.data_parser import WebmDataset
from torch.utils.dat... | 31,078 | 46.813846 | 142 | py |
TCGL | TCGL-main/datasets/transforms_video.py | import torch
import cv2
import numpy as np
import numbers
import collections
import random
class ComposeMix(object):
r"""Composes several transforms together. It takes a list of
transformations, where each element odf transform is a list with 2
elements. First being the transform function itself, second b... | 8,616 | 31.889313 | 82 | py |
TCGL | TCGL-main/datasets/k400.py | """Dataset utils for NN."""
import os
import random
from glob import glob
from pprint import pprint
import uuid
import tempfile
import numpy as np
#import ffmpeg
#import skvideo.io
import pandas as pd
#from skvideo.io import ffprobe
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import ... | 46,166 | 46.545829 | 127 | py |
TCGL | TCGL-main/datasets/ucf101.py | """Dataset utils for NN."""
import os
import random
from glob import glob
from pprint import pprint
import uuid
import tempfile
import numpy as np
#import ffmpeg
#import skvideo.io
import pandas as pd
#from skvideo.io import ffprobe
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import ... | 41,947 | 41.891616 | 129 | py |
TCGL | TCGL-main/datasets/hmdb51.py | """Dataset utils for NN."""
import os
import random
from glob import glob
from pprint import pprint
import uuid
import tempfile
import numpy as np
import ffmpeg
import skvideo.io
import pandas as pd
from skvideo.io import ffprobe
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import tra... | 22,458 | 41.535985 | 119 | py |
TCGL | TCGL-main/lib/custom_transforms.py | import numpy as np
import scipy
import scipy.ndimage
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage.interpolation import map_coordinates
import collections
from PIL import Image
import numbers
import random
__author__ = "Wei OUYANG"
__license__ = "GPL"
__version__ = "0.1.0"
__status__ = "Developm... | 14,157 | 31.324201 | 107 | py |
TCGL | TCGL-main/lib/utils.py | import torch
import numpy as np
def adjust_learning_rate(epoch, opt, optimizer):
"""Sets the learning rate to the initial LR decayed by 0.2 every steep step"""
steps = np.sum(epoch > np.asarray(opt.lr_decay_epochs))
if steps > 0:
new_lr = opt.learning_rate * (opt.lr_decay_rate ** steps)
fo... | 1,428 | 28.770833 | 88 | py |
TCGL | TCGL-main/lib/alias_multinomial.py | import torch
import numpy as np
class AliasMethod(object):
'''
From: https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
'''
def __init__(self, probs):
if probs.sum() > 1:
probs.div_(probs.sum())
K = len(probs)
... | 1,935 | 28.784615 | 124 | py |
TCGL | TCGL-main/lib/NCEAverage.py | import torch
from torch import nn
from .alias_multinomial import AliasMethod
import math
class NCEAverage_ori(nn.Module):
def __init__(self, inputSize, outputSize, K, T=0.07, momentum=0.5, use_softmax=False):
super(NCEAverage_ori, self).__init__()
self.nLem = outputSize
self.unigrams = t... | 7,812 | 41.461957 | 104 | py |
TCGL | TCGL-main/lib/LinearAverage.py | import torch
from torch.autograd import Function
from torch import nn
import math
class LinearAverageOp(Function):
@staticmethod
def forward(self, x, y, memory, params):
T = params[0].item()
batchSize = x.size(0)
# inner product
out = torch.mm(x.data, memory.t())
out.di... | 1,785 | 29.271186 | 98 | py |
TCGL | TCGL-main/lib/NCECriterion.py | import torch
from torch import nn
eps = 1e-7
class NCECriterion(nn.Module):
"""
Eq. (12): L_{NCE}
"""
def __init__(self, n_data):
super(NCECriterion, self).__init__()
self.n_data = n_data
def forward(self, x):
bsz = x.shape[0]
m = x.size(1) - 1
# noise di... | 1,154 | 24.108696 | 87 | py |
TCGL | TCGL-main/lib/normalize.py | import torch
from torch.autograd import Variable
from torch import nn
class Normalize(nn.Module):
def __init__(self, power=2):
super(Normalize, self).__init__()
self.power = power
def forward(self, x):
norm = x.pow(self.power).sum(1, keepdim=True).pow(1./self.power)
out = ... | 351 | 22.466667 | 72 | py |
hankel | hankel-main/docs/conf.py | # -*- coding: utf-8 -*-
#
# hankel documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 13 10:17:24 2017.
#
# 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.
#
# Al... | 5,458 | 29.160221 | 114 | py |
maxvit | maxvit-main/maxvit/models/maxvit.py | # Copyright 2023 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 43,178 | 33.5432 | 80 | py |
maxvit | maxvit-main/maxvit/models/eval_ckpt.py | # Copyright 2023 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 11,163 | 36.463087 | 79 | py |
maxvit | maxvit-main/maxvit/models/common_ops.py | # Copyright 2023 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 4,808 | 33.35 | 91 | py |
pnp-3d | pnp-3d-main/pytorch/pnp3d.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Shi Qiu
@Contact: shi.qiu@anu.edu.au
@File: model.py
@Time: 2021/01/06
"""
import os
import sys
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def knn(x, k):
inner = -2*torch.matmul(x.transpose... | 5,123 | 36.40146 | 193 | py |
Devign | Devign-master/main.py | import argparse
import os
import pickle
import sys
import numpy as np
import torch
from torch.nn import BCELoss
from torch.optim import Adam
from data_loader.dataset import DataSet
from modules.model import DevignModel, GGNNSum
from trainer import train
from utils import tally_param, debug
if __name__ == '__main__'... | 3,901 | 50.342105 | 109 | py |
Devign | Devign-master/trainer.py | import copy
from sys import stderr
import numpy as np
import torch
from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score
from tqdm import tqdm
from utils import debug
def evaluate_loss(model, loss_function, num_batches, data_iter, cuda=False):
model.eval()
with torch.no_grad():... | 4,958 | 42.5 | 115 | py |
Devign | Devign-master/modules/model.py | import torch
from dgl.nn import GatedGraphConv
from torch import nn
import torch.nn.functional as f
class DevignModel(nn.Module):
def __init__(self, input_dim, output_dim, max_edge_types, num_steps=8):
super(DevignModel, self).__init__()
self.inp_dim = input_dim
self.out_dim = output_dim
... | 3,338 | 39.719512 | 95 | py |
Devign | Devign-master/data_loader/dataset.py | import copy
import json
import sys
import torch
from dgl import DGLGraph
from tqdm import tqdm
from data_loader.batch_graph import GGNNBatchGraph
from utils import load_default_identifiers, initialize_batch, debug
class DataEntry:
def __init__(self, datset, num_nodes, features, edges, target):
self.data... | 5,345 | 39.195489 | 122 | py |
Devign | Devign-master/data_loader/batch_graph.py | import torch
from dgl import DGLGraph
class BatchGraph:
def __init__(self):
self.graph = DGLGraph()
self.number_of_nodes = 0
self.graphid_to_nodeids = {}
self.num_of_subgraphs = 0
def add_subgraph(self, _g):
assert isinstance(_g, DGLGraph)
num_new_nodes = _g.nu... | 2,327 | 38.457627 | 106 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/XGBoost_ensemble/xgboost_ensemble.py | #!/bin/bash python
import sklearn.metrics
import os
import numpy as np
import pandas as pd
from ray.tune.schedulers import ASHAScheduler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error,mean_absolute_error
import xgboost as xgb
import argparse
import ray
from ray impor... | 8,154 | 43.081081 | 207 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Transformer/transformer_future.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
import seaborn as sns
import time
import argparse
import random
from transformer imp... | 3,716 | 34.066038 | 137 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Transformer/utils.py | #!/bin/bash python
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.preprocessing import StandardScaler
def to_windowed(data,window_size,pred_size):
out = []
for i in range(len(data)-window_size):
feature = np.array(data[i:i+(window_size)])
target = np.arra... | 6,735 | 51.625 | 177 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Transformer/transformer_train.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import time
import random
import os
import ray
from ray import tune
from ray.tune.schedulers import AsyncHyperBandScheduler, ASHAScheduler
from transformer import Tranformer
from utils import *
def process_one_batch(model,... | 5,613 | 39.388489 | 184 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Transformer/transformer.py | #!/bin/bash python
import torch
import torch.nn as nn
import math
class TokenEmbedding(nn.Module):
def __init__(self, d_model):
super(TokenEmbedding, self).__init__()
self.tokenConv = nn.Conv1d(in_channels=1, out_channels=d_model, kernel_size=3, padding=1, padding_mode='circular')
self.ini... | 3,846 | 42.715909 | 122 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Transformer/transformer_result.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
import seaborn as sns
import time
import argparse
import random
from transformer imp... | 16,073 | 42.560976 | 222 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/LSTM/lstm_future.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
import seaborn as sns
import matplotlib.pyplot as plt
import time
import argparse
import random
from lstm import LST... | 3,408 | 32.752475 | 139 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/LSTM/lstm.py | #!/bin/bash python
import torch
import torch.nn as nn
class LSTM(nn.Module):
def __init__(self, input_size = 1, hidden_size = 256, num_layers = 1, dropout = 0.1,bidirectional = False):
super(LSTM, self).__init__()
self.num_layers = num_layers
self.hidden_size = hidden_size
self.re... | 1,451 | 34.414634 | 136 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/LSTM/utils.py | #!/bin/bash python
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.preprocessing import StandardScaler
from utils import *
def to_windowed(data,window_size,pred_size):
out = []
for i in range(len(data)-window_size):
feature = np.array(data[i:i+(window_size)])
... | 6,611 | 50.255814 | 177 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/LSTM/lstm_result.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
import seaborn as sns
import matplotlib.pyplot as plt
import time
import argparse
import random
from lstm import LST... | 13,982 | 40.616071 | 222 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/LSTM/lstm_train.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import time
import random
import os
import tensorboard
import ray
from ray import tune
from ray.tune.schedulers import AsyncHyperBandScheduler, ASHAScheduler
from ray.tune import CLIReporter
from lstm import LSTM
from utils... | 4,002 | 32.923729 | 306 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Informer/informer_result.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
import random
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
import seaborn as sns
import time
import argparse
from informer import... | 16,932 | 40.400978 | 222 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Informer/utils.py | #!/bin/bash python
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.preprocessing import StandardScaler
def to_windowed(data,window_size,pred_size):
out = []
for i in range(len(data)-window_size):
feature = np.array(data[i:i+(window_size)])
target = np.arra... | 6,735 | 51.625 | 177 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Informer/informer_train.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import time
import random
import os
import ray
from ray import tune
from ray.tune.schedulers import AsyncHyperBandScheduler, ASHAScheduler
from sklearn.metrics import mean_squared_error
from informer import Informer
from ut... | 5,389 | 38.057971 | 221 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Informer/informer.py | import torch
from torch import optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
import os
import time
from math import sqrt
from typing import List
from pandas.tseries import offsets
from pandas.tseries.frequencies import to_offset
import math
class TriangularCausalMas... | 17,052 | 37.321348 | 118 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/Informer/informer_future.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
import random
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
import seaborn as sns
import time
import argparse
from informer import... | 4,146 | 33.558333 | 136 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/GRU/gru.py | #!/bin/bash python
import torch
import torch.nn as nn
class GRU(nn.Module):
def __init__(self, input_size = 1, hidden_size = 256, num_layers = 1, dropout = 0.1,bidirectional = False):
super(GRU, self).__init__()
self.num_layers = num_layers
self.hidden_size = hidden_size
self.relu... | 1,206 | 33.485714 | 134 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/GRU/utils.py | #!/bin/bash python
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.preprocessing import StandardScaler
def to_windowed(data,window_size,pred_size):
out = []
for i in range(len(data)-window_size):
feature = np.array(data[i:i+(window_size)])
target = np.arra... | 6,735 | 51.625 | 177 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/GRU/gru_future.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
import seaborn as sns
import matplotlib.pyplot as plt
import time
import argparse
import random
from gru import GRU
... | 3,794 | 33.189189 | 138 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/GRU/gru_train.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import time
import random
import os
import tensorboard
import ray
from ray import tune
from ray.tune.schedulers import AsyncHyperBandScheduler, ASHAScheduler
from ray.tune import CLIReporter
from gru import GRU
from utils i... | 3,903 | 33.857143 | 238 | py |
ts_ensemble_sunspot | ts_ensemble_sunspot-main/code/GRU/gru_result.py | #!/bin/bash python
import torch
from torch.utils import tensorboard
import torch.optim as optim
import pandas as pd
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error
import seaborn as sns
import matplotlib.pyplot as plt
import time
import argparse
import random
from gru import GRU
... | 13,883 | 39.955752 | 222 | py |
ABS | ABS-master/abs.py | import pickle
import h5py
import gzip
import numpy as np
import os
import sys
import json
np.set_printoptions(precision=2, linewidth=200, threshold=10000)
os.system('mkdir -p ./temp')
with open('config.json') as config_file:
config = json.load(config_file)
use_pickle = bool(config["use_pickle"])
use_h5 = bool... | 43,274 | 41.635468 | 232 | py |
ABS | ABS-master/reformat_model.py | import os, sys
from keras.models import load_model, Sequential
from keras.layers import Activation, Layer
import numpy as np
import imageio
from keras.datasets import cifar10
from keras import optimizers
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
if __name__ == '__main__':
modelname = 'model_that_does_not_sep... | 1,244 | 33.583333 | 101 | py |
ABS | ABS-master/test_on_all.py | import pickle
import gzip
import numpy as np
import os
import sys
np.set_printoptions(precision=2, linewidth=200, threshold=10000)
import keras
from keras.models import Model, Sequential, model_from_yaml, load_model
from keras import backend as K
import json
from preprocess import CIFAR10
import tensorflow as tf
import... | 4,436 | 36.601695 | 128 | py |
ABS | ABS-master/TrojAI_competition/round4/abs_pytorch1_color_simple_filter4_11_9_d_classifier.py |
import numpy as np
import os, sys
import argparse
import math
import sys
import json
import skimage.io
import random
import torch
import torch.nn.functional as F
import pickle
import time
np.set_printoptions(precision=2, linewidth=200, threshold=10000)
# with open(args.config) as config_file:
# config = json.loa... | 111,751 | 41.107008 | 268 | py |
ABS | ABS-master/TrojAI_competition/round2/abs_pytorch1_color_simple_filter4_8_6_3_determinism.py | import numpy as np
import os, sys
sys.path.append('/trojai')
sys.path.append('./trojai')
import argparse
import math
import sys
import json
import skimage.io
import random
import torch
import torch.nn.functional as F
import pickle
import time
import trojai.datagen.instagram_xforms as tinstx
import wand.image
np.set_p... | 101,134 | 41.963042 | 481 | py |
ABS | ABS-master/TrojAI_competition/round1/abs_pytorch_round1.py | import numpy as np
import os
import argparse
# os.environ["OMP_NUM_THREADS"] = "4" # export OMP_NUM_THREADS=4
# os.environ["OPENBLAS_NUM_THREADS"] = "4" # export OPENBLAS_NUM_THREADS=4
# os.environ["MKL_NUM_THREADS"] = "6" # export MKL_NUM_THREADS=6
# os.environ["VECLIB_MAXIMUM_THREADS"] = "4" # export VECLIB_MAXIMUM_... | 43,213 | 39.844991 | 247 | py |
ABS | ABS-master/TrojAI_competition/round3/abs_pytorch1_color_simple_filter4_10_5_determinism.py | import numpy as np
import os, sys
# sys.path.append('/trojai')
sys.path.append('./trojai')
import argparse
import math
import sys
import json
import skimage.io
import random
import torch
import torch.nn.functional as F
import pickle
import time
import trojai.datagen.instagram_xforms as tinstx
import wand.image
np.set... | 103,713 | 41.999171 | 481 | py |
f-IRL | f-IRL-main/envs/tasks/grid_task.py | import numpy as np
from scipy.stats import multivariate_normal
import torch
import math
# grid is 6x6, reacher is like 0.4x0.4 but centered at (0,0)
def expert_density(task_name, env, goal=None, goal_radius=None, **kwargs):
'''
Generate the state marginal distribution of expert by specifying the reward
Can... | 3,178 | 36.4 | 120 | py |
f-IRL | f-IRL-main/common/sac.py | # '''
# Code from spinningup repo.
# Refer[Original Code]: https://github.com/openai/spinningup/tree/master/spinup/algos/pytorch/sac
# '''
from copy import deepcopy
import itertools
import numpy as np
import torch
from torch.optim import Adam
import gym
import time
import sys
import common.sac_agent as core
def combi... | 24,622 | 41.162671 | 131 | py |
f-IRL | f-IRL-main/common/train_expert.py | import sys, os, time
from ruamel.yaml import YAML
from utils import system
import gym
import numpy as np
import torch
import matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import envs
from common.sac import ReplayBuffer, SAC
from utils.plots.train_plot import plot_sac_curve
... | 4,063 | 34.649123 | 126 | py |
f-IRL | f-IRL-main/common/sac_agent.py | '''
Code from spinningup repo.
Refer[Original Code]: https://github.com/openai/spinningup/tree/master/spinup/algos/pytorch/sac
'''
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
LOG_STD_MAX = 2
LOG_STD_MIN = -20
def mlp(sizes, activa... | 6,695 | 37.262857 | 122 | py |
f-IRL | f-IRL-main/common/train_optimal.py | import sys, os, time
from ruamel.yaml import YAML
from utils import system
import gym
import numpy as np
import torch
import matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import envs
from common.sac import ReplayBuffer, SAC
from firl.models.reward import MLPReward
from utils... | 2,848 | 33.743902 | 164 | py |
f-IRL | f-IRL-main/baselines/discrim.py |
# '''
# Code built on top of https://github.com/KamyarGh/rl_swiss
# Refer[Original Code]: https://github.com/KamyarGh/rl_swiss
# '''
# rl_swiss/rlkit/torch/irl/disc_models/simple_disc_models.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class MLPDisc(nn.Module):
def __init__(
sel... | 2,972 | 28.435644 | 104 | py |
f-IRL | f-IRL-main/baselines/main_samples.py | import sys, os, time
import numpy as np
import math
import gym
from ruamel.yaml import YAML
import envs
import torch
from common.sac import SAC
from baselines.discrim import ResNetAIRLDisc, MLPDisc
from baselines.adv_smm import AdvSMM
from utils import system, collect, logger
import datetime
import dateutil.tz
import... | 4,666 | 33.57037 | 105 | py |
f-IRL | f-IRL-main/baselines/bc.py | # '''
# Behavior cloning MLE(Learnt variance) and (MSE)Fixed variance policy.
# '''
import sys, os, time
import numpy as np
import torch
import gym
from ruamel.yaml import YAML
from common.sac import ReplayBuffer, SAC
import envs
from utils import system, logger, eval
from utils.plots.train_plot_high_dim import plot... | 6,380 | 35.884393 | 157 | py |
f-IRL | f-IRL-main/baselines/adv_smm.py | # '''
# Code built on top of https://github.com/KamyarGh/rl_swiss
# Refer[Original Code]: https://github.com/KamyarGh/rl_swiss
# '''
# rl_swiss/rlkit/torch/state_marginal_matching/adv_smm.py
# rl_swiss/rlkit/core/base_algorithm.py
import numpy as np
import torch
import torch.optim as optim
from torch import nn
from t... | 24,906 | 44.45073 | 132 | py |
f-IRL | f-IRL-main/baselines/main_density.py | import sys, os, time
import numpy as np
import math
import gym
from ruamel.yaml import YAML
import envs
from envs.tasks.grid_task import expert_density
import torch
from common.sac import SAC
from baselines.discrim import ResNetAIRLDisc
from baselines.adv_smm import AdvSMM
from utils import system, collect, logger
im... | 3,961 | 32.576271 | 105 | py |
f-IRL | f-IRL-main/firl/irl_samples.py | '''
f-IRL: Extract policy/reward from specified expert samples
'''
import sys, os, time
import numpy as np
import torch
import gym
from ruamel.yaml import YAML
from firl.divs.f_div_disc import f_div_disc_loss
from firl.divs.f_div import maxentirl_loss
from firl.divs.ipm import ipm_loss
from firl.models.reward import M... | 9,976 | 45.404651 | 142 | py |
f-IRL | f-IRL-main/firl/irl_density.py | '''
f-IRL: Extract policy/reward from specified expert density
'''
import sys, os, time
import numpy as np
import torch
import gym
from ruamel.yaml import YAML
from firl.divs.f_div import f_div_loss, f_div_current_state_loss
from firl.divs.ipm import ipm_loss
from firl.models.reward import MLPReward
from firl.models.... | 9,608 | 43.693023 | 133 | py |
f-IRL | f-IRL-main/firl/models/discrim.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch import autograd
import numpy as np
class ResNetAIRLDisc(nn.Module):
def __init__(
self,
input_dim,
num_layer_blocks=2,
hid_dim=100,
hid_act='relu',
use_bn=True,
... | 7,710 | 33.891403 | 108 | py |
f-IRL | f-IRL-main/firl/models/reward.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class MLPReward(nn.Module):
def __init__(
self,
input_dim,
hidden_sizes=(256,256),
hid_act='tanh',
use_bn=False,
residual=False,
clamp_magnitude=10.0,
device=torch.... | 1,997 | 28.382353 | 93 | py |
f-IRL | f-IRL-main/firl/prior_reward/main.py | import gym
from envs.vectorized_grid import ContinuousGridEnv
from common.sac import ReplayBuffer, SAC
import torch
from utils import system
import argparse
import numpy as np
from firl.prior_reward.util import Discriminator_reward
import os
from os import path as osp
import json
def use_reward(s):
return 'rkl' i... | 6,072 | 37.929487 | 137 | py |
f-IRL | f-IRL-main/firl/prior_reward/plot_reward.py | import gym
from common.sac import ReplayBuffer, SAC
import torch
from utils import system
import argparse
import numpy as np
from firl.prior_reward.util import Discriminator_reward
import os
from os import path as osp
import json
from matplotlib import pyplot as plt
import matplotlib
matplotlib.style.use('seaborn')
d... | 4,370 | 33.148438 | 105 | py |
f-IRL | f-IRL-main/firl/prior_reward/util.py | import torch
from torch import nn
import torch.nn.functional as F
class Discriminator_reward():
def __init__(self, discriminator, mode, rew_clip_max=10., state_indices = [0, 1],
rew_clip_min=-10, reward_scale = 1, device=torch.device("cpu"), agent=None, **kwargs):
self.discriminator = discriminato... | 3,065 | 44.088235 | 132 | py |
f-IRL | f-IRL-main/firl/divs/ipm.py | import numpy as np
import torch
import torch.nn.functional as F
def ipm_loss(metric: str, IS: bool, samples, critic_value, reward_func, device, expert_trajs=None):
# please add eps to expert density, not here
assert metric in ['emd']
s, _, log_a = samples
if expert_trajs is not None:
assert exp... | 1,277 | 40.225806 | 114 | py |
f-IRL | f-IRL-main/firl/divs/f_div.py | import numpy as np
import torch
import torch.nn.functional as F
def f_div_loss(div: str, IS: bool, samples, rho_expert, agent_density, reward_func, device):
# please add eps to expert density, not here
assert div in ['fkl', 'rkl', 'js']
s, _, log_a = samples
N, T, d = s.shape
s_vec = s.reshape(-1,... | 3,336 | 41.240506 | 114 | py |
f-IRL | f-IRL-main/firl/divs/f_div_disc.py | import numpy as np
import torch
import torch.nn.functional as F
def f_div_disc_loss(div: str, IS: bool, samples, disc, reward_func, device, expert_trajs=None):
# please add eps to expert density, not here
assert div in ['fkl', 'rkl', 'js']
s, _, log_a = samples
if expert_trajs is not None:
asse... | 1,617 | 40.487179 | 114 | py |
f-IRL | f-IRL-main/utils/system.py | import os
import numpy as np
import random
import torch
def reproduce(seed):
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
| 312 | 21.357143 | 45 | py |
f-IRL | f-IRL-main/utils/collect.py | import numpy as np
import torch
from utils.it_estimator import entropy as it_entropy
from utils.it_estimator import kldiv
from scipy.stats import multivariate_normal
# Collect samples using the SAC policy
def collect_trajectories_policy(env, sac_agent, n=10000, state_indices=None):
'''
Samples n trajectories f... | 6,914 | 36.994505 | 124 | py |
f-IRL | f-IRL-main/utils/eval.py | from common.sac import ReplayBuffer, SAC
from utils import system, collect, logger
from utils.plots import train_plot
import torch
from sklearn import neighbors
import numpy as np
import gym
import time, copy
def KL_summary(expert_samples, agent_emp_states, env_steps: int, policy_type: str, show_ent=False):
start ... | 4,701 | 39.188034 | 115 | py |
f-IRL | f-IRL-main/utils/plots/train_plot.py | import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import os
import torch
import numpy as np
from scipy.ndimage import uniform_filter
def print_metrics(metrics):
info = ""
for k, v in metrics.items():
info += f" {k}: {v:.2f}"
return info
def plot(samples, reward_fn, kde_fn, dens... | 9,875 | 32.938144 | 109 | py |
RespVAD | RespVAD-master/sad_conv_lstm.py | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from pathlib import Path
from glob import glob
from natsort import natsorted
from sklearn.metrics import f1_score, precision_score, recall_score, roc_curve, roc_auc_score, p... | 18,834 | 42.599537 | 122 | py |
RespVAD | RespVAD-master/sad_mlp.py | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from pathlib import Path
from glob import glob
from natsort import natsorted
from sklearn.metrics import f1_score, precision_score, recall_score, roc_curve, roc_auc_score, p... | 14,368 | 38.259563 | 120 | py |
RespVAD | RespVAD-master/sad_conv.py | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from pathlib import Path
from glob import glob
from natsort import natsorted
from sklearn.metrics import f1_score, precision_score, recall_score, roc_curve, roc_auc_score, p... | 19,145 | 42.513636 | 122 | py |
RespVAD | RespVAD-master/sad_lstm.py | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from pathlib import Path
from glob import glob
from natsort import natsorted
from sklearn.metrics import f1_score, precision_score, recall_score, roc_curve, roc_auc_score, p... | 15,148 | 39.397333 | 122 | py |
RF-VAE | RF-VAE-master/main.py | """main.py"""
import argparse
import numpy as np
import torch
from solver import Solver
from utils import str2bool
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
init_seed = 1
torch.manual_seed(init_seed)
torch.cuda.manual_seed(init_seed)
np.random.seed(init_seed)
def main(args):
ne... | 3,867 | 54.257143 | 133 | py |
RF-VAE | RF-VAE-master/model.py | """model.py"""
import torch.nn as nn
import torch.nn.init as init
class Discriminator(nn.Module):
def __init__(self, z_dim):
super(Discriminator, self).__init__()
self.z_dim = z_dim
self.net = nn.Sequential(
nn.Linear(z_dim, 1000),
nn.LeakyReLU(0.2, True),
... | 7,399 | 29.452675 | 78 | py |
RF-VAE | RF-VAE-master/dataset.py | """dataset.py"""
import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision.datasets import ImageFolder
from torchvision import transforms
def is_power_of_2(num):
return ((num & (num - 1)) == 0) and num != 0
class CustomImageFolder(ImageFolder):
... | 2,923 | 29.14433 | 104 | py |
RF-VAE | RF-VAE-master/ops.py | """ops.py"""
import torch
import torch.nn.functional as F
def recon_loss(x, x_recon):
n = x.size(0)
loss = F.binary_cross_entropy_with_logits(x_recon, x, size_average=False).div(n)
return loss
def kl_divergence(mu, logvar,r):
kld = -0.5*(1+logvar-mu**2-logvar.exp()).sum(1)
lam = -9.9*r + 10.0
... | 704 | 19.735294 | 84 | py |
RF-VAE | RF-VAE-master/solver.py | """solver.py"""
import os
import visdom
from tqdm import tqdm
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from torchvision.utils import make_grid, save_image
from utils import DataGather, mkdirs, grid2gif
from ops import recon_loss, kl_divergence, permute_dims, entropy
... | 19,922 | 42.5 | 123 | py |
FILM-public | FILM-public/main.py | import os, sys
import matplotlib
os.environ['KMP_DUPLICATE_LIB_OK']='True'
os.environ["OMP_NUM_THREADS"] = "1"
if sys.platform == 'darwin':
matplotlib.use("tkagg")
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
import math
import time
import cv2
from torchvision impo... | 36,539 | 42.865546 | 191 | py |
FILM-public | FILM-public/arguments.py | import argparse
import math
import torch
import copy
def get_args():
parser = argparse.ArgumentParser(description='Active-Neural-SLAM')
parser.add_argument('--aithor', type=int, default=0)
parser.add_argument('--alfred', type=int, default=0)
## General Arguments
parser.add_argument('--seed', type=... | 22,979 | 47.481013 | 150 | py |
FILM-public | FILM-public/sem_mapping.py | import torch
import torch.nn as nn
from torch.nn import functional as F
import torchvision.models as models
import numpy as np
from utils.distributions import Categorical, DiagGaussian
from utils.model import get_grid, ChannelPool, Flatten, NNBase
import envs.utils.depth_utils as du
import cv2
import time
class Se... | 7,245 | 39.255556 | 123 | py |
FILM-public | FILM-public/envs/__init__.py | import numpy as np
import torch
from agents.sem_exp_thor import Sem_Exp_Env_Agent_Thor
from .utils.vector_env import VectorEnv
import yaml
import yacs.config
import os
import json
def make_vec_envs(args):
envs = construct_envs_alfred(args)
envs = VecPyTorch(envs, args.device)
return envs
# Adapted fr... | 5,115 | 35.028169 | 165 | py |
FILM-public | FILM-public/envs/utils/vector_env.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from multiprocessing.connection import Connection
from multiprocessing.context import BaseContext
from queue import Queu... | 30,960 | 37.035627 | 120 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.