repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
risk-slim
risk-slim-master/riskslim/__init__.py
from .coefficient_set import CoefficientSet from .lattice_cpa import run_lattice_cpa, setup_lattice_cpa, finish_lattice_cpa from .utils import load_data_from_csv, print_model
174
57.333333
79
py
risk-slim
risk-slim-master/riskslim/mip.py
from math import ceil, floor import numpy as np from cplex import Cplex, SparsePair, infinity as CPX_INFINITY from .coefficient_set import CoefficientSet from .utils import print_log #todo: add loss cut #todo: add constraint function #todo: default cplex parameters #todo: check cores #todo: pass compute_loss to conver...
17,079
32.754941
134
py
risk-slim
risk-slim-master/riskslim/tests/test_risk_slim.py
import os import pprint import numpy as np import riskslim # Dataset Strategy # # variables: binary, real, # N+: 0, 1, >1 # N-: 0, 1, >1 # Testing Strategy # # loss_computation normal, fast, lookup # max_coefficient 0, 1, >1 # max_L0_value 0, 1, >1 # max_offset 0, 1, Inf # c0_v...
6,690
50.076336
170
py
risk-slim
risk-slim-master/riskslim/tests/test_loss_functions.py
#noinspection import numpy as np import riskslim.loss_functions.fast_log_loss as fast import riskslim.loss_functions.log_loss as normal import riskslim.loss_functions.log_loss_weighted as weighted import riskslim.loss_functions.lookup_log_loss as lookup from riskslim.setup_functions import _setup_training_weights np....
7,112
37.657609
128
py
risk-slim
risk-slim-master/riskslim/tests/__init__.py
0
0
0
py
risk-slim
risk-slim-master/riskslim/loss_functions/log_loss_weighted.py
import numpy as np def log_loss_value(Z, weights, total_weights, rho): """ computes the value and slope of the logistic loss in a numerically stable way supports sample non-negative weights for each example in the training data see http://stackoverflow.com/questions/20085768/ Parameters ------...
3,880
37.425743
88
py
risk-slim
risk-slim-master/riskslim/loss_functions/build_cython_loss_functions.py
#!/usr/bin/env python """ This script builds loss functions using Cython on a local machine. To run this script 1. Change to the directory $REPO_DIR/riskslim/loss_functions 2. Run the following commands in Bash: python2 build_cython_loss_functions.py build_ext --inplace python3 build_cython_loss_functions.py build...
1,404
23.224138
81
py
risk-slim
risk-slim-master/riskslim/loss_functions/log_loss.py
import numpy as np def log_loss_value(Z, rho): """ computes the value and slope of the logistic loss in a numerically stable way see also: http://stackoverflow.com/questions/20085768/ Parameters ---------- Z numpy.array containing training data with shape = (n_rows, n_cols) rho ...
3,795
32.298246
95
py
risk-slim
risk-slim-master/riskslim/loss_functions/__init__.py
from .log_loss import * from .log_loss_weighted import * try: from .fast_log_loss import * except ImportError: print("warning: could not import fast log loss") print("warning: returning handle to standard loss functions") # todo replace with warning object import log_loss as fast_log_loss try: ...
572
27.65
65
py
risk-slim
risk-slim-master/batch/train_risk_slim.py
#!/usr/bin/python """ This file is to train a RiskSLIM model in a batch computing environment It parses command line arguments, and can be called as: python train_risk_slim.py --data="${data_file}" --results="${results_file}" where: data_file csv file containing the training data results_file file name for...
9,707
36.338462
122
py
ShiftCNN
ShiftCNN-master/shiftcnn_quantization.py
import sys import os import numpy as np import pickle import matplotlib.pyplot as plt # N = 2 B = 4 # #model = "squeezenet_v1.1" model = "ResNet-50" SOURCE_PATH = os.environ["HOME"]+"/github/caffe/models/"+model+"/" prototxt = SOURCE_PATH+"train_val.prototxt" source = SOURCE_PATH+model+".caffemodel" qtarget = SOURCE...
1,514
28.134615
120
py
agd
agd-main/main.py
import sys import os import math import argparse import pickle import torch import importlib from tqdm import tqdm from agd import AGD from architecture.fcn import * from architecture.vgg import * from architecture.resnet import * ###############################################################################...
8,893
41.966184
122
py
agd
agd-main/agd.py
import math import torch from torch.optim.optimizer import Optimizer from torch.nn.init import orthogonal_ def singular_value(p): sv = math.sqrt(p.shape[0] / p.shape[1]) if p.dim() == 4: sv /= math.sqrt(p.shape[2] * p.shape[3]) return sv class AGD(Optimizer): def __init__(self, net, ...
1,412
26.173077
81
py
agd
agd-main/architecture/fcn.py
import math import torch.nn as nn import torch.nn.functional as F class FCN(nn.Module): def __init__(self, depth, width, input_dim, output_dim, bias=False): super(FCN, self).__init__() self.initial = nn.Linear(input_dim, width, bias=bias) self.layers = nn.ModuleList([nn.Linear(widt...
718
28.958333
97
py
agd
agd-main/architecture/resnet.py
import math import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import Any, Callable, List, Optional, Type, Union import torch import torch.nn as nn from torch import Tensor ### For CIFAR-10 def PreActResNet18(output_dim): return PreActResNet(PreActBlock, ...
14,531
35.512563
118
py
agd
agd-main/architecture/vgg.py
import torch.nn as nn def VGG11(output_dim): return VGG_CIFAR([64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], output_dim) def VGG13(output_dim): return VGG_CIFAR([64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], output_dim) def VGG16(output_dim): return VGG_CIFAR([64, 64, 'M'...
1,587
44.371429
156
py
agd
agd-main/architecture/__init__.py
0
0
0
py
agd
agd-main/latex/algorithm/agd.py
import math import torch from torch.nn.init import orthogonal_ def singular_value(p): sv = math.sqrt(p.shape[0] / p.shape[1]) if p.dim() == 4: sv /= math.sqrt(p.shape[2] * p.shape[3]) return sv class AGD: @torch.no_grad() def __init__(self, net, gain=1.0): self.net = net ...
1,174
26.97619
77
py
agd
agd-main/data/cifar100.py
from torchvision import datasets, transforms def getData(): mean = (0.5071, 0.4867, 0.4408) std = (0.2675, 0.2565, 0.2761) transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Norm...
764
27.333333
96
py
agd
agd-main/data/cifar10.py
from torchvision import datasets, transforms def getData(): mean = (0.4914, 0.4822, 0.4465) std = (0.2023, 0.1994, 0.2010) transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Norm...
761
27.222222
95
py
agd
agd-main/data/__init__.py
0
0
0
py
agd
agd-main/data/imagenet.py
import os from torchvision import datasets, transforms def getData(): mean = (0.485, 0.456, 0.406) std = (0.229, 0.224, 0.225) traindir = os.path.join(os.getenv('IMAGENET_PATH'), "train") valdir = os.path.join(os.getenv('IMAGENET_PATH'), "val") trainset = datasets.ImageFolder( traindir, ...
887
25.117647
64
py
agd
agd-main/data/mnist.py
from torchvision import datasets, transforms def getData(): mean = (0.1307,) std = (0.3081,) transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean, std) ]) trainset = datasets.MNIST('./data', train=True, download=True, transform=transform) testset =...
493
25
87
py
aldiplusplus
aldiplusplus-main/forecasting_results.py
import os import argparse import glob import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from functools import partial from collections import defaultdict from sklearn.linear_model import Ridge from sklearn.metrics import mean_squared_log_error, mean_squared_error from utils ...
3,154
35.264368
96
py
aldiplusplus
aldiplusplus-main/train_lgb_meter.py
import os import argparse import yaml from datetime import datetime import lightgbm as lgb import numpy as np from utils import ( timer, Logger, make_dir, rmsle, load_data, get_validation_months, ) parser = argparse.ArgumentParser(description="") parser.add_argument( "--overwrite", action...
8,108
32.097959
129
py
aldiplusplus
aldiplusplus-main/predict_lgb_meter.py
import argparse import glob import yaml import numpy as np import pandas as pd import lightgbm as lgb from utils import ( Logger, timer, rmsle, load_data, make_dir, ) parser = argparse.ArgumentParser(description="") parser.add_argument( "--normalize_target", action="store_true", help="...
4,845
25.480874
97
py
aldiplusplus
aldiplusplus-main/aldi_gmm_dyn_none_both.py
from scipy import stats import math import torch #import stumpy import pyscamp import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.mplot3d import Axes3D import seaborn as sns import calmap # not working with latest pandas import calplot import joypy import sys impo...
43,203
36.865031
135
py
aldiplusplus
aldiplusplus-main/utils.py
import os import time import pickle import pandas as pd import seaborn as sns import numpy as np import matplotlib import datetime from datetime import datetime from contextlib import contextmanager, redirect_stdout from functools import partial from sklearn.metrics import mean_squared_error from sklearn.preprocessing...
20,883
34.336717
124
py
aldiplusplus
aldiplusplus-main/vae.py
import torch from torch import nn from torch.utils.data import DataLoader class VAE(nn.Module): def __init__(self, num_input, latent_dim, hidden_size=[300, 200, 100]): super().__init__() self.latent_dim = latent_dim self.num_input = num_input self.encoder = nn.Sequential( ...
1,984
30.015625
75
py
aldiplusplus
aldiplusplus-main/aldi_evaluation_metrics.py
from functools import reduce from sklearn.metrics import accuracy_score from sklearn.metrics import roc_auc_score from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np class AldiEvalua...
9,212
33.897727
112
py
aldiplusplus
aldiplusplus-main/prepare_predictions.py
import os import argparse import glob import numpy as np import pandas as pd from functools import partial from sklearn.linear_model import Ridge from sklearn.metrics import mean_squared_error from utils import ( load_data, rmsle, timer, GeneralizedMeanBlender ) parser = argparse.ArgumentParser(desc...
1,835
28.142857
92
py
aldiplusplus
aldiplusplus-main/data_import_ashrae.py
import numpy as np import pandas as pd class DataImportAshrae(): """ class provides different methods to import BDG2 data for experiments with Discord Detectors """ def __init__(self): """ method initializes df_all_data """ self.df_all_data = None def get_met...
14,877
39.210811
146
py
aldiplusplus
aldiplusplus-main/anomaly_detection.py
import warnings import os import sys import logging import yaml import wandb import torch import pandas as pd from sklearn.cluster import SpectralClustering, KMeans from sklearn.metrics import silhouette_score from datetime import timedelta from collections import Counter from matplotlib import pyplot as plt from util...
7,508
37.116751
210
py
aldiplusplus
aldiplusplus-main/preprocess_modeling.py
import gc import sys import logging import yaml import numpy as np import pandas as pd from pandas.tseries.holiday import USFederalHolidayCalendar as calendar from utils import timer, load_data, reduce_mem_usage from encoders import GaussianTargetEncoder # define groupings and corresponding priors groups_and_priors = ...
10,908
38.241007
94
py
aldiplusplus
aldiplusplus-main/encoders.py
import numpy as np class FastLabelEncoder(): """Map categorical variable into {0, 1, ..., n_categories}. Note: https://stackoverflow.com/questions/45321999/how-can-i-optimize-label-encoding-for-large-data-sets-sci-kit-learn?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa ...
2,816
33.353659
199
py
aldiplusplus
aldiplusplus-main/GMM_training.py
import pandas as pd import numpy as np from sklearn.mixture import GaussianMixture class GMMTraining(): def __init__(self, values): self.values = np.array([[val] for val in values]) self.x_values = np.linspace(0, 1, 1000) ''' p_values = np.array([ [val] for val in df_pD_values.p....
1,803
33.037736
89
py
aldiplusplus
aldiplusplus-main/aldi.py
from scipy import stats import stumpy import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import calmap # not working with latest pandas import calplot import joypy import sys import time import datetime as dt class ALDI(): def __init__(self, df_meters, df_metadata, m=24, c...
19,418
37.993976
119
py
pytorch_RVAE
pytorch_RVAE-master/sample.py
import argparse import os import numpy as np import torch as t from utils.batch_loader import BatchLoader from utils.parameters import Parameters from model.rvae import RVAE if __name__ == '__main__': assert os.path.exists('trained_RVAE'), \ 'trained model not found' parser = argparse.ArgumentParse...
1,265
31.461538
78
py
pytorch_RVAE
pytorch_RVAE-master/__init__.py
from . import nn_layers from . import utility
46
14.666667
23
py
pytorch_RVAE
pytorch_RVAE-master/train_word_embeddings.py
import argparse import numpy as np import torch as t from torch.autograd import Variable from torch.optim import SGD from utils.batch_loader import BatchLoader from utils.parameters import Parameters from selfModules.neg import NEG_loss if __name__ == '__main__': parser = argparse.ArgumentParser(description='wo...
2,183
36.016949
116
py
pytorch_RVAE
pytorch_RVAE-master/train.py
import argparse import os import numpy as np import torch as t from torch.optim import Adam from utils.batch_loader import BatchLoader from utils.parameters import Parameters from model.rvae import RVAE if __name__ == "__main__": if not os.path.exists('data/word_embeddings.npy'): raise FileNotFoundError...
4,032
37.04717
102
py
pytorch_RVAE
pytorch_RVAE-master/selfModules/embedding.py
import numpy as np import torch as t import torch.nn as nn from torch.nn import Parameter from .tdnn import TDNN class Embedding(nn.Module): def __init__(self, params, path='../../../'): super(Embedding, self).__init__() self.params = params word_embed = np.load(path + 'data/word_embedd...
2,001
37.5
98
py
pytorch_RVAE
pytorch_RVAE-master/selfModules/highway.py
import torch.nn as nn import torch.nn.functional as F class Highway(nn.Module): def __init__(self, size, num_layers, f): super(Highway, self).__init__() self.num_layers = num_layers self.nonlinear = [nn.Linear(size, size) for _ in range(num_layers)] for i, module in enumerate(se...
1,743
33.88
105
py
pytorch_RVAE
pytorch_RVAE-master/selfModules/neg.py
import torch as t import torch.nn as nn from torch.autograd import Variable from torch.nn import Parameter from utils.functional import * class NEG_loss(nn.Module): def __init__(self, num_classes, embed_size): """ :param num_classes: An int. The number of possible classes. :param embed_si...
2,619
37.529412
118
py
pytorch_RVAE
pytorch_RVAE-master/selfModules/tdnn.py
import torch as t from torch.nn import Parameter import torch.nn as nn import torch.nn.functional as F class TDNN(nn.Module): def __init__(self, params): super(TDNN, self).__init__() self.params = params self.kernels = [Parameter(t.Tensor(out_dim, self.params.char_embed_size, kW).uniform...
1,769
33.038462
117
py
pytorch_RVAE
pytorch_RVAE-master/selfModules/__init__.py
0
0
0
py
pytorch_RVAE
pytorch_RVAE-master/utils/visualize_word_embeddings.py
import os import matplotlib.pyplot as plt import numpy as np from sklearn.decomposition import PCA from utils.batch_loader import BatchLoader if __name__ == "__main__": if not os.path.exists('../../data/word_embeddings.npy'): raise FileNotFoundError("word embeddings file was't found") pca = PCA(n_co...
807
25.933333
67
py
pytorch_RVAE
pytorch_RVAE-master/utils/functional.py
def fold(f, l, a): return a if (len(l) == 0) else fold(f, l[1:], f(a, l[0])) def f_and(x, y): return x and y def f_or(x, y): return x or y def parameters_allocation_check(module): parameters = list(module.parameters()) return fold(f_and, parameters, True) or not fold(f_or, parameters, False) ...
648
19.28125
77
py
pytorch_RVAE
pytorch_RVAE-master/utils/batch_loader.py
import collections import os import re import numpy as np from six.moves import cPickle from .functional import * class BatchLoader: def __init__(self, path='../../'): ''' :properties data_files - array containing paths to data sources idx_files - array of ...
14,202
42.434251
119
py
pytorch_RVAE
pytorch_RVAE-master/utils/parameters.py
from .functional import * class Parameters: def __init__(self, max_word_len, max_seq_len, word_vocab_size, char_vocab_size): self.max_word_len = int(max_word_len) self.max_seq_len = int(max_seq_len) + 1 # go or eos token self.word_vocab_size = int(word_vocab_size) self.char_vocab...
780
30.24
90
py
pytorch_RVAE
pytorch_RVAE-master/utils/__init__.py
0
0
0
py
pytorch_RVAE
pytorch_RVAE-master/model/rvae.py
import numpy as np import torch as t import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from .decoder import Decoder from .encoder import Encoder from selfModules.embedding import Embedding from utils.functional import kld_coef, parameters_allocation_check, fold class RVAE(nn...
7,319
38.567568
119
py
pytorch_RVAE
pytorch_RVAE-master/model/encoder.py
import torch as t import torch.nn as nn import torch.nn.functional as F from selfModules.highway import Highway from utils.functional import parameters_allocation_check class Encoder(nn.Module): def __init__(self, params): super(Encoder, self).__init__() self.params = params self.hw1 = ...
1,685
34.125
115
py
pytorch_RVAE
pytorch_RVAE-master/model/decoder.py
import torch as t import torch.nn as nn import torch.nn.functional as F from utils.functional import parameters_allocation_check class Decoder(nn.Module): def __init__(self, params): super(Decoder, self).__init__() self.params = params self.rnn = nn.LSTM(input_size=self.params.latent_va...
2,142
39.433962
103
py
pytorch_RVAE
pytorch_RVAE-master/model/__init__.py
0
0
0
py
semantic-abstraction
semantic-abstraction-main/plot_utils.py
import numpy as np from matplotlib.patches import Patch import matplotlib.pyplot as plt import io from PIL import Image import open3d as o3d from skimage.measure import block_reduce import matplotlib.cm as cm import matplotlib as mpl def plot_to_png(fig): buf = io.BytesIO() plt.savefig(buf, format="png") ...
6,575
33.429319
84
py
semantic-abstraction
semantic-abstraction-main/generate_relevancy.py
from typing import List from pathlib import Path import h5py import torch from tqdm import tqdm import ray from utils import write_to_hdf5 from filelock import FileLock import numpy as np from CLIP.clip import ClipWrapper, saliency_configs, imagenet_templates from dataset import synonyms, deref_h5py import typer import...
18,591
39.77193
88
py
semantic-abstraction
semantic-abstraction-main/fusion.py
# Copyright (c) 2018 Andy Zeng # Source: https://github.com/andyzeng/tsdf-fusion-python/blob/master/fusion.py # BSD 2-Clause License # Copyright (c) 2019, Princeton University # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the fo...
14,231
39.31728
88
py
semantic-abstraction
semantic-abstraction-main/point_cloud.py
import pybullet_data import numpy as np from numba import njit, prange import pybullet as p import matplotlib.pyplot as plt def transform_pointcloud(xyz_pts, rigid_transform): """Apply rigid transformation to 3D pointcloud. Args: xyz_pts: Nx3 float array of 3D points rigid_transform: 3x4 or 4x...
9,990
33.451724
113
py
semantic-abstraction
semantic-abstraction-main/summarize.py
import pandas as pd import rich import pickle from dataset import synonyms import numpy as np from rich.console import Console from rich.table import Table test_objs = set( map(lambda l: l.rstrip().lstrip(), open("test_semantic_classes.txt", "r")) ) def summarize_ovssc(metric="voxel32x32x32_iou"): ssc_approa...
10,203
36.105455
87
py
semantic-abstraction
semantic-abstraction-main/train_vool.py
from typing import Dict, Tuple, Union import numpy as np from dataset import ObjectLocalizationDataset from net import ( SemAbsVOOL, ClipSpatialVOOL, SemanticAwareVOOL, ) import utils from torch.nn.functional import binary_cross_entropy_with_logits import torch import pandas as pd def get_detailed_stats( ...
8,243
34.230769
88
py
semantic-abstraction
semantic-abstraction-main/utils.py
from __future__ import annotations import os import pickle import signal from typing import Optional, Tuple, Type import numpy as np import pandas as pd import torch from torch.backends import cudnn from tqdm import tqdm from transformers import get_scheduler from argparse import ArgumentParser import random from CLIP....
27,394
35.526667
88
py
semantic-abstraction
semantic-abstraction-main/dataset.py
import numpy as np import torch from torch.utils.data import Dataset from fusion import TSDFVolume from point_cloud import ( check_pts_in_frustum, filter_pts_bounds, get_pointcloud, ) from typing import List, Optional, Tuple import h5py from transforms3d import affines, euler from torchtyping import TensorT...
52,891
41.689266
138
py
semantic-abstraction
semantic-abstraction-main/net.py
from typing import List, Tuple import torch from torch.nn import ( Sequential, LeakyReLU, Linear, Module, Dropout, ParameterDict, ) from torch.nn.parameter import Parameter from torch.nn.functional import grid_sample from torch_scatter import scatter import numpy as np from unet3d import Residua...
25,154
36.047128
88
py
semantic-abstraction
semantic-abstraction-main/eval.py
import pandas as pd import numpy as np from tqdm import tqdm import torch import os import pickle from dataset import ObjectLocalizationDataset, SceneCompletionDataset from train_vool import get_losses as vool_get_losses, approach as vool_approaches from train_ovssc import get_losses as ovssc_get_losses, approach as ov...
3,625
37.574468
86
py
semantic-abstraction
semantic-abstraction-main/unet3d.py
""" Code from the 3D UNet implementation: https://github.com/wolny/pytorch-3dunet/ """ import importlib import torch import torch.nn as nn from torch.nn import functional as F from functools import partial def number_of_features_per_level(init_channel_number, num_levels): return [init_channel_number * 2**k for k ...
25,729
36.289855
144
py
semantic-abstraction
semantic-abstraction-main/visualize.py
import io import logging from pathlib import Path import textwrap from typing import Any, Dict, List, Tuple from skimage.measure import marching_cubes import numpy as np import torch import os import pickle from net import SemAbs3D, SemAbsVOOL from point_cloud import ( check_pts_in_frustum, filter_pts_bounds, ...
23,057
35.084507
110
py
semantic-abstraction
semantic-abstraction-main/train_ovssc.py
import numpy as np import torch from torch.nn.functional import binary_cross_entropy_with_logits from net import SemAbs3D, SemanticAwareOVSSC import utils import pandas as pd from dataset import SceneCompletionDataset from typing import Dict, Tuple, Union def get_detailed_stats( prediction, gt_label, xyz_...
6,693
32.808081
87
py
semantic-abstraction
semantic-abstraction-main/generate_thor_data.py
import logging import re from copy import deepcopy import shutil from argparse import ArgumentParser from typing import List import ray from ai2thor.controller import Controller from ai2thor.platform import CloudRendering from matplotlib import pyplot as plt import numpy as np import torch from transforms3d import aff...
46,662
37.405761
91
py
semantic-abstraction
semantic-abstraction-main/arm/utils.py
# Adapted from: https://github.com/stepjam/ARM/blob/main/arm/utils.py import torch import numpy as np from scipy.spatial.transform import Rotation import pyrender import trimesh from pyrender.trackball import Trackball def normalize_quaternion(quat): return np.array(quat) / np.linalg.norm(quat, axis=-1, keepdim...
7,072
32.842105
88
py
semantic-abstraction
semantic-abstraction-main/arm/network_utils.py
# Adapted from https://github.com/stepjam/ARM/blob/main/arm/network_utils.py import copy from typing import List, Union import numpy as np import torch import torch.nn as nn import torch.nn.functional as F LRELU_SLOPE = 0.02 def act_layer(act): if act == "relu": return nn.ReLU() elif act == "lrelu"...
23,208
30.363514
88
py
semantic-abstraction
semantic-abstraction-main/arm/__init__.py
0
0
0
py
semantic-abstraction
semantic-abstraction-main/arm/optim/__init__.py
0
0
0
py
semantic-abstraction
semantic-abstraction-main/arm/optim/lamb.py
# From https://github.com/cybertronai/pytorch-lamb/blob/master/pytorch_lamb/lamb.py """Lamb optimizer.""" import collections import math import torch from torch.optim import Optimizer # def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int): # """Log a histogram of trust ratio sca...
5,163
39.34375
103
py
semantic-abstraction
semantic-abstraction-main/CLIP/setup.py
import os import pkg_resources from setuptools import setup, find_packages setup( name="clip", py_modules=["clip"], version="1.0", description="", author="OpenAI", packages=find_packages(exclude=["tests*"]), install_requires=[ str(r) for r in pkg_resources.parse_requirement...
491
21.363636
77
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/clip_explainability.py
# modified from: https://github.com/hila-chefer/Transformer-MM-Explainability/blob/main/CLIP/clip/clip.py import hashlib import os import urllib import warnings from typing import Any, Union, List from pkg_resources import packaging import torch from PIL import Image from torchvision.transforms import Compose, Resize...
9,663
34.270073
154
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/simple_tokenizer.py
import gzip import html import os from functools import lru_cache import ftfy import regex as re @lru_cache() def default_bpe(): return os.path.join( os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz" ) @lru_cache() def bytes_to_unicode(): """ Returns list of utf-8 b...
4,851
31.13245
111
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/auxiliary.py
# adding hooks, copied from: https://github.com/hila-chefer/Transformer-MM-Explainability/blob/e63b4ab0d0722faa11ff2f7549c4f88074e7edd7/CLIP/clip/auxilary.py import torch import warnings from typing import Tuple, Optional import torch from torch import Tensor from torch.nn.init import xavier_uniform_ from torch.nn.ini...
21,829
38.981685
157
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/clip.py
import hashlib import os import urllib import warnings from typing import Any, Union, List import torch from PIL import Image from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize from tqdm import tqdm from .model import build_model from .simple_tokenizer import SimpleTokenizer as _Token...
9,497
33.791209
154
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/model.py
from collections import OrderedDict from typing import Tuple, Union import numpy as np import torch import torch.nn.functional as F from torch import nn from .auxiliary import interpolate_positional_emb class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1): super(...
20,260
33.457483
112
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/clip_gradcam.py
from typing import List import torch import torch.nn as nn from .clip_explainability import load from .clip import tokenize from torch import device import numpy as np import torch.nn.functional as nnf import itertools def zeroshot_classifier(clip_model, classnames, templates, device): with torch.no_grad(): ...
5,420
36.909091
165
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/__init__.py
from .clip import * from .clip_gradcam import ClipGradcam import torch import numpy as np from PIL import Image import torchvision from functools import reduce def factors(n): return set( reduce( list.__add__, ([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0), ...
12,890
33.934959
88
py
semantic-abstraction
semantic-abstraction-main/CLIP/clip/model_explainability.py
# modified from: https://github.com/hila-chefer/Transformer-MM-Explainability/blob/main/CLIP/clip/model.py from collections import OrderedDict from typing import Tuple, Union import numpy as np import torch import torch.nn.functional as F from torch import nn from .auxiliary import ( multi_head_attention_forward, ...
20,409
32.84743
112
py
semantic-abstraction
semantic-abstraction-main/CLIP/tests/test_consistency.py
import numpy as np import pytest import torch from PIL import Image import clip @pytest.mark.parametrize("model_name", clip.available_models()) def test_consistency(model_name): device = "cpu" jit_model, transform = clip.load(model_name, device=device, jit=True) py_model, _ = clip.load(model_name, device...
812
30.269231
73
py
UniVL
UniVL-main/main_task_retrieval.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from __future__ import print_function import torch from torch.utils.data import (SequentialSampler) import numpy as np import random import os from metrics import compute_metrics import time import argparse f...
24,353
46.28932
144
py
UniVL
UniVL-main/main_pretrain.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from __future__ import print_function import torch from torch.utils.data import (SequentialSampler) import numpy as np import random import os from collections import OrderedDict import pickle import time imp...
19,914
47.691932
140
py
UniVL
UniVL-main/main_task_caption.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from __future__ import print_function import torch from torch.utils.data import (SequentialSampler) import numpy as np import random import os from collections import OrderedDict from nlgeval import NLGEval i...
33,617
47.792453
151
py
UniVL
UniVL-main/util.py
import torch import torch.nn as nn import threading from torch._utils import ExceptionWrapper import logging def get_a_var(obj): if isinstance(obj, torch.Tensor): return obj if isinstance(obj, list) or isinstance(obj, tuple): for result in map(get_a_var, obj): if isinstance(result,...
2,495
33.191781
99
py
UniVL
UniVL-main/metrics.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from __future__ import print_function import numpy as np def compute_metrics(x): sx = np.sort(-x, axis=1) d = np.diag(-x) d = d[:, np.newaxis] ind = sx - d ind = np.where(ind == 0) in...
796
27.464286
92
py
UniVL
UniVL-main/modules/module_visual.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
19,708
45.374118
139
py
UniVL
UniVL-main/modules/optimization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # # 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/LICENS...
7,260
42.220238
141
py
UniVL
UniVL-main/modules/module_decoder.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
18,283
43.923833
138
py
UniVL
UniVL-main/modules/tokenization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # # 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/LICENS...
16,424
39.158924
219
py
UniVL
UniVL-main/modules/modeling.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
22,558
51.707944
153
py
UniVL
UniVL-main/modules/until_module.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
10,299
39.873016
114
py
UniVL
UniVL-main/modules/beam.py
""" Manage beam search info structure. Heavily borrowed from OpenNMT-py. For code in OpenNMT-py, please check the following link (maybe in oldest version): https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/Beam.py """ import torch class Constants(): def __init__(self): self.PAD = 0 self.UNK =...
3,840
31.82906
97
py
UniVL
UniVL-main/modules/module_bert.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
21,157
46.333333
139
py
UniVL
UniVL-main/modules/module_cross.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
17,516
43.346835
108
py
UniVL
UniVL-main/modules/file_utils.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ import os import logging import shutil import tempfile import json from urllib.parse import urlparse from pathlib import Path from typing ...
8,021
32.425
98
py
UniVL
UniVL-main/modules/__init__.py
0
0
0
py