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 |
|---|---|---|---|---|---|---|
kge_ecotox_regression | kge_ecotox_regression-main/main.py |
"""
TODO:
- Train embedding model.
- Apply embeddings to data.
- Encode data.
- Train,valid,test model
"""
from autoencoder import create_auto_encoder
from model import create_model, CorrelelatedFeatures, ApproxKerasSVM, coeff_determination
import numpy as np
import pandas as pd
from sklearn.model... | 32,681 | 35.394209 | 169 | py |
kge_ecotox_regression | kge_ecotox_regression-main/train_rdf2vec.py |
from pyrdf2vec.graphs import KG
from pyrdf2vec.samplers import UniformSampler
from pyrdf2vec.walkers import RandomWalker
from pyrdf2vec import RDF2VecTransformer
import pandas as pd
from rdflib import Graph, URIRef
import numpy as np
from main import load_data
import rdflib
d = './data/embeddings/'
pdf = [pd... | 1,266 | 27.795455 | 93 | py |
kge_ecotox_regression | kge_ecotox_regression-main/embedding_model.py | from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import Input, Embedding, Dense, Dropout, Conv2D, Flatten, Concatenate, Multiply
import tensorflow as tf
def min_distance_loss(w,epsilon=1.0):
r = tf.reduce_sum(w*w, 1)
r = tf.reshape(r, [-1, 1])
D = r - 2*tf.matmul(w, tf.... | 4,177 | 31.897638 | 108 | py |
kge_ecotox_regression | kge_ecotox_regression-main/pretrained_embedding_models.py |
import sys
import os
from itertools import product
from KGEkeras import DistMult, HolE, TransE, HAKE, ConvE, ComplEx, ConvR, RotatE, pRotatE, ConvKB, CosinE
from kerastuner import RandomSearch, HyperParameters, Objective, Hyperband, BayesianOptimization
from random import choice
from collections import defaultdict
... | 8,625 | 30.140794 | 134 | py |
kge_ecotox_regression | kge_ecotox_regression-main/create_data.py |
"""
TODO:
- Load LC50 data from ECOTOX.
- Take median per chemical species pairs.
- Defined chemical groups.
- Export files per chemical groups and each species.
- Forall chemicals and species export relevant KGs.
"""
from tera.DataAggregation import Taxonomy, Effects, Traits
from tera.... | 10,807 | 30.510204 | 157 | py |
kge_ecotox_regression | kge_ecotox_regression-main/autoencoder.py |
from tensorflow.keras.layers import Dense, GaussianNoise, Input, LayerNormalization
from tensorflow.keras.models import Model
from tensorflow import keras
def create_auto_encoder(input_size, dense_layers = (10,), noise=0):
autoencoder = keras.Sequential()
if noise > 0:
autoencoder.add(GaussianNoise(no... | 613 | 33.111111 | 83 | py |
lepard | lepard-main/main.py | import os, torch, json, argparse, shutil
from easydict import EasyDict as edict
import yaml
from datasets.dataloader import get_dataloader, get_datasets
from models.pipeline import Pipeline
from lib.utils import setup_seed
from lib.tester import get_trainer
from models.loss import MatchMotionLoss
from lib.tictok import... | 3,723 | 32.54955 | 116 | py |
lepard | lepard-main/models/matching.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from models.position_encoding import VolumetricPositionEncoding as VolPE
def log_optimal_transport(scores, alpha, iters, src_mask, tgt_mask ):
b, m, n = scores.shape
if src_mask is None:
ms = m
ns = n
else :
ms = s... | 5,412 | 29.931429 | 118 | py |
lepard | lepard-main/models/loss.py | import torch
import torch.nn as nn
import numpy as np
import open3d as o3d
from lib.benchmark_utils import to_o3d_pcd
from lib.visualization import *
import nibabel.quaternions as nq
from sklearn.metrics import precision_recall_fscore_support
from datasets.utils import blend_scene_flow, multual_nn_correspondence, knn_p... | 18,271 | 38.042735 | 137 | py |
lepard | lepard-main/models/position_encoding.py | import math
import torch
from torch import nn
class VolumetricPositionEncoding(nn.Module):
def __init__(self, config):
super().__init__()
self.feature_dim = config.feature_dim
self.vol_bnds = config.vol_bnds
self.voxel_size = config.voxel_size
self.vol_origin = self.vol_b... | 2,989 | 33.367816 | 160 | py |
lepard | lepard-main/models/backbone.py | from models.blocks import *
import torch.nn.functional as F
import numpy as np
class KPFCN(nn.Module):
def __init__(self, config):
super(KPFCN, self).__init__()
############
# Parameters
############
layer = 0
r = config.first_subsampling_dl * config.conv_radius
... | 6,033 | 36.018405 | 100 | py |
lepard | lepard-main/models/transformer.py | import copy
import math
import torch
from torch import nn
from torch.nn import Module, Dropout
from models.position_encoding import VolumetricPositionEncoding as VolPE
from models.matching import Matching
from models.procrustes import SoftProcrustesLayer
import numpy as np
import random
from scipy.spatial.transform imp... | 10,666 | 36.559859 | 142 | py |
lepard | lepard-main/models/__init__.py | 0 | 0 | 0 | py | |
lepard | lepard-main/models/procrustes.py | import torch
import torch.nn as nn
def topk(data, num_topk):
sort, idx = data.sort(descending=True)
return sort[:num_topk], idx[:num_topk]
class SoftProcrustesLayer(nn.Module):
def __init__(self, config):
super(SoftProcrustesLayer, self).__init__()
self.sample_rate = config.sample_rate
... | 3,591 | 37.623656 | 107 | py |
lepard | lepard-main/models/pipeline.py | from models.blocks import *
from models.backbone import KPFCN
from models.transformer import RepositioningTransformer
from models.matching import Matching
from models.procrustes import SoftProcrustesLayer
class Pipeline(nn.Module):
def __init__(self, config):
super(Pipeline, self).__init__()
self.... | 3,685 | 43.95122 | 154 | py |
lepard | lepard-main/models/blocks.py | import time
import math
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn.init import kaiming_uniform_
from kernels.kernel_points import load_kernels
# from lib.ply import write_ply
def gather(x, idx, method=2):
"""
implementation of a custom gather operation for faste... | 26,090 | 35.956091 | 122 | py |
lepard | lepard-main/cpp_wrappers/cpp_neighbors/setup.py | from distutils.core import setup, Extension
import numpy.distutils.misc_util
# Adding OpenCV to project
# ************************
# Adding sources of the project
# *****************************
SOURCES = ["../cpp_utils/cloud/cloud.cpp",
"neighbors/neighbors.cpp",
"wrapper.cpp"]
module = E... | 619 | 20.37931 | 92 | py |
lepard | lepard-main/cpp_wrappers/cpp_subsampling/setup.py | from distutils.core import setup, Extension
import numpy.distutils.misc_util
# Adding OpenCV to project
# ************************
# Adding sources of the project
# *****************************
SOURCES = ["../cpp_utils/cloud/cloud.cpp",
"grid_subsampling/grid_subsampling.cpp",
"wrapper.cpp... | 633 | 20.862069 | 92 | py |
lepard | lepard-main/datasets/_4dmatch.py | import os, sys, glob, torch
# sys.path.append("../")
[sys.path.append(i) for i in ['.', '..']]
import numpy as np
import torch
import random
from scipy.spatial.transform import Rotation
from torch.utils.data import Dataset
from lib.benchmark_utils import to_o3d_pcd, to_tsfm, KDTree_corr
from lib.utils import load_obj
H... | 5,939 | 32.75 | 123 | py |
lepard | lepard-main/datasets/dataloader.py | import numpy as np
from functools import partial
import torch
import cpp_wrappers.cpp_subsampling.grid_subsampling as cpp_subsampling
import cpp_wrappers.cpp_neighbors.radius_neighbors as cpp_neighbors
from datasets._3dmatch import _3DMatch
from datasets._4dmatch import _4DMatch
from datasets.utils import blend_scene_f... | 24,996 | 37.875583 | 171 | py |
lepard | lepard-main/datasets/utils.py | import numpy as np
# from lib.benchmark_utils import to_o3d_pcd, KDTree_corr
def partition_arg_topK(matrix, K, axis=0):
""" find index of K smallest entries along a axis
perform topK based on np.argpartition
:param matrix: to be sorted
:param K: select and sort the top K items
:param axis: 0 or 1.... | 2,983 | 36.3 | 104 | py |
lepard | lepard-main/datasets/__init__.py | 0 | 0 | 0 | py | |
lepard | lepard-main/datasets/_3dmatch.py | import os, sys, glob, torch
# sys.path.append("../")
[sys.path.append(i) for i in ['.', '..']]
import numpy as np
import torch
import random
from scipy.spatial.transform import Rotation
from torch.utils.data import Dataset
from lib.benchmark_utils import to_o3d_pcd, to_tsfm, KDTree_corr
from lib.utils import load_obj
... | 5,766 | 33.327381 | 116 | py |
lepard | lepard-main/configs/models.py | architectures = dict()
kpfcn_backbone = [
'simple',
'resnetb',
'resnetb_strided',
'resnetb',
'resnetb',
'resnetb_strided',
'resnetb',
'resnetb',
'resnetb_strided',
'resnetb',
'resnetb',
'nearest_upsample',
'unary',
'nearest_upsample',
'unary',
'nearest_up... | 428 | 16.16 | 41 | py |
lepard | lepard-main/lib/tester.py | from lib.trainer import Trainer
import torch
from tqdm import tqdm
from models.loss import MatchMotionLoss as MML
import numpy as np
from models.matching import Matching as CM
import math
class _3DMatchTester(Trainer):
"""
3DMatch tester
"""
def __init__(self,args):
Trainer.__init__(self, args)... | 10,544 | 34.385906 | 164 | py |
lepard | lepard-main/lib/visualization.py |
c_red = (224. / 255., 0 / 255., 125 / 255.)
c_pink = (224. / 255., 75. / 255., 232. / 255.)
c_blue = (0. / 255., 0. / 255., 255. / 255.)
c_green = (0. / 255., 255. / 255., 0. / 255.)
c_gray1 = (100. / 255., 100. / 255., 100. / 255.)
c_gray2 = (175. / 255., 175. / 255., 175. / 255.)
def viz_flow_mayavi( s_pc,flow = No... | 2,352 | 36.951613 | 126 | py |
lepard | lepard-main/lib/timer.py | import time
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0.0
self.sq_sum = 0.0
self.count = 0
def update(self, val, n=1):
... | 1,335 | 22.438596 | 71 | py |
lepard | lepard-main/lib/benchmark_utils.py | import os,re,sys,json,yaml,random, glob, argparse, torch, pickle
from tqdm import tqdm
import numpy as np
from scipy.spatial.transform import Rotation
import open3d as o3d
_EPS = 1e-7 # To prevent division by zero
def viz_coarse_nn_correspondence_mayavi(s_pc, t_pc, good_c, bad_c, f_src_pcd=None, f_tgt_pcd=None, sca... | 11,442 | 31.882184 | 122 | py |
lepard | lepard-main/lib/utils.py | import os,re,sys,json,yaml,random, argparse, torch, pickle
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from scipy.spatial.transform import Rotation
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.distance import minkowski
_EPS = 1e-7 # To prev... | 2,759 | 23.424779 | 82 | py |
lepard | lepard-main/lib/ply.py | #
#
# 0===============================0
# | PLY files reader/writer |
# 0===============================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# function to read/write .ply files
#
# ---------------------... | 10,301 | 28.267045 | 120 | py |
lepard | lepard-main/lib/tictok.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import time
import numpy as np
from collections import defaultdict
class Timer(object):
def __init__(self):
self.reset()
def tic(self):
self.st... | 1,644 | 24.307692 | 130 | py |
lepard | lepard-main/lib/__init__.py | 0 | 0 | 0 | py | |
lepard | lepard-main/lib/trainer.py | import gc
import os
import torch
import torch.nn as nn
import numpy as np
from tensorboardX import SummaryWriter
from tqdm import tqdm
from lib.timer import AverageMeter
from lib.utils import Logger, validate_gradient
from lib.tictok import Timers
class Trainer(object):
def __init__(self, args):
self.c... | 8,861 | 34.590361 | 117 | py |
lepard | lepard-main/kernels/kernel_points.py |
#
#
# 0=================================0
# | Kernel Point Convolutions |
# 0=================================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Functions handling the disposition of kernel points.... | 17,189 | 35.496815 | 120 | py |
sngan.pytorch | sngan.pytorch-master/test.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-25
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cfg
import models
from functions import validate
from utils.utils import set... | 2,425 | 29.708861 | 88 | py |
sngan.pytorch | sngan.pytorch-master/functions.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-25
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
import os
import numpy as np
import torch
import torch.nn as nn
from torchvision.utils import make_grid
from imageio import imsave
from tqdm import tqdm
from copy import deepcopy
import logging... | 6,022 | 32.837079 | 123 | py |
sngan.pytorch | sngan.pytorch-master/cfg.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-25
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
import argparse
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
... | 4,330 | 27.30719 | 78 | py |
sngan.pytorch | sngan.pytorch-master/datasets.py | import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import Dataset
class ImageDataset(object):
def __init__(self, args):
if args.dataset.lower() == 'cifar10':
Dt = datasets.CIFAR10
transform = transforms.Compose([
... | 2,115 | 40.490196 | 101 | py |
sngan.pytorch | sngan.pytorch-master/train.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-25
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cfg
import models
import datasets
from functions import train, validate, Lin... | 6,393 | 37.287425 | 116 | py |
sngan.pytorch | sngan.pytorch-master/models/sngan_64.py | import torch.nn as nn
class GenBlock(nn.Module):
def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1,
activation=nn.ReLU(), upsample=False, n_classes=0):
super(GenBlock, self).__init__()
self.activation = activation
self.upsample = upsample
... | 6,296 | 34.778409 | 107 | py |
sngan.pytorch | sngan.pytorch-master/models/sngan_stl10.py | import torch.nn as nn
class GenBlock(nn.Module):
def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1,
activation=nn.ReLU(), upsample=False, n_classes=0):
super(GenBlock, self).__init__()
self.activation = activation
self.upsample = upsample
... | 6,305 | 34.426966 | 99 | py |
sngan.pytorch | sngan.pytorch-master/models/sngan_cifar10.py | import torch.nn as nn
from .gen_resblock import GenBlock
class Generator(nn.Module):
def __init__(self, args, activation=nn.ReLU(), n_classes=0):
super(Generator, self).__init__()
self.bottom_width = args.bottom_width
self.activation = activation
self.n_classes = n_classes
... | 4,805 | 34.338235 | 107 | py |
sngan.pytorch | sngan.pytorch-master/models/__init__.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-25
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import models.sngan_cifar10
import models.sngan_stl10
| 291 | 21.461538 | 42 | py |
sngan.pytorch | sngan.pytorch-master/models/gen_resblock.py | # -*- coding: utf-8 -*-
# @Date : 3/26/20
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
import torch.nn as nn
class GenBlock(nn.Module):
def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1,
activation=nn.ReLU(), upsample=False, n_... | 1,671 | 33.833333 | 90 | py |
sngan.pytorch | sngan.pytorch-master/utils/cal_fid_stat.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-26
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
import os
import glob
import argparse
import numpy as np
from imageio import imread
import tensorflow as tf
import utils.fid_score as fid
def parse_args():
parser = argparse.ArgumentPar... | 2,264 | 29.2 | 103 | py |
sngan.pytorch | sngan.pytorch-master/utils/utils.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-25
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
import os
import torch
import dateutil.tz
from datetime import datetime
import time
import logging
def create_logger(log_dir, phase='train'):
time_str = time.strftime('%Y-%m-%d-%H-%M')
... | 1,772 | 26.703125 | 75 | py |
sngan.pytorch | sngan.pytorch-master/utils/inception_score.py | # Code derived from tensorflow/tensorflow/models/image/imagenet/classify_image.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tqdm import tqdm
import os.path
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
im... | 3,818 | 36.07767 | 96 | py |
sngan.pytorch | sngan.pytorch-master/utils/__init__.py | # -*- coding: utf-8 -*-
# @Date : 2019-07-25
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from utils import utils
| 261 | 20.833333 | 42 | py |
sngan.pytorch | sngan.pytorch-master/utils/fid_score.py | #!/usr/bin/env python3
""" Calculates the Frechet Inception Distance (FID) to evaluate GANs.
The FID metric calculates the distance between two distributions of images.
Typically, we have summary statistics (mean & covariance matrix) of one
of these distributions, while the 2nd distribution is given by a GAN.
When ru... | 13,063 | 39.196923 | 103 | py |
neu-nbv | neu-nbv-main/scripts/planning/simulator_planning.py | import rospy
import os
import sys
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, root_dir)
import yaml
import argparse
from planner import get_planner
from datetime import datetime
def main():
# planning experiment in simulator using a specific planner
args = pa... | 2,103 | 22.640449 | 76 | py |
neu-nbv | neu-nbv-main/scripts/planning/dtu_experiment.py | import sys
import os
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, root_dir)
from neural_rendering.evaluation.pretrained_model import PretrainedModel
from neural_rendering.data import get_data
from neural_rendering.utils import parser, util
import yaml
from dotmap import... | 13,632 | 34.046272 | 113 | py |
neu-nbv | neu-nbv-main/scripts/planning/simulator_experiment.py | import rospy
import os
import sys
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, root_dir)
import yaml
import argparse
from planner import get_planner
from planner.utils import uniform_sampling
import numpy as np
import scipy.spatial as spatial
from datetime import dateti... | 9,450 | 29.685065 | 94 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/simulator_bridge.py | import rospy
from gazebo_msgs.msg import ModelState
from sensor_msgs.msg import Image, CameraInfo
from cv_bridge import CvBridge
from . import utils
import numpy as np
class SimulatorBridge:
def __init__(self, cfg):
self.cv_bridge = CvBridge()
self.current_rgb = None
self.current_depth = N... | 2,869 | 33.166667 | 77 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/utils.py | from scipy.spatial.transform import Rotation as R
import cv2
import numpy as np
import json
# from rembg import remove
import os
import imageio
def get_roi_mask(rgb):
"""binary mask for ROIs using color thresholding"""
hsv = cv2.cvtColor(np.array(rgb, dtype=np.uint8), cv2.COLOR_RGB2HSV)
lower_red = np.ar... | 7,770 | 26.459364 | 90 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/__init__.py | from .neural_nbv.neural_nbv_planner import NeuralNBVPlanner
from .baselines.random_planner import RandomPlanner
from .baselines.max_distance_planner import MaxDistancePlanner
def get_planner(cfg):
planner_type = cfg["planner_type"]
if planner_type == "neural_nbv":
return NeuralNBVPlanner(cfg)
eli... | 462 | 29.866667 | 62 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/planner.py | from .simulator_bridge import SimulatorBridge
from . import utils
import time
import os
from datetime import datetime
import numpy as np
import imageio.v2 as imageio
import yaml
class Planner:
def __init__(self, cfg):
self.simulator_bridge = SimulatorBridge(cfg["simulation_bridge"])
self.camera_in... | 4,844 | 34.364964 | 87 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/neural_nbv/neural_nbv_planner.py | import numpy as np
from scipy.spatial.transform import Rotation as R
from planner.planner import Planner
from planner.utils import view_to_pose_batch, random_view, uniform_sampling
from neural_rendering.evaluation.pretrained_model import PretrainedModel
import torch
from dotmap import DotMap
from neural_rendering.utils... | 8,864 | 33.901575 | 88 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/baselines/random_planner.py | from planner.planner import Planner
from planner.utils import random_view, uniform_sampling
import numpy as np
class RandomPlanner(Planner):
def __init__(self, cfg):
super().__init__(cfg)
print("initial ")
self.num_candidates = cfg["num_candidates"]
self.view_change = cfg["view_cha... | 1,101 | 32.393939 | 74 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/baselines/max_distance_planner.py | from planner.planner import Planner
from planner.utils import view_to_pose_batch, random_view, uniform_sampling
import numpy as np
from scipy.spatial import distance
class MaxDistancePlanner(Planner):
def __init__(self, cfg):
super().__init__(cfg)
self.num_candidates = cfg["num_candidates"]
... | 1,982 | 34.410714 | 81 | py |
neu-nbv | neu-nbv-main/scripts/utils/plot.py | import seaborn as sb
import matplotlib.pyplot as plt
import pandas
import os
import argparse
from matplotlib.ticker import FormatStrFormatter
from matplotlib.ticker import MaxNLocator
from matplotlib import rc
PLOT_FONT_SIZE = 22
PLOT_LEGEND_SIZE = 18
PLOT_TICKS_SIZE = 18
PLOT_LINE_WIDTH = 4
plt.rcParams["figure.figs... | 6,469 | 29.518868 | 89 | py |
PolSF | PolSF-master/label2dto3d.py | import numpy as np
from skimage import io
from scipy import misc
### The original PolSAR data is downloaded from www.ietr.fr/polsarpro-bio/sanfrancisco.
### Courtesy of CNSA, CSA, ESA, IECAS, ISRO, JAXA, MDA, NASA-JPL, NSOAS.
### The color code and the class are shown as follows:
# SF-ALOS2
# https://www.ietr.fr/polsa... | 2,153 | 45.826087 | 97 | py |
MP-FedXGB | MP-FedXGB-main/VerticalXGBoost.py | import numpy as np
import pandas as pd
from mpi4py import MPI
from datetime import *
from SSCalculation import *
from Tree import *
import math
import time
np.random.seed(10)
clientNum = 4
class LeastSquareLoss:
def gradient(self, actual, predicted):
return -(actual - predicted)
def hess(self, actual, ... | 15,375 | 37.059406 | 179 | py |
MP-FedXGB | MP-FedXGB-main/XGBoost.py | import numpy as np
import progressbar
import pandas as pd
from datetime import *
np.random.seed(10)
class LeastSquareLoss():
def gradient(self, actual, predicted):
return -(actual - predicted)
def hess(self, actual, predicted):
return np.ones_like(actual)
class LogLoss():
def gradient(self... | 14,368 | 39.590395 | 137 | py |
MP-FedXGB | MP-FedXGB-main/SSCalculation.py | import numpy as np
import pandas as pd
from mpi4py import MPI
from datetime import *
import math
import time
from VerticalXGBoost import *
from Tree import *
np.random.seed(10)
clientNum = 4
comm = MPI.COMM_WORLD
class SSCalculate:
def SSSplit(self, data, clientNum):
r = np.array([np.random.uniform(0, 4, (d... | 39,914 | 54.36061 | 208 | py |
MP-FedXGB | MP-FedXGB-main/data_adult_process.py | import pandas as pd
import numpy as np
training_data = './adult.data'
columns = ['Age','Workclass','fnlwgt','Education','EdNum','MaritalStatus',
'Occupation','Relationship','Race','Sex','CapitalGain',
'CapitalLoss','HoursPerWeek','Country','Income']
income = pd.read_csv(training_data, names=colum... | 799 | 39 | 86 | py |
MP-FedXGB | MP-FedXGB-main/Tree.py | import numpy as np
import pandas as pd
from mpi4py import MPI
from datetime import *
import math
import time
from SSCalculation import *
from VerticalXGBoost import *
np.random.seed(10)
clientNum = 4
comm = MPI.COMM_WORLD
class Tree:
def __init__(self, value=None, leftBranch=None, rightBranch=None, col=-1, result=N... | 29,996 | 50.541237 | 257 | py |
fitclip | fitclip-main/gunicorn.conf.py | bind = "0.0.0.0:5000"
reload = True
timeout = 3600
wsgi_app = "demo.app"
| 73 | 13.8 | 21 | py |
fitclip | fitclip-main/util/structured_group_utils.py | """Useful utils when using `DataModuleStructuredGroup`."""
from typing import Any, Mapping, Sequence, Tuple
import torch
from aligner.video_text_module import TYPE_INPUT
from util.tensor_utils import pad
TYPE_MULTI_INPUT = Mapping[str, TYPE_INPUT]
# It's like `default_collate` but instead of a sequence we have a m... | 1,737 | 40.380952 | 110 | py |
fitclip | fitclip-main/util/viz_utils.py | import numpy as np
import torch
import torchvision
from matplotlib import pyplot as plt
from matplotlib.pyplot import subplots_adjust
from torchvision.transforms.functional import to_pil_image
from aligner.encoder.video_text_encoder import VideoTextEncoder
def visualize_images_tensor(images: torch.Tensor) -> plt.Axe... | 1,139 | 29 | 95 | py |
fitclip | fitclip-main/util/tensor_utils.py | from typing import Any, Mapping, Optional, Sequence, TypeVar, Union
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from pytorch_lightning.utilities.apply_func import apply_to_collection
T = TypeVar("T")
def pad(t: torch.Tensor, min_size: int, dim: int = 1, value: Any = 0) -> torch.Tenso... | 3,355 | 49.089552 | 120 | py |
fitclip | fitclip-main/util/typing_utils.py | from os import PathLike
from typing import Union
# See https://stackoverflow.com/a/53418245/1165181
TYPE_PATH = Union[PathLike, str, bytes]
| 141 | 22.666667 | 50 | py |
fitclip | fitclip-main/util/checkpoint_utils.py | from typing import MutableMapping
import torch
from cached_path import cached_path
from util.typing_utils import TYPE_PATH
def state_dict_from_checkpoint_path(checkpoint_path: TYPE_PATH, prefix: str = "") -> MutableMapping[str, torch.Tensor]:
prefix += ("" if prefix.endswith(".") or not prefix else ".")
che... | 472 | 35.384615 | 119 | py |
fitclip | fitclip-main/util/video_utils.py | import os
from typing import Any, Callable, Iterable, Iterator, Optional, Sequence
from torchvision.datasets.video_utils import VideoClips
from util.typing_utils import TYPE_PATH
# From https://en.wikipedia.org/wiki/Video_file_format
VIDEO_FILE_EXTENSIONS = (".3g2", ".3gp", ".amv", ".asf", ".avi", ".drc", ".f4a", ".... | 2,659 | 53.285714 | 119 | py |
fitclip | fitclip-main/util/__init__.py | 0 | 0 | 0 | py | |
fitclip | fitclip-main/util/argparse_with_defaults.py | import argparse
from typing import Any
# Copied from https://github.com/allenai/allennlp/blob/3aafb92/allennlp/commands/__init__.py
class ArgumentParserWithDefaults(argparse.ArgumentParser):
"""Custom argument parser that will display the default value for an argument in the help message. """
_action_default... | 981 | 45.761905 | 111 | py |
fitclip | fitclip-main/util/iter_utils.py | import collections
import itertools
from typing import Any, Iterable, Iterator, Literal, Optional, Sequence, Tuple, TypeVar
T = TypeVar("T")
# See https://stackoverflow.com/a/50938015/1165181
def consume(it: Iterator[Any]) -> None:
collections.deque(it, maxlen=0)
# See https://docs.python.org/3/library/itertoo... | 1,784 | 30.315789 | 93 | py |
fitclip | fitclip-main/scripts/apply_wise_ft.py | #!/usr/bin/env python
import argparse
import torch
from aligner.encoder.clip_video_text_encoder import load_clip_model
from aligner.wise import wise_state_dict
from util.argparse_with_defaults import ArgumentParserWithDefaults
def parse_args() -> argparse.Namespace:
parser = ArgumentParserWithDefaults("Applies ... | 1,526 | 37.175 | 116 | py |
fitclip | fitclip-main/scripts/csv_diff.py | #!/usr/bin/env python
import argparse
import pandas as pd
from util.argparse_with_defaults import ArgumentParserWithDefaults
def parse_args() -> argparse.Namespace:
parser = ArgumentParserWithDefaults()
parser.add_argument("path1", metavar="FILE1")
parser.add_argument("path2", metavar="FILE2")
retur... | 635 | 21.714286 | 80 | py |
fitclip | fitclip-main/scripts/subcorr.py | #!/usr/bin/env python
import argparse
import sys
from typing import Any, Callable, Iterable, MutableMapping, Optional, Sequence, Union
import PIL.Image
import clip
import decord
import numpy as np
import seaborn as sns
import torch
from clip.model import CLIP
from matplotlib import pyplot as plt
from matplotlib.offset... | 4,981 | 35.101449 | 109 | py |
fitclip | fitclip-main/scripts/sample_csv.py | #!/usr/bin/env python
import argparse
import sys
import pandas as pd
from util.argparse_with_defaults import ArgumentParserWithDefaults
def parse_args() -> argparse.Namespace:
parser = ArgumentParserWithDefaults()
parser.add_argument("path", metavar="FILE", nargs="?", default="-")
parser.add_argument("-... | 624 | 21.321429 | 71 | py |
fitclip | fitclip-main/scripts/prepare_trained_clip_checkpoint_for_evaluation.py | #!/usr/bin/env python
import argparse
import torch
from util.checkpoint_utils import state_dict_from_checkpoint_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE")
parser.add_argument("output_path", metavar="OUTPUT_FILE"... | 868 | 27.032258 | 116 | py |
fitclip | fitclip-main/scripts/checkpoint_to_state_dict.py | #!/usr/bin/env python
import argparse
import sys
import torch
from util.checkpoint_utils import state_dict_from_checkpoint_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE")
parser.add_argument("--prefix", default="enco... | 582 | 22.32 | 85 | py |
fitclip | fitclip-main/scripts/list_possible_pos.py | #!/usr/bin/env python
import fileinput
from nltk.corpus import wordnet as wn
from nltk.corpus.reader import POS_LIST
if __name__ == "__main__":
for line in fileinput.input():
if line := line.strip():
print("".join(pos for pos in POS_LIST if wn.synsets(line, pos=pos)))
| 295 | 25.909091 | 80 | py |
fitclip | fitclip-main/scripts/prepare_trained_checkpoint_for_evaluation.py | #!/usr/bin/env python
import argparse
import torch
from cached_path import cached_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE", type=cached_path)
parser.add_argument("output_path", metavar="OUTPUT_FILE")
parser.... | 771 | 26.571429 | 120 | py |
fitclip | fitclip-main/scripts/speech_to_text.py | #!/usr/bin/env python
import sys
from google.cloud.speech_v1p1beta1 import RecognitionAudio, RecognitionConfig, RecognitionMetadata, \
SpeakerDiarizationConfig, SpeechClient
# We use a Python script as the `gcloud` equivalent command doesn't support the enhanced models
# (`gcloud ml speech recognize-long-running... | 2,428 | 47.58 | 118 | py |
fitclip | fitclip-main/scripts/open_clip_checkpoint_to_model.py | #!/usr/bin/env python
import argparse
import torch
from cached_path import cached_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE", type=cached_path)
parser.add_argument("output_path", metavar="OUTPUT_FILE")
return ... | 744 | 25.607143 | 97 | py |
fitclip | fitclip-main/demo/app.py | import json
import random
from typing import Tuple
from flask import Flask, Response, jsonify, request
from flask_cors import CORS, cross_origin
from demo.search import search_in_subtitles
app = application = Flask(__name__, static_url_path="/") # `application` is gunicorn's default, `app` is flask's.
cors = CORS(a... | 1,213 | 30.128205 | 114 | py |
fitclip | fitclip-main/demo/__init__.py | 0 | 0 | 0 | py | |
fitclip | fitclip-main/demo/search.py | import json
import os
import re
from typing import Any, Iterable, Iterator, Mapping, Optional, Sequence
import spacy
import spacy_alignments
from cached_path import cached_path
from spacy.matcher import Matcher
from spacy.tokens import Doc, DocBin, Span, Token
from tqdm.auto import tqdm
RE_MULTIPLE_SPACES = re.compil... | 4,180 | 34.432203 | 111 | py |
fitclip | fitclip-main/aligner/video_text_module.py | from typing import Any, Literal, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
import math
import pytorch_lightning as pl
import torch.distributed.nn
from overrides import overrides
from torch import nn
from torch.nn.modules.loss import _Loss
from aligner.encoder.video_text_encoder import TYPE_OUTPUT, Vid... | 4,376 | 43.663265 | 116 | py |
fitclip | fitclip-main/aligner/__main__.py | #!/usr/bin/env python
import logging
import os
from time import strftime
from typing import Mapping, Optional
import hydra
import torch
from omegaconf import DictConfig
from pytorch_lightning.loggers import NeptuneLogger, TensorBoardLogger
from aligner.cli import create_model_data_module_trainer_and_ckpt_path, init_c... | 4,715 | 43.490566 | 118 | py |
fitclip | fitclip-main/aligner/logger_utils.py | from typing import Optional, Type, TypeVar
import pytorch_lightning as pl
from pytorch_lightning.loggers import LightningLoggerBase, LoggerCollection
T = TypeVar("T", bound=LightningLoggerBase)
def get_logger_by_type(trainer: pl.Trainer, logger_class: Type[T]) -> Optional[T]:
if isinstance(trainer.logger, Logg... | 564 | 32.235294 | 117 | py |
fitclip | fitclip-main/aligner/teacher_student.py | import itertools
from typing import Iterable, Mapping, MutableMapping, Optional, Tuple, Union
import torch.distributed.nn
from overrides import overrides
from torch import nn
from aligner.encoder import video_text_encoder
from aligner.encoder.video_text_encoder import TYPE_TOKENIZER, VideoTextEncoder
from aligner.los... | 10,735 | 54.05641 | 117 | py |
fitclip | fitclip-main/aligner/loss.py | from typing import Literal
import torch
from overrides import overrides
from torch.nn import functional as F
from torch.nn.modules.loss import _Loss
TYPE_REDUCTION = Literal["none", "mean", "sum"]
# noinspection SpellCheckingInspection
TYPE_REDUCTION_KL_DIV = Literal["none", "batchmean", "mean", "sum"]
def _rows_to... | 2,447 | 36.090909 | 105 | py |
fitclip | fitclip-main/aligner/text_video_retrieval.py | from collections import OrderedDict
from typing import Iterable, Mapping, Optional, Sequence, Tuple, Union
import torch
import torch.distributed.nn
from overrides import overrides
from torch import nn
from torchmetrics import Metric, Recall
from aligner.encoder.video_text_encoder import TYPE_OUTPUT
from aligner.metri... | 6,325 | 46.924242 | 115 | py |
fitclip | fitclip-main/aligner/video_text_classification.py | import logging
import math
from typing import Any, Iterable, Mapping, Optional, Sequence, TypeVar
import torch
from overrides import overrides
from pytorch_lightning.callbacks import RichProgressBar
from pytorch_lightning.utilities.apply_func import apply_to_collection
from torch import nn
from torchmetrics import Acc... | 6,045 | 41.879433 | 114 | py |
fitclip | fitclip-main/aligner/cli.py | #!/usr/bin/env python
import copy
import logging
import warnings
from types import MethodType
from typing import Any, Mapping, Optional, Tuple, Type
import hydra
import pytorch_lightning as pl
from cached_path import cached_path
from omegaconf import DictConfig
from pytorch_lightning import seed_everything
from torch.... | 6,809 | 44.099338 | 119 | py |
fitclip | fitclip-main/aligner/wise.py | import copy
from typing import Mapping, TypeVar
import torch
from torch import nn
T = TypeVar("T", bound=nn.Module)
def wise_state_dict(model1: T, model2: T, weight_for_2: float = 0.5) -> Mapping[str, torch.Tensor]:
state_dict1 = dict(model1.named_parameters())
state_dict2 = dict(model2.named_parameters())
... | 779 | 31.5 | 104 | py |
fitclip | fitclip-main/aligner/param_freezer.py | # Inspired from https://github.com/allenai/allennlp/blob/0d8c0fc/allennlp/training/optimizers.py
import logging
import re
from typing import Iterable, Optional, Union
import pytorch_lightning as pl
from overrides import overrides
LOGGER = logging.getLogger(__name__)
class ParamFreezer(pl.Callback):
def __init__... | 1,450 | 32.744186 | 113 | py |
fitclip | fitclip-main/aligner/metrics.py | import torch
from overrides import overrides
from torchmetrics import Metric
class Rank(Metric):
is_differentiable: bool = False
higher_is_better: bool = False
full_state_update: bool = False
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.add_state("ranks", defa... | 1,162 | 30.432432 | 92 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.