Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
lightly
lightly-master/tests/loss/test_VICRegLLoss.py
import unittest from typing import List import numpy as np import torch import torch.nn.functional as F from torch import Tensor from lightly.loss import VICRegLLoss class TestVICRegLLoss(unittest.TestCase): def test_forward(self) -> None: torch.manual_seed(0) criterion = VICRegLLoss() g...
6,906
36.134409
116
py
lightly
lightly-master/tests/loss/test_VICRegLoss.py
import unittest import pytest import torch import torch.nn.functional as F from pytest_mock import MockerFixture from torch import Tensor from torch import distributed as dist from lightly.loss import VICRegLoss class TestVICRegLoss: def test__gather_distributed(self, mocker: MockerFixture) -> None: moc...
5,386
32.459627
116
py
lightly
lightly-master/tests/loss/test_barlow_twins_loss.py
import pytest from pytest_mock import MockerFixture from torch import distributed as dist from lightly.loss.barlow_twins_loss import BarlowTwinsLoss class TestBarlowTwinsLoss: def test__gather_distributed(self, mocker: MockerFixture) -> None: mock_is_available = mocker.patch.object(dist, "is_available", ...
792
33.478261
88
py
lightly
lightly-master/tests/models/test_ModelUtils.py
import copy import unittest import torch import torch.nn as nn from lightly.models import utils from lightly.models.utils import ( _no_grad_trunc_normal, activate_requires_grad, batch_shuffle, batch_unshuffle, deactivate_requires_grad, nearest_neighbors, normalize_weight, update_moment...
13,742
35.357143
87
py
lightly
lightly-master/tests/models/test_ModelsBYOL.py
import unittest import torch import torch.nn as nn import torchvision import lightly from lightly.models import BYOL, ResNetGenerator def get_backbone(resnet, num_ftrs=64): last_conv_channels = list(resnet.children())[-1].in_features backbone = nn.Sequential( lightly.models.batchnorm.get_norm_layer(...
4,235
35.205128
87
py
lightly
lightly-master/tests/models/test_ModelsMoCo.py
import unittest import torch import torch.nn as nn import torchvision import lightly from lightly.models import MoCo, ResNetGenerator def get_backbone(resnet, num_ftrs=64): last_conv_channels = list(resnet.children())[-1].in_features backbone = nn.Sequential( lightly.models.batchnorm.get_norm_layer(...
4,132
36.572727
82
py
lightly
lightly-master/tests/models/test_ModelsNNCLR.py
import unittest import torch import torch.nn as nn import torchvision from lightly.models import NNCLR from lightly.models.modules import NNMemoryBankModule def resnet_generator(name: str): if name == "resnet18": return torchvision.models.resnet18() elif name == "resnet50": return torchvisio...
5,345
41.094488
83
py
lightly
lightly-master/tests/models/test_ModelsSimCLR.py
import unittest import torch import torch.nn as nn import torchvision import lightly from lightly.models import ResNetGenerator, SimCLR def get_backbone(resnet, num_ftrs=64): last_conv_channels = list(resnet.children())[-1].in_features backbone = nn.Sequential( lightly.models.batchnorm.get_norm_laye...
4,146
36.7
82
py
lightly
lightly-master/tests/models/test_ModelsSimSiam.py
import unittest import torch import torch.nn as nn import torchvision from lightly.models import SimSiam def resnet_generator(name: str): if name == "resnet18": return torchvision.models.resnet18() elif name == "resnet50": return torchvision.models.resnet50() raise NotImplementedError ...
4,483
40.137615
83
py
lightly
lightly-master/tests/models/test_ProjectionHeads.py
import unittest import torch import lightly from lightly.models.modules.heads import ( BarlowTwinsProjectionHead, BYOLPredictionHead, BYOLProjectionHead, DINOProjectionHead, MoCoProjectionHead, MSNProjectionHead, NNCLRPredictionHead, NNCLRProjectionHead, SimCLRProjectionHead, S...
12,093
42.503597
87
py
lightly
lightly-master/tests/models/modules/test_masked_autoencoder.py
import unittest import torch import torchvision from lightly import _torchvision_vit_available from lightly.models import utils if _torchvision_vit_available: from lightly.models.modules import MAEBackbone, MAEDecoder, MAEEncoder @unittest.skipUnless(_torchvision_vit_available, "Torchvision ViT not available")...
4,602
34.407692
85
py
lightly
lightly-master/tests/transforms/test_GaussianBlur.py
import unittest from PIL import Image from lightly.transforms import GaussianBlur class TestGaussianBlur(unittest.TestCase): def test_on_pil_image(self): for w in range(1, 100): for h in range(1, 100): gaussian_blur = GaussianBlur() sample = Image.new("RGB", (...
651
27.347826
51
py
lightly
lightly-master/tests/transforms/test_Jigsaw.py
import unittest from PIL import Image from lightly.transforms import Jigsaw class TestJigsaw(unittest.TestCase): def test_on_pil_image(self): crop = Jigsaw() sample = Image.new("RGB", (255, 255)) crop(sample)
241
17.615385
45
py
lightly
lightly-master/tests/transforms/test_Solarize.py
import unittest from PIL import Image from lightly.transforms.solarize import RandomSolarization class TestRandomSolarization(unittest.TestCase): def test_on_pil_image(self): for w in [32, 64, 128]: for h in [32, 64, 128]: solarization = RandomSolarization(0.5) ...
393
25.266667
58
py
lightly
lightly-master/tests/transforms/test_dino_transform.py
from PIL import Image from lightly.transforms.dino_transform import DINOTransform, DINOViewTransform def test_view_on_pil_image(): single_view_transform = DINOViewTransform(crop_size=32) sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (3, 32, 32) ...
710
31.318182
80
py
lightly
lightly-master/tests/transforms/test_fastsiam_transform.py
from PIL import Image from lightly.transforms.fast_siam_transform import FastSiamTransform def test_multi_view_on_pil_image(): multi_view_transform = FastSiamTransform(num_views=3, input_size=32) sample = Image.new("RGB", (100, 100)) output = multi_view_transform(sample) assert len(output) == 3 a...
441
30.571429
72
py
lightly
lightly-master/tests/transforms/test_location_to_NxN_grid.py
import torch import lightly.transforms.random_crop_and_flip_with_grid as test_module def test_location_to_NxN_grid(): # create a test instance of the Location class test_location = test_module.Location( left=10, top=20, width=100, height=200, image_height=244, ...
1,105
30.6
77
py
lightly
lightly-master/tests/transforms/test_mae_transform.py
from PIL import Image from lightly.transforms.mae_transform import MAETransform def test_multi_view_on_pil_image(): multi_view_transform = MAETransform(input_size=32) sample = Image.new("RGB", (100, 100)) output = multi_view_transform(sample) assert len(output) == 1 assert output[0].shape == (3, ...
328
26.416667
57
py
lightly
lightly-master/tests/transforms/test_moco_transform.py
from PIL import Image from lightly.transforms.moco_transform import MoCoV1Transform, MoCoV2Transform def test_moco_v1_multi_view_on_pil_image(): multi_view_transform = MoCoV1Transform(input_size=32) sample = Image.new("RGB", (100, 100)) output = multi_view_transform(sample) assert len(output) == 2 ...
702
30.954545
78
py
lightly
lightly-master/tests/transforms/test_msn_transform.py
from PIL import Image from lightly.transforms.msn_transform import MSNTransform, MSNViewTransform def test_view_on_pil_image(): single_view_transform = MSNViewTransform(crop_size=32) sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (3, 32, 32) def ...
696
30.681818
75
py
lightly
lightly-master/tests/transforms/test_multi_crop_transform.py
from lightly.transforms.multi_crop_transform import MultiCropTranform
70
34.5
69
py
lightly
lightly-master/tests/transforms/test_multi_view_transform.py
import unittest import torchvision.transforms as T from PIL import Image from lightly.transforms.multi_view_transform import MultiViewTransform def test_multi_view_on_pil_image(): multi_view_transform = MultiViewTransform( [ T.RandomHorizontalFlip(p=0.1), T.RandomVerticalFlip(p=0...
489
23.5
70
py
lightly
lightly-master/tests/transforms/test_pirl_transform.py
from PIL import Image from lightly.transforms.pirl_transform import PIRLTransform def test_multi_view_on_pil_image(): multi_view_transform = PIRLTransform(input_size=32) sample = Image.new("RGB", (100, 100)) output = multi_view_transform(sample) assert len(output) == 2 assert output[0].shape == (...
376
28
59
py
lightly
lightly-master/tests/transforms/test_rotation.py
from PIL import Image from lightly.transforms.rotation import ( RandomRotate, RandomRotateDegrees, random_rotation_transform, ) def test_RandomRotate_on_pil_image(): random_rotate = RandomRotate() sample = Image.new("RGB", (100, 100)) random_rotate(sample) def test_RandomRotateDegrees_on_pi...
941
30.4
75
py
lightly
lightly-master/tests/transforms/test_simclr_transform.py
from PIL import Image from lightly.transforms.simclr_transform import SimCLRTransform, SimCLRViewTransform def test_view_on_pil_image(): single_view_transform = SimCLRViewTransform(input_size=32) sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (3, 3...
619
30
84
py
lightly
lightly-master/tests/transforms/test_simsiam_transform.py
from PIL import Image from lightly.transforms.simsiam_transform import SimSiamTransform, SimSiamViewTransform def test_view_on_pil_image(): single_view_transform = SimSiamViewTransform(input_size=32) sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (...
624
30.25
87
py
lightly
lightly-master/tests/transforms/test_smog_transform.py
from PIL import Image from lightly.transforms.smog_transform import SMoGTransform, SmoGViewTransform def test_view_on_pil_image(): single_view_transform = SmoGViewTransform(crop_size=32) sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (3, 32, 32) ...
653
31.7
78
py
lightly
lightly-master/tests/transforms/test_swav_transform.py
from PIL import Image from lightly.transforms.swav_transform import SwaVTransform, SwaVViewTransform def test_view_on_pil_image(): single_view_transform = SwaVViewTransform() sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (3, 100, 100) def test_m...
643
31.2
78
py
lightly
lightly-master/tests/transforms/test_vicreg_transform.py
from PIL import Image from lightly.transforms.vicreg_transform import VICRegTransform, VICRegViewTransform def test_view_on_pil_image(): single_view_transform = VICRegViewTransform(input_size=32) sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (3, 3...
619
30
84
py
lightly
lightly-master/tests/transforms/test_vicregl_transform.py
from PIL import Image from lightly.transforms.vicregl_transform import VICRegLTransform, VICRegLViewTransform def test_view_on_pil_image(): single_view_transform = VICRegLViewTransform() sample = Image.new("RGB", (100, 100)) output = single_view_transform(sample) assert output.shape == (3, 100, 100) ...
1,086
32.96875
87
py
lightly
lightly-master/tests/utils/__init__.py
0
0
0
py
lightly
lightly-master/tests/utils/test_debug.py
import math import unittest import numpy as np import torch from PIL import Image from lightly.data import collate from lightly.utils import debug try: import matplotlib.pyplot as plt MATPLOTLIB_AVAILABLE = True except ImportError: MATPLOTLIB_AVAILABLE = False BATCH_SIZE = 10 DIMENSION = 10 class Tes...
3,075
35.619048
85
py
lightly
lightly-master/tests/utils/test_dist.py
import unittest from unittest import mock import torch from lightly.utils import dist class TestDist(unittest.TestCase): def test_eye_rank_undist(self): self.assertTrue(torch.all(dist.eye_rank(3) == torch.eye(3))) def test_eye_rank_dist(self): n = 3 zeros = torch.zeros((n, n)).bool(...
1,158
33.088235
76
py
lightly
lightly-master/tests/utils/test_io.py
import csv import json import sys import tempfile import unittest import numpy as np from lightly.utils.io import ( check_embeddings, check_filenames, save_custom_metadata, save_embeddings, save_schema, save_tasks, ) from tests.api_workflow.mocked_api_workflow_client import ( MockedApiWork...
6,311
36.129412
88
py
lightly
lightly-master/tests/utils/test_scheduler.py
import unittest import torch from torch import nn from lightly.utils.scheduler import CosineWarmupScheduler, cosine_schedule class TestScheduler(unittest.TestCase): def test_cosine_schedule(self): self.assertAlmostEqual(cosine_schedule(1, 10, 0.99, 1.0), 0.99030154, 6) self.assertAlmostEqual(cos...
2,304
34.461538
81
py
lightly
lightly-master/tests/utils/test_version_compare.py
import unittest from lightly.utils import version_compare class TestVersionCompare(unittest.TestCase): def test_valid_versions(self): # general test of smaller than version numbers self.assertEqual(version_compare.version_compare("0.1.4", "1.2.0"), -1) self.assertEqual(version_compare.ver...
1,259
36.058824
88
py
lightly
lightly-master/tests/utils/benchmarking/__init__.py
0
0
0
py
lightly
lightly-master/tests/utils/benchmarking/test_benchmark_module.py
import unittest import torch from pytorch_lightning import Trainer from torch.nn import CrossEntropyLoss, Flatten, Linear, Sequential from torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets import FakeData from torchvision.transforms import ToTensor from lightly.data import Light...
2,840
32.034884
84
py
lightly
lightly-master/tests/utils/benchmarking/test_knn.py
import torch import torch.nn.functional as F from lightly.utils.benchmarking import knn def test_knn() -> None: feature_bank = torch.tensor( [ [1.0, 1.0, 1.0], [-1.0, 1.0, 1.0], [-1.0, -1.0, 1.0], [-1.0, -1.0, -1.0], ] ).t() feature_labels =...
1,832
25.185714
91
py
lightly
lightly-master/tests/utils/benchmarking/test_knn_classifier.py
from typing import Tuple import pytest import torch from pytorch_lightning import Trainer from torch import Tensor, nn from torch.utils.data import DataLoader, Dataset from lightly.utils.benchmarking import KNNClassifier class TestKNNClassifier: def test(self) -> None: # Define 4 training points from 4 ...
5,630
41.659091
88
py
lightly
lightly-master/tests/utils/benchmarking/test_linear_classifier.py
import torch from pytorch_lightning import Trainer from torch import nn from torch.utils.data import DataLoader from torchvision.datasets import FakeData from torchvision.transforms import ToTensor from lightly.utils.benchmarking import LinearClassifier class TestLinearClassifier: def test__finetune(self) -> Non...
4,403
41.346154
88
py
lightly
lightly-master/tests/utils/benchmarking/test_metric_callback.py
import torch from pytorch_lightning import LightningModule, Trainer from torch.utils.data import DataLoader from torchvision.datasets import FakeData from torchvision.transforms import ToTensor from lightly.utils.benchmarking import MetricCallback class TestMetricCallback: def test(self) -> None: callbac...
1,673
36.2
81
py
lightly
lightly-master/tests/utils/benchmarking/test_online_linear_classifier.py
import pytest import torch from pytorch_lightning import LightningModule, Trainer from torch import Tensor, nn from torch.optim import SGD from torch.utils.data import DataLoader from torchvision.datasets import FakeData from torchvision.transforms import ToTensor from lightly.utils.benchmarking import OnlineLinearCla...
2,948
36.807692
85
py
lightly
lightly-master/tests/utils/benchmarking/test_topk.py
import torch from lightly.utils.benchmarking import topk def test_mean_topk_accuracy() -> None: predicted_classes = torch.tensor( [ [1, 2, 3, 4], [4, 1, 10, 0], [3, 1, 5, 8], ] ) targets = torch.tensor([1, 10, 8]) assert topk.mean_topk_accuracy(pred...
460
19.954545
86
py
BioNEV
BioNEV-master/README.md
# BioNEV (Biomedical Network Embedding Evaluation) ## 1. Introduction This repository contains source code and datasets for paper ["Graph Embedding on Biomedical Networks: Methods, Applications, and Evaluations"](https://arxiv.org/pdf/1906.05017.pdf) (accepted by **Bioinformatics**). This work aims to systematically e...
10,080
57.953216
513
md
BioNEV
BioNEV-master/setup.py
# -*- coding: utf-8 -*- """Setup module.""" import setuptools if __name__ == '__main__': setuptools.setup()
115
11.888889
26
py
BioNEV
BioNEV-master/src/bionev/__init__.py
# -*- coding: utf-8 -*-
24
11.5
23
py
BioNEV
BioNEV-master/src/bionev/__main__.py
# -*- coding: utf-8 -*- """Entrypoint module, in case you use ``python -m bionev``. Why does this file exist, and why ``__main__``? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from .main import more_main if __name__ == '__main__':...
337
23.142857
68
py
BioNEV
BioNEV-master/src/bionev/embed_train.py
# -*- coding: utf-8 -*- import ast import logging import os from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence from bionev.GAE.train_model import gae_model from bionev.OpenNE import gf, grarep, hope, lap, line, node2vec, sdne from bionev.SVD.model import SVD_embedding from bionev.stru...
4,371
36.367521
115
py
BioNEV
BioNEV-master/src/bionev/evaluation.py
# -*- coding: utf-8 -*- from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, average_precision_score, f1_score, roc_auc_score from sklearn.multiclass import OneVsRestClassifier from sklearn.preprocessing import MultiLabelBinarizer from bionev.utils import * def LinkPredict...
4,002
37.12381
103
py
BioNEV
BioNEV-master/src/bionev/main.py
# -*- coding: utf-8 -*- import datetime import getpass import json import os import random import time from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser import numpy as np from bionev.embed_train import embedding_training, load_embedding, read_node_labels, split_train_test_graph from bionev.evaluati...
9,368
46.318182
135
py
BioNEV
BioNEV-master/src/bionev/utils.py
# -*- coding: utf-8 -*- import copy import itertools import random import networkx as nx import numpy as np import bionev.OpenNE.graph as og import bionev.struc2vec.graph as sg def read_for_OpenNE(filename, weighted=False): G = og.Graph() print("Loading training graph for learning embedding...") G.read...
6,094
33.050279
105
py
BioNEV
BioNEV-master/src/bionev/GAE/__init__.py
# -*- coding: utf-8 -*-
24
11.5
23
py
BioNEV
BioNEV-master/src/bionev/GAE/initialization.py
# -*- coding: utf-8 -*- import numpy as np import tensorflow as tf def weight_variable_glorot(input_dim, output_dim, name=""): """Create a weight variable with Glorot & Bengio (AISTATS 2010) initialization. """ init_range = np.sqrt(6.0 / (input_dim + output_dim)) initial = tf.random_uniform([inpu...
472
30.533333
76
py
BioNEV
BioNEV-master/src/bionev/GAE/layers.py
# -*- coding: utf-8 -*- import tensorflow as tf from bionev.GAE.initialization import * # global unique layer ID dictionary for layer name assignment _LAYER_UIDS = {} def get_layer_uid(layer_name=''): """Helper function, assigns unique layer IDs """ if layer_name not in _LAYER_UIDS: _LAYER_UIDS...
4,048
31.392
107
py
BioNEV
BioNEV-master/src/bionev/GAE/model.py
# -*- coding: utf-8 -*- import tensorflow as tf from bionev.GAE.layers import GraphConvolution, GraphConvolutionSparse, InnerProductDecoder flags = tf.app.flags FLAGS = flags.FLAGS class Model(object): def __init__(self, **kwargs): allowed_kwargs = {'name', 'logging'} for kwarg in kwargs.keys()...
5,047
39.709677
109
py
BioNEV
BioNEV-master/src/bionev/GAE/optimizer.py
# -*- coding: utf-8 -*- import tensorflow as tf class OptimizerAE(object): def __init__(self, preds, labels, pos_weight, norm, learning_rate): preds_sub = preds labels_sub = labels self.cost = norm * tf.reduce_mean( tf.nn.weighted_cross_entropy_with_logits(logits=preds_sub, t...
1,989
44.227273
118
py
BioNEV
BioNEV-master/src/bionev/GAE/preprocessing.py
# -*- coding: utf-8 -*- import numpy as np import scipy.sparse as sp def sparse_to_tuple(sparse_mx): if not sp.isspmatrix_coo(sparse_mx): sparse_mx = sparse_mx.tocoo() coords = np.vstack((sparse_mx.row, sparse_mx.col)).transpose() values = sparse_mx.data shape = sparse_mx.shape return coo...
4,060
34.938053
104
py
BioNEV
BioNEV-master/src/bionev/GAE/train_model.py
# -*- coding: utf-8 -*- import time import numpy as np import scipy.sparse as sp import tensorflow as tf from bionev.GAE.model import GCNModelAE, GCNModelVAE from bionev.GAE.optimizer import OptimizerAE, OptimizerVAE from bionev.GAE.preprocessing import construct_feed_dict, preprocess_graph, sparse_to_tuple # # Tr...
5,069
41.605042
114
py
BioNEV
BioNEV-master/src/bionev/OpenNE/__init__.py
# -*- coding: utf-8 -*-
24
11.5
23
py
BioNEV
BioNEV-master/src/bionev/OpenNE/classify.py
# -*- coding: utf-8 -*- import numpy from sklearn.metrics import f1_score from sklearn.multiclass import OneVsRestClassifier from sklearn.preprocessing import MultiLabelBinarizer class TopKRanker(OneVsRestClassifier): def predict(self, X, top_k_list): probs = numpy.asarray(super(TopKRanker, self).predict...
3,142
30.747475
90
py
BioNEV
BioNEV-master/src/bionev/OpenNE/gf.py
# -*- coding: utf-8 -*- import numpy as np import tensorflow as tf __author__ = "Wang Binlu" __email__ = "wblmail@whu.edu.cn" class GraphFactorization(object): def __init__(self, graph, rep_size=128, epoch=120, learning_rate=0.003, weight_decay=1.): self.g = graph self.node_size = graph.G.numbe...
2,561
33.621622
117
py
BioNEV
BioNEV-master/src/bionev/OpenNE/graph.py
# -*- coding: utf-8 -*- """Graph utilities.""" import networkx as nx import numpy as np __author__ = "Zhang Zhengyan" __email__ = "zhangzhengyan14@mails.tsinghua.edu.cn" class Graph(object): def __init__(self): self.G = None self.look_up_dict = {} self.look_back_list = [] self....
3,533
28.45
79
py
BioNEV
BioNEV-master/src/bionev/OpenNE/grarep.py
# -*- coding: utf-8 -*- import numpy as np from scipy.sparse.linalg import svds from sklearn.preprocessing import normalize class GraRep(object): def __init__(self, graph, Kstep, dim): self.g = graph self.Kstep = Kstep assert dim % Kstep == 0 self.dim = int(dim / Kstep) s...
3,001
35.168675
79
py
BioNEV
BioNEV-master/src/bionev/OpenNE/hope.py
# -*- coding: utf-8 -*- import networkx as nx import numpy as np import scipy.sparse.linalg as lg __author__ = "Alan WANG" __email__ = "alan1995wang@outlook.com" class HOPE(object): def __init__(self, graph, d): ''' d: representation vector dimension ''' self._d = d sel...
1,605
25.766667
73
py
BioNEV
BioNEV-master/src/bionev/OpenNE/lap.py
# -*- coding: utf-8 -*- import networkx as nx import numpy as np from scipy.sparse.linalg import eigsh __author__ = "Wang Binlu" __email__ = "wblmail@whu.edu.cn" class LaplacianEigenmaps(object): def __init__(self, graph, rep_size=128): self.g = graph self.node_size = self.g.G.number_of_nodes() ...
2,399
33.285714
90
py
BioNEV
BioNEV-master/src/bionev/OpenNE/line.py
# -*- coding: utf-8 -*- import math import random import numpy as np import tensorflow as tf from sklearn.linear_model import LogisticRegression from bionev.OpenNE.classify import Classifier, read_node_label class _LINE(object): def __init__(self, graph, rep_size=128, batch_size=1000, negative_ratio=5, order=...
11,252
39.478417
114
py
BioNEV
BioNEV-master/src/bionev/OpenNE/node2vec.py
# -*- coding: utf-8 -*- from gensim.models import Word2Vec from bionev.OpenNE import walker class Node2vec(object): def __init__(self, graph, path_length, num_paths, dim, p=1.0, q=1.0, dw=False, **kwargs): kwargs["workers"] = kwargs.get("workers", 1) if dw: kwargs["hs"] = 1 ...
1,593
31.530612
93
py
BioNEV
BioNEV-master/src/bionev/OpenNE/sdne.py
# -*- coding: utf-8 -*- import numpy as np import tensorflow as tf __author__ = "Wang Binlu" __email__ = "wblmail@whu.edu.cn" def fc_op(input_op, name, n_out, layer_collector, act_func=tf.nn.leaky_relu): n_in = input_op.get_shape()[-1].value with tf.name_scope(name) as scope: kernel = tf.Variable(tf...
11,631
36.766234
119
py
BioNEV
BioNEV-master/src/bionev/OpenNE/walker.py
# -*- coding: utf-8 -*- import random import numpy as np def deepwalk_walk_wrapper(class_instance, walk_length, start_node): class_instance.deepwalk_walk(walk_length, start_node) class BasicWalker: def __init__(self, G, workers): self.G = G.G self.node_size = G.node_size self.look_...
6,186
28.461905
123
py
BioNEV
BioNEV-master/src/bionev/SVD/__init__.py
0
0
0
py
BioNEV
BioNEV-master/src/bionev/SVD/model.py
import networkx as nx import numpy as np from scipy.sparse.linalg import svds def SVD_embedding(G, output_filename, size=100): node_list = list(G.nodes()) adjacency_matrix = nx.adjacency_matrix(G, node_list) adjacency_matrix = adjacency_matrix.astype(float) # adjacency_matrix = sparse.csc_matrix(adjac...
949
30.666667
69
py
BioNEV
BioNEV-master/src/bionev/struc2vec/__init__.py
# -*- coding: utf-8 -*-
24
11.5
23
py
BioNEV
BioNEV-master/src/bionev/struc2vec/algorithms.py
# -*- coding: utf-8 -*- import math import random from collections import deque from concurrent.futures import ProcessPoolExecutor, as_completed import numpy as np from bionev.struc2vec.utils import * def generate_parameters_random_walk(workers): logging.info('Loading distances_nets from disk...') sum_wei...
6,624
30.103286
115
py
BioNEV
BioNEV-master/src/bionev/struc2vec/algorithms_distances.py
# -*- coding: utf-8 -*- import math import os from collections import deque from concurrent.futures import ProcessPoolExecutor, as_completed import numpy as np from fastdtw import fastdtw from bionev.struc2vec.utils import * limiteDist = 20 def getDegreeListsVertices(g, vertices, calcUntilLayer): degreeList =...
20,177
28.074928
128
py
BioNEV
BioNEV-master/src/bionev/struc2vec/graph.py
# -*- coding: utf-8 -*- """Graph utilities.""" import logging from collections import Iterable, defaultdict from concurrent.futures import ProcessPoolExecutor from io import open from itertools import permutations from multiprocessing import cpu_count from time import time from six import iterkeys from six.moves imp...
6,465
22.512727
102
py
BioNEV
BioNEV-master/src/bionev/struc2vec/struc2vec.py
# -*- coding: utf-8 -*- from bionev.struc2vec.algorithms import * from bionev.struc2vec.algorithms_distances import * class Graph: def __init__(self, g, workers, is_directed=False, untilLayer=None): logging.info(" - Converting graph to dict...") self.G = g.gToDict() logging.info("Graph c...
6,956
31.059908
119
py
BioNEV
BioNEV-master/src/bionev/struc2vec/utils.py
# -*- coding: utf-8 -*- import inspect import logging import os.path import pickle as pickle from itertools import islice from time import time dir_f = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) folder_pickles = dir_f + "/pickles/" def returnPathStruc2vec(): return dir_f def isP...
1,341
23.851852
92
py
null
LERG-main/README.md
# LERG LERG (Local Explanation of Response Generation) is a unified approach to explain why a conditional text generation model will predict a text. For more details, please refer to the paper [Local Explanation of Dialogue Response Generation, Neurips 2021](https://arxiv.org/pdf/2106.06528.pdf). ## Install LERG c...
3,445
41.02439
164
md
null
LERG-main/eval.py
from target_models import GPT from lerg.metrics import ppl_c, ppl_c_add from lerg.visualize import plot_interactions import tqdm import sys import json import torch import numpy as np import os from datetime import datetime from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("--explain_m...
3,915
44.534884
164
py
null
LERG-main/explain.py
from lerg.perturbation_models import RandomPM, LIMERandomPM from lerg.RG_explainers import LERG_LIME, LERG_R, LERG_SHAP, LERG_SHAP_log from target_models import GPT import torch import tqdm import sys import json import os from datetime import datetime from argparse import ArgumentParser parser = ArgumentParser() par...
2,528
36.746269
136
py
null
LERG-main/target_models.py
import torch import torch.nn.functional as F from transformers import OpenAIGPTTokenizer, OpenAIGPTLMHeadModel from transformers import GPT2Tokenizer, GPT2LMHeadModel def get_sum_multi_head_attentions(multi_head_attentions): return sum(torch.sum(x,1) for x in multi_head_attentions) class GPT: def __init__(sel...
4,007
55.450704
135
py
null
LERG-main/lerg/RG_explainers.py
import math import torch import torch.nn as nn import torch.nn.functional as F import pdb from sklearn.metrics.pairwise import pairwise_distances from sklearn.linear_model import Ridge import numpy as np import random class Explainer(): """ The base class for various explainers arguments: model_f:...
8,905
39.666667
166
py
null
LERG-main/lerg/__init__.py
0
0
0
py
null
LERG-main/lerg/metrics.py
import torch import numpy as np import random import pdb from scipy.stats import skew from collections import Counter def get_expl(x, expl, ratio=0.2, remain_masks=False): if expl is None: x_entities = [tok for tok in x if random.random() < ratio] if not remain_masks else [tok if random.random() < ratio e...
2,391
33.666667
171
py
null
LERG-main/lerg/perturbation_models.py
import torch import warnings import math import random import numpy as np import pdb import scipy as sp import sklearn from transformers import BartTokenizer, BartForConditionalGeneration import torch def binomial_coef_dist(n): dist = [math.comb(n, i+1) for i in range(n//2)] total = sum(dist) dist = [dens...
4,757
33.230216
130
py
null
LERG-main/lerg/visualize.py
import numpy as np import matplotlib.pyplot as plt def plot_interactions(phi_map,x,y): values = np.around([[phi_map[(i,j)].item() for i in range(len(x))] for j in range(len(y))], decimals=2) fig = plt.figure() ax = plt.axes() im = ax.imshow(values, cmap=plt.get_cmap('Reds')) ax.set_xticks(np.arang...
733
33.952381
107
py
null
vnncomp2021_results-main/README.md
# vnncomp2021_results results for vnncomp 2021. The csv files for all tools are in results_csv. The scores are computed using process_results.py, with stdout redirected to the output_*.txt files. Summary scores are near the end of the file. You can check a specific benchmark by looking in the file. For example, to se...
3,058
57.826923
283
md
null
vnncomp2021_results-main/process_results.py
""" Process vnncomp results Stanley Bak """ from typing import Dict, List import glob import csv from pathlib import Path from collections import defaultdict import numpy as np class ToolResult: """Tool's result""" # columns CATEGORY = 0 NETWORK = 1 PROP = 2 PREPARE_TIME = 3 RESULT = 4 ...
18,053
32.557621
125
py
null
vnncomp2021_results-main/compare_cifar2020/README.md
comparison for cifar between 2020 and 2021. The numbered files are created using tail to get the last 138 benchmarks from last years results files. For example: tail -n 138 ggn-all-verinet.txt > 6.txt sum.py is then executed to print out the summary statistics in the table
278
33.875
116
md
null
vnncomp2021_results-main/compare_cifar2020/sum.py
'stanley bak' def main(): 'main entry point' vio2021 = 0 holds2021 = 0 with open('2021.csv') as f: for line in f: if '(v)' in line: vio2021 += 1 elif '(h)' in line: holds2021 += 1 unknown2021 = 138 - vio2021 - holds2021 print(f"...
1,367
26.36
110
py
null
emil-main/README.md
<img src="images/emil.png" width="800" /> # EMIL Implementation of the EMIL architecture. Illustrated with MNIST and a simplified ResNet backbone. ## Usage ```python import torch from emil import EMIL net = EMIL( output_type = 'multiclass', num_inp_channels = 1, num_fmap_channels = 128, att_dim = 128, num...
1,491
23.866667
119
md
null
emil-main/emil.py
import torch from torch import nn from resnet import resnet18 class EMIL(nn.Module): def __init__(self, output_type, num_inp_channels, num_fmap_channels, att_dim, num_classes, patch_size, patch_stride, k_min): super().__init__() self.num_classes = num_classes self.k_min = k_min sel...
1,789
34.098039
128
py
null
emil-main/main.py
import os import numpy as np import torch from torch import nn import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.utils.data import DataLoader from emil import EMIL os.environ["CUDA_VISIBLE_DEVICES"] = "0" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')...
2,595
25.222222
101
py
null
emil-main/resnet.py
from typing import Type, Any, Callable, Union, List, Optional import torch import torch.nn as nn from torch import Tensor from torch.hub import load_state_dict_from_url # from https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py, based on commit d367a01 # changes forward method to output feature ...
15,042
36.327543
118
py
null
emil-main/vis.py
import os import sys import torch import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.utils.data import DataLoader from emil import EMIL from vis_utils import * os.environ["CUDA_VISIBLE_DEVICES"]="0" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') img_s...
2,153
27.72
129
py
null
emil-main/vis_utils.py
import numpy as np from matplotlib import pyplot as plt import torch from torch import nn def get_heatmap(patch_scores, fmap_dims, patch_size, patch_stride, img_size): """ Returns a heatmap of *img_size* *patch_scores* is either patch pred probabilities or attention weights """ device = ...
2,330
36
126
py
evo
evo-master/README.md
# evo ***Python package for the evaluation of odometry and SLAM*** | Linux / macOS / Windows / ROS / ROS2 | | :---: | | [![Build Status](https://dev.azure.com/michl2222/michl2222/_apis/build/status/MichaelGrupp.evo?branchName=master)](https://dev.azure.com/michl2222/michl2222/_build/latest?definitionId=1&branchName=...
11,345
47.076271
580
md
evo
evo-master/_config.yml
theme: jekyll-theme-cayman
26
26
26
yml
evo
evo-master/azure-pipelines.yml
# https://docs.microsoft.com/azure/devops/pipelines/languages/python # https://docs.microsoft.com/en-us/azure/devops/pipelines/languages/docker trigger: - master pr: autoCancel: true # PRs into ... branches: include: - master schedules: - cron: "0 0 * * *" displayName: 'daily build' branches: i...
2,315
21.057143
96
yml