repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
TFLEX | TFLEX-main/assistance/toolbox/nn/CapsE.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
USE_CUDA = True if torch.cuda.is_available() else False
class ConvLayer(nn.Module):
def __init__(self, in_channels=1, out_channels=256, kernel_size=9):
super(ConvLayer, self).__init__()
self.co... | 6,108 | 38.412903 | 119 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/BetaE.py | """
@date: 2021/10/26
@description: null
"""
# !/usr/bin/python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import logging
from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import t... | 37,858 | 52.700709 | 187 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/ConvE.py | import torch
import torch.nn.functional as F
from torch import nn
class CoreConvE(nn.Module):
def __init__(self, embedding_dim, img_h=10, input_dropout=0.2, hidden_dropout1=0.3, hidden_dropout2=0.2):
super(CoreConvE, self).__init__()
self.inp_drop = nn.Dropout(input_dropout)
self.feature_m... | 2,186 | 30.695652 | 109 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/OctonionE.py | import torch
import torch.nn as nn
from torch.nn import functional as F
def octonion_mul(O_1, O_2):
x0, x1, x2, x3, x4, x5, x6, x7 = O_1
y0, y1, y2, y3, y4, y5, y6, y7 = O_2
x = x0 * y0 - x1 * y1 - x2 * y2 - x3 * y3 - x4 * y4 - x5 * y5 - x6 * y6 - x7 * y7
e1 = x0 * y1 + x1 * y0 + x2 * y3 - x3 * y2 + x... | 41,793 | 57.947814 | 128 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/TransE.py | import torch
import torch.nn.functional as F
from torch import nn
class CoreTransE(nn.Module):
def __init__(self):
super(CoreTransE, self).__init__()
def forward(self, h, r):
x = h + r
x = F.relu(x)
return x
class TransE(nn.Module):
def __init__(self, num_entities, num_r... | 2,350 | 29.141026 | 87 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/GPT.py | """
@date: 2021/12/4
@description: null
"""
import logging
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
logger = logging.getLogger(__name__)
class GPTConfig:
""" base GPT config, params common to all GPT versions """
embd_pdrop = 0.1
resid_pdrop = 0.1
attn_pdr... | 9,565 | 39.706383 | 127 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/Highway.py | import torch
import torch.nn as nn
class Highway(nn.Module):
def __init__(self, x_hidden):
super(Highway, self).__init__()
self.lin = nn.Linear(x_hidden, x_hidden)
def forward(self, x1, x2):
gate = torch.sigmoid(self.lin(x1))
x = torch.mul(gate, x2) + torch.mul(1 - gate, x1)
... | 336 | 23.071429 | 57 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/ComplexEmbedding.py | from typing import List, Tuple
import torch
from torch import nn
ComplexNum = Tuple[torch.Tensor, torch.Tensor]
class ComplexEmbedding(nn.Module):
def __init__(self, num_entities, embedding_dim, num_channels=2):
super(ComplexEmbedding, self).__init__()
self.num_entities = num_entities
se... | 5,445 | 25.696078 | 113 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/TuckerMobiusE.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from toolbox.nn.ComplexEmbedding import ComplexEmbedding, ComplexDropout, ComplexBatchNorm1d, ComplexMult, ComplexAdd, ComplexDiv, ComplexAlign
from toolbox.nn.MobiusEmbedding import MobiusEmbedding, MobiusDropout, MobiusBatchNorm1d
from toolbox.nn.Reg... | 5,633 | 36.065789 | 143 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/TuckERTTR.py | import numpy as np
import torch
import torch.nn as nn
class TuckERTTR(nn.Module):
def __init__(self, d, de, dr, dt, ranks, device='cpu', input_dropout=0., hidden_dropout1=0., hidden_dropout2=0., **kwargs):
super(TuckERTTR, self).__init__()
self.device = device
# Embeddings dimensionality... | 2,860 | 31.511364 | 158 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/MobiusE.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from toolbox.nn.ComplexEmbedding import ComplexEmbedding, ComplexDropout, ComplexScoringAll, ComplexBatchNorm1d, ComplexMult, ComplexAdd, ComplexDiv, ComplexAlign
from toolbox.nn.MobiusEmbedding import MobiusEmbedding, MobiusDropout, MobiusBatchNorm1d
... | 5,494 | 36.128378 | 162 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/ComplexTuckER.py | import numpy as np
import torch
from torch import nn
from toolbox.nn.ComplexEmbedding import ComplexEmbedding, ComplexDropout, ComplexScoringAll, ComplexBatchNorm1d
class CoreTuckER(nn.Module):
def __init__(self, entity_dim, relation_dim, hidden_dropout1=0.4):
super(CoreTuckER, self).__init__()
s... | 4,703 | 35.465116 | 138 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/ComplexMultiheadAttention.py | """
@date: 2021/10/27
@description: null
"""
import math
import os
import random
import numpy as np
import torch
import torch.nn.functional as F
import torch.utils
from sklearn.metrics import confusion_matrix
from torch import nn
from torch.nn import Parameter
class MultiheadAttention(nn.Module):
"""Multi-headed... | 54,870 | 37.723359 | 157 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/ParamE.py | import torch
import torch.nn.functional as F
from torch import nn
class CoreParamEGate(nn.Module):
def __init__(self, entity_dim, hidden_dim=100):
super(CoreParamEGate, self).__init__()
self.entity_dim = entity_dim
self.hidden_dim = hidden_dim
self.linear = nn.Linear(hidden_dim, en... | 4,458 | 37.111111 | 120 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/Regularizer.py | from typing import Tuple, Sequence
import torch
from torch import nn
class Fro(nn.Module):
def __init__(self, weight: float):
super(Fro, self).__init__()
self.weight = weight
def forward(self, factors: Sequence[torch.Tensor]):
norm = 0
for factor in factors:
for f... | 3,676 | 27.503876 | 104 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/LongitudE.py | """
@date: 2021/12/7
@description: 经度嵌入
这是中心参数和范围参数都多头的版本
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import logging
from typing import Dict, List
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as... | 30,370 | 45.79661 | 180 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/GAT.py | import torch
import torch.nn.functional as F
from torch import nn
from torch_geometric.utils import softmax
from torch_sparse import spmm
class GAT(nn.Module):
"""
第一种GAT,可以不用关系,只用实体对
"""
def __init__(self, hidden):
super(GAT, self).__init__()
self.a_i = nn.Linear(hidden, 1, bias=Fals... | 1,878 | 29.306452 | 71 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/ComplexAttention.py | """
@date: 2021/10/27
@description: null
"""
import torch
from torch import nn
class ComplexMatrixMult(nn.Module):
"""
x = x_a + x_b i
W = W_a + W_b i
W * x = (W_a * x_a - W_b * x_b) + (W_a * x_b + W_b * x_a) i
x in C^d, x_a in (B, d), x_b in (B, d)
W in C^(d, d_out), W_a in (d, d_out), W_b ... | 5,799 | 32.142857 | 122 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/EchoE.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.utils import softmax
from toolbox.nn.Highway import Highway
class GraphEncoder(nn.Module):
def __init__(self, entity_dim, relation_dim):
super(GraphEncoder, self).__init__()
self.a_i = nn.Linear(entity_dim, 1,... | 7,495 | 34.866029 | 110 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/HAKE.py | import os
import logging
import numpy as np
from abc import ABC, abstractmethod
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
class KGEModel(nn.Module, ABC):
"""
Must define
`self.entity_embedding`
`self.relation_embedding`
in th... | 12,561 | 33.991643 | 106 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/TuckERT.py | import torch
import torch.nn as nn
class TuckERT(nn.Module):
def __init__(self, d, de, dr, dt, device="cpu", input_dropout=0., hidden_dropout1=0., hidden_dropout2=0., **kwargs):
super(TuckERT, self).__init__()
self.device = device
# Embeddings dimensionality
self.de = de
... | 2,011 | 29.029851 | 120 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/TuckERCPD.py | import numpy as np
import torch
import torch.nn as nn
class TuckERCPD(torch.nn.Module):
def __init__(self, d, de, dr, dt, device="cpu", **kwargs):
super(TuckERCPD, self).__init__()
self.device = device
# Embeddings dimensionality
self.de = de
self.dr = dr
self.dt ... | 3,318 | 30.913462 | 144 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/functional/complex.py | import torch
def mobius_mul_with_unit_norm(Q_1, Q_2):
a_h = Q_1 # = {a_h + b_h i + c_h j + d_h k : a_r, b_r, c_r, d_r \in R^k}
a_r, b_r, c_r, d_r = Q_2 # = {a_r + b_r i + c_r j + d_r k : a_r, b_r, c_r, d_r \in R^k}
# Normalize the relation to eliminate the scaling effect
denominator = torch.sqrt(a_... | 789 | 31.916667 | 92 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/functional/graph.py | from functools import reduce
import torch
def edge_match(edge_index, query_index):
# O((n + q)logn) time
# O(n) memory
# edge_index: big underlying graph (3, n)
# query_index: edges to match (3, q)
base = edge_index.max(dim=1)[0] + 1
# we will map edges to long ints, so we need to make sure ... | 8,039 | 49.886076 | 165 | py |
TFLEX | TFLEX-main/assistance/toolbox/nn/functional/operation.py | import torch
def rankOf(vector, values):
"""Returns the indices of the first occurrences of values in a tensor.
Args:
tensor (tensor): ranking tensor, shape [len(tensor)]
values (tensor): values to be ranked, shape [len(values)]
Returns:
tensor: indices of the first occurrences o... | 1,453 | 40.542857 | 118 | py |
TFLEX | TFLEX-main/assistance/toolbox/optim/lr_scheduler.py | """
@date: 2021/11/7
@description: null
"""
import torch
def get_scheduler(optimizer, lr_policy="exp", epoch_count=5, lr_decay_iters=25, niter=100, niter_decay=100, ):
"""Return a learning rate scheduler
Parameters:
optimizer -- 网络优化器
lr_policy -- 学习率scheduler的名称: linear | step | plateau |... | 1,252 | 39.419355 | 125 | py |
TFLEX | TFLEX-main/assistance/toolbox/optim/EMA.py | import torch
class EMA:
"""
移动平均,保存历史的一份参数,在一定训练阶段后,拿历史的参数给目前学习的参数做一次平滑。
初始化
```
ema = EMA(model, 0.999)
ema.register()
```
训练过程中,更新完参数后,同步 update shadow weights
```
def train():
optimizer.step()
ema.update()
```
eval 前,apply shadow weights;eval 之后,恢复... | 3,104 | 25.092437 | 96 | py |
TFLEX | TFLEX-main/assistance/toolbox/optim/__init__.py | import torch.optim as optim
def create_optimizer(opt, model, lr, weight_decay, get_num_layer=None, get_layer_scale=None):
opt_lower = opt.lower()
parameters = model.parameters()
opt_args = dict(lr=lr, weight_decay=weight_decay)
opt_split = opt_lower.split("_")
opt_lower = opt_split[-1]
if op... | 845 | 30.333333 | 93 | py |
TFLEX | TFLEX-main/assistance/toolbox/optim/FGM.py | import torch
from typing import Callable
class FGM(object):
"""
# 对抗训练就是在输入的层次增加扰动,根据扰动产生的样本,来做一次反向传播。
# 初始化
fgm = FGM(model)
for batch_input, batch_label in data:
# 正常训练
loss = model(batch_input, batch_label)
loss.backward() # 反向传播,得到正常的grad
# 对抗训练
fgm.atta... | 1,438 | 33.261905 | 97 | py |
TFLEX | TFLEX-main/assistance/toolbox/evaluate/LinkPredict.py | from collections import defaultdict
from typing import Union, Dict, List
import numpy as np
import pandas as pd
import torch
def link_predict(predictions, truth):
"""
predictions : torch.Tensor, similarity matrix of shape (batch_size, entity_count)
truth: torch.Tensor, vector of length (BatchSize)
""... | 10,490 | 31.887147 | 122 | py |
TFLEX | TFLEX-main/assistance/toolbox/evaluate/EntityAlignment.py |
def entity_alignment(predictions):
"""
predictions : torch.Tensor, similarity matrix of shape (entity_count, entity_count)
"""
pass | 148 | 23.833333 | 87 | py |
TFLEX | TFLEX-main/assistance/toolbox/evaluate/Evaluate.py | # 指标计算
#
#
# outline
# 1. utils function
# 2. exported function
import time
import timeit
from typing import Dict, Union
import numpy as np
import torch
from scipy.spatial.distance import cdist
from sklearn import preprocessing
# region 1. utils function
from toolbox.utils.Progbar import Progbar
def div_list(ls, n... | 19,546 | 32.994783 | 118 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/SpeedUp.py | import torch
def speed_up():
torch.cuda.emptyCache()
def how_to_speed_up():
info = """
1. for your dataloader: pin_memory == True, num_worker >= 8
2. choose faster optimizer: AdamW
"""
print(info)
| 224 | 16.307692 | 63 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/RandomSeeds.py | """
@date: 2022/2/19
@description: 随机种子
"""
import random
import numpy as np
import torch
def set_seeds(seed=1234):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
if seed == 0:
torch.backends.cu... | 396 | 18.85 | 53 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/ModelParamStore.py | """
@date: 2022/2/19
@description: 模型保存和恢复
"""
import os
from typing import Tuple, List, Union, Optional
import torch
from pathlib import Path
from torch import nn
from torch.optim import optimizer
from toolbox.exp.OutputSchema import OutputPathSchema
_MODEL_STATE_DICT = "model_state_dict"
_OPTIMIZER_STATE_DICT = "o... | 6,117 | 34.988235 | 133 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/Framework.py | import importlib
import logging
import os
import sys
from functools import wraps
import numpy as np
from packaging import version
if sys.version_info < (3, 8):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
... | 4,979 | 26.513812 | 117 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/Progbar.py | """
@date: 2022/2/19
@description: 进度条
"""
import sys
import time
from typing import Dict, Any, Union, Tuple, List
import datetime
import numpy as np
class Progbar(object):
"""Progress bar class inspired by keras 进度条
Examples:
>>> from toolbox.utils.Progbar import Progbar
>>> progba... | 5,008 | 32.844595 | 107 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/VisualizeStore.py | """
@author: lxy
@email: linxy59@mail2.sysu.edu.cn
@date: 2022/2/19
@description: 可视化
run the command below to open tensorbard
```shell
tensorboard --logdir .
```
"""
def get_writer(log_dir: str, comments=""):
from torch.utils.tensorboard import SummaryWriter
return SummaryWriter(log_dir, comments)
def add_... | 2,151 | 31.119403 | 85 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/KGArgs.py | import json
import os
from enum import Enum
from typing import Optional, Dict, Any, List
import torch
from dataclasses import dataclass, field, asdict
from toolbox.utils.Framework import is_torch_available, cached_property, torch_required
class ExplicitEnum(Enum):
"""
Enum with more explicit error message f... | 36,075 | 50.610873 | 149 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/Embed.py | from typing import List
import torch
def get_vec(entities_embedding, id_list: List[int], embedding_dim=200, device="cuda"):
tensor = torch.LongTensor(id_list).view(-1, 1).to(device)
return entities_embedding(tensor).view(-1, embedding_dim).cpu().detach().numpy()
def get_vec2(entities_embedding, id_list: Li... | 1,029 | 32.225806 | 88 | py |
TFLEX | TFLEX-main/assistance/toolbox/utils/MetricLogStore.py | """
@date: 2022/2/19
@description: null
"""
import argparse
import json
import logging
import os
import re
import time
from configparser import ConfigParser
from copy import deepcopy
from typing import Union
import numpy as np
class MetricLogStoreSchema:
"""实验指标日志
需要以特定的格式存储和读取
"""
def __init__(self... | 28,473 | 32.97852 | 115 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/LinkPredictDataset.py | from typing import List, Tuple, Dict, Set
import torch
from torch.utils.data import Dataset
class LinkPredictDataset(Dataset):
def __init__(self, test_triples_ids: List[Tuple[int, int, int]], hr_t: Dict[Tuple[int, int], Set[int]], max_relation_id: int, entity_count: int):
"""
test_triples_ids: wi... | 3,705 | 33.635514 | 149 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/FixWindowNegSamplingDataset.py | import random
from typing import List, Tuple, Set, Dict
import numpy as np
import torch
from torch.utils.data import Dataset
from toolbox.data.functional import build_map_hr_t
def get_neg_sampling_batch(entity_ids: Set[int],
hr_t: Dict[Tuple[int, int], Set[int]],
... | 2,140 | 38.648148 | 119 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/ComplementaryDataset.py | from typing import List, Tuple, Set
import torch
from torch.utils.data import Dataset
class ComplementaryTrainDataset(Dataset):
"""
生成 补集划分 的数据集
head0: Bx(T-1)
rel0: Bx(T-1)
tail0: Bx(T-1)
head: Bx1
rel: Bx1
tail: Bx1
"""
def __init__(self, triples_ids: List[Tuple[int, int, i... | 1,652 | 29.054545 | 96 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/dataloader.py | """
@author: lxy
@email: linxy59@mail2.sysu.edu.cn
@date: 2021/10/26
@description: null
"""
from typing import List, Tuple
import numpy as np
import torch
from torch.utils.data import Dataset
class AlignDataset(Dataset):
def __init__(self,
seeds: List[Tuple[int, int]],
kg1_entit... | 11,668 | 33.832836 | 109 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/functional.py | import pickle
from collections import defaultdict
from pathlib import Path
from typing import Tuple, List, Union, Set, Dict
import torch
def cache_data(data, cache_path: Union[str, Path]):
with open(str(cache_path), 'wb') as f:
pickle.dump(data, f)
def read_cache(cache_path: Union[str, Path]):
with... | 5,931 | 33.091954 | 155 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/PyG_extension.py | from typing import List, Tuple
import torch
from torch_geometric.data import Data
from toolbox.data.DataSchema import RelationalTripletData
from toolbox.data.functional import with_inverse_relations
def triple_to_Data(triple: List[Tuple[int, int, int]]) -> Data:
triple_tensor = torch.tensor(triple, dtype=torch.... | 829 | 40.5 | 116 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/TripleDataset.py | """
@author: lxy
@email: linxy59@mail2.sysu.edu.cn
@date: 2021/10/30
@description: null
"""
from typing import List, Tuple
import torch
from torch.utils.data import Dataset
class TripleDataset(Dataset):
def __init__(self, triples_ids: List[Tuple[int, int, int]]):
self.triples_ids = triples_ids
def _... | 569 | 20.923077 | 64 | py |
TFLEX | TFLEX-main/assistance/toolbox/data/ScoringAllDataset.py | from typing import List, Tuple, Dict, Set
import torch
from torch.utils.data import Dataset
from ComplexTemporalQueryData import build_map_sro2t_and_srt2o, build_map_sro_t, build_map_srt_o
from toolbox.data.functional import build_map_hr_t
class ScoringAllDataset(Dataset):
def __init__(self, train_triples_ids: ... | 3,251 | 32.525773 | 149 | py |
TFLEX | TFLEX-main/assistance/toolbox/exp/DistributeSchema.py | import os
from typing import Optional, List
import torch
from torch import distributed as dist
class DistributeSchema:
def __init__(self, local_rank=-1, gpus: Optional[List[int]] = None):
self.local_rank = local_rank
self.gpus = gpus
self.world_size = self.get_world_size()
if sel... | 1,879 | 28.84127 | 93 | py |
TFLEX | TFLEX-main/assistance/toolbox/exp/classic/train_TransE.py | import click
import numpy as np
import torch
from torch.utils.data import DataLoader
from toolbox.data.DataSchema import RelationalTripletData, RelationalTripletDatasetCachePath
from toolbox.data.DatasetSchema import FreebaseFB15k_237
from toolbox.data.LinkPredictDataset import LinkPredictDataset
from toolbox.data.Sco... | 8,267 | 52.341935 | 195 | py |
TFLEX | TFLEX-main/assistance/toolbox/exp/classic/train_CartPole.py | import gym
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# Hyper Parameters
BATCH_SIZE = 32
LR = 0.01 # learning rate
EPSILON = 0.9 # greedy policy
GAMMA = 0.9 # reward discount
TARGET_REPLACE_ITER = 100 # target update frequency
MEMORY_CAPACITY = 2000
env = gym.make('CartPo... | 4,123 | 33.082645 | 122 | py |
TFLEX | TFLEX-main/assistance/toolbox/exp/classic/train_ConvE.py | import click
import numpy as np
import torch
from torch.utils.data import DataLoader
from toolbox.data.DataSchema import RelationalTripletData, RelationalTripletDatasetCachePath
from toolbox.data.DatasetSchema import FreebaseFB15k_237
from toolbox.data.LinkPredictDataset import LinkPredictDataset
from toolbox.data.Sco... | 8,264 | 52.322581 | 195 | py |
TFLEX | TFLEX-main/tests/test_model.py | import torch
from train_TCQE_TFLEX import TFLEX
max_id = 20
entity_count = max_id
relation_count = max_id
timestamp_count = max_id
hidden_dim = 10
gamma = 10
center_reg = 0.02
test_batch_size = 1
input_dropout = 0.1
model = TFLEX(
nentity=entity_count,
nrelation=relation_count,
ntimestamp=timestamp_count,... | 689 | 22 | 61 | py |
TFLEX | TFLEX-main/temp/gridsearch.py | import time
import numpy as np
import pandas as pd
import torch
from sklearn.model_selection import ParameterGrid
from temp.load_data import Data
from temp.train import train_temporal
from toolbox.nn.TuckERCPD import TuckERCPD
from toolbox.nn.TuckERTTR import TuckERTTR
def grid_search(model, data, param_model_grid,... | 2,784 | 38.225352 | 201 | py |
TFLEX | TFLEX-main/temp/metrics.py | import numpy as np
import torch
def get_ranks(model, torch_data_idxs, targets, batch_size=128, device='cpu'):
"""
Compute ranks
model : torch.nn.Module,
model from which to do the prediction
torch_data_idxs : torch.tensor,
data matrix
targets : array,
List of targets value... | 1,577 | 30.56 | 104 | py |
TFLEX | TFLEX-main/temp/train.py | from collections import defaultdict
import numpy as np
import torch
from temp.metrics import get_ranks, compute_hits, compute_MRR
def get_ert_vocab(data):
"""
Construct a dict of the data containing [E,R,T] as keys and target entities as values
"""
ert_vocab = defaultdict(list)
for quad in data... | 5,959 | 33.252874 | 163 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/losses.py | import torch
import torch.nn
import torch.nn.functional
def loss_weight(n_class):
if n_class == 2:
weights = [1.25423722, 0.83146071]
else:
weights = [0.89716412, 0.5875235, 5.45502627]
weights = torch.FloatTensor(weights)
return weights
class DiceLoss(torch.nn.Module):
def __ini... | 3,263 | 31.969697 | 101 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/network.py |
import torch
import segmentation_models_pytorch as smp
def factory(args):
if not args.checkpoint:
epoch = 0
pretrained = 'imagenet' if args.pretrained else None
attention = 'scse' if 'scse' in args.model_name else None
if 'unet' in args.model_name:
net = smp.Unet(encod... | 1,072 | 37.321429 | 88 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/dataset.py | import os
import torch.utils.data
import numpy as np
from scipy.io import loadmat
import cv2
class HistologyDataset(torch.utils.data.Dataset):
def __init__(self, img_root, mat_root, transform=None, target_transform=None, num_class=2):
self.img_root = img_root
self.mat_root = mat_root
self.... | 5,229 | 35.319444 | 117 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/eval.py | """ evaluate metrics on the dataset"""
import argparse
import torch
import sys
import os
import logging
import torch.utils.data
import time
import torch.nn.functional
import albumentations
import albumentations.pytorch
from . import network, transforms, dataset
from .metrics import ConfusionMatrix, dice, jaccard, fsc... | 4,892 | 30.980392 | 110 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/metrics.py | import torch
import torch.nn.functional
import numpy as np
def assert_shape(output, target):
assert output.shape == target.shape, "Shape mismatch: {} and {}".format(
output.shape, target.shape)
def threshold_mask(probs):
labels = torch.argmax(probs, dim=1)
predicted_mask = torch.nn.functional.o... | 5,628 | 28.165803 | 99 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/predict.py | """ predict for given image(s)"""
import cv2
import os
import numpy as np
import torch
import torch.nn.functional
import torch.utils.data
import matplotlib.pyplot as plt
import argparse
import albumentations
import albumentations.pytorch
from . import dataset, network
def cli():
parser = argparse.ArgumentParser... | 8,362 | 36.334821 | 107 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/train.py | """train a network"""
import argparse
import datetime
import logging
import sys
import torch
from . import dataset, transforms, losses, network
from .trainer import Trainer
def cli():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--image-dir', default='data/imgs/',
... | 4,489 | 39.089286 | 110 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/trainer.py | import torch.utils.data
import torch.nn.functional
import torch
import sklearn.model_selection
import time
import logging
import numpy as np
from .metrics import ConfusionMatrix, dice, jaccard, fscore, accuracy
class Trainer(object):
def __init__(self, model, losses, optimizer,
lr_scheduler=None... | 8,295 | 34.91342 | 116 | py |
tube_segmentation | tube_segmentation-main/tube_segmentation/transforms.py | import albumentations
import albumentations.pytorch
class TargetTransform(object):
def __init__(self, model_name):
self.model_name = model_name
def __call__(self, mask):
return [mask]
def augment_transform(long_edge, augmentation=True, pretrained=False):
if pretrained:
mean = (0... | 1,922 | 33.339286 | 106 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig7_FullyDigital_BFgain/multiAoA_BF_RNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'This code generate the results for Proposed active sensing method'
'System Information'
N = 64 # Number of BS's antennas
actual... | 10,615 | 48.840376 | 148 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig7_FullyDigital_BFgain/multiAoA_BF_DNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'This code generate the results for DNN-based design (random sensing vectors, fixed)'
'System Information'
N = 64 # Number of B... | 8,328 | 48.874251 | 148 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig7_FullyDigital_BFgain/multiAoA_BF_DNN_trainable_w.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'This code generate the results for DNN-based design (learned sensing vectors, fixed)'
'System Information'
N = 64 # Number of... | 8,320 | 47.947059 | 148 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig6_FullyDigital_AoA_MultiPath/Coherent/multiAoA_est_RNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
# from func_codedesign_cont import func_codedesign_cont
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'System Information'
N = 64 # Number of ... | 12,665 | 50.279352 | 138 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig6_FullyDigital_AoA_MultiPath/Noncoherent/multiAoA_est_RNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
# from func_codedesign_cont import func_codedesign_cont
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'System Information'
N = 64 # Number of ... | 12,741 | 50.379032 | 138 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig9_RIS/max_rate_nonadaptive_dnn_trainable_w.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
from generate_channel import main_generate_channel
import scipy.io as sio
from keras.layers import BatchNormalization
# from tensorflow.keras.layers import BatchNormalization
from keras.layers import Dense
fro... | 7,621 | 47.547771 | 124 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig9_RIS/max_rate_rnn.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
from generate_channel import main_generate_channel
import scipy.io as sio
# from tensorflow.keras.layers import BatchNormalization
# from tensorflow.keras.layers import Dense
from keras.layers.normalization im... | 9,986 | 48.935 | 137 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig9_RIS/max_rate_nonadaptive_dnn.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
from generate_channel import main_generate_channel
import scipy.io as sio
from keras.layers import BatchNormalization
# from tensorflow.keras.layers import BatchNormalization
'This code generates the results ... | 7,639 | 46.160494 | 124 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig5_Hybrid_AoA_SinglePath/Coherent/AoA_estimation_known_alpha_RNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
from func_codedesign_cont import func_codedesign_cont
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'System Information'
N = 64 #Number of BS... | 10,552 | 49.492823 | 149 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig5_Hybrid_AoA_SinglePath/Noncoherent/AoA_estimation_known_alpha_RNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
from func_codedesign_cont import func_codedesign_cont
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'System Information'
N = 64 #Number of BS... | 10,488 | 49.427885 | 149 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig4_Fig8_FullyDigital_AoA_SinglePath/Fig4/Coherent/AoA_estimation_known_alpha_RNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
from func_codedesign_cont import func_codedesign_cont
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'System Information'
N = 64 #Number of BS... | 10,342 | 48.966184 | 149 | py |
DL-ActiveSensing | DL-ActiveSensing-main/Fig4_Fig8_FullyDigital_AoA_SinglePath/Fig4/Noncoherent/AoA_estimation_known_alpha_RNN.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt
from func_codedesign_cont import func_codedesign_cont
import scipy.io as sio
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense
'System Information'
N = 64 #Number of BS... | 10,307 | 49.038835 | 149 | py |
CGvsPhoto | CGvsPhoto-master/Textures/lbp.py | import numpy as np
from CGvsPhoto import image_loader as il
from multiprocessing import Pool
from functools import partial
from sklearn.svm import SVC, LinearSVC
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import normalize
from sklearn.calibration import CalibratedClassifierCV
from sklearn... | 13,847 | 25.128302 | 115 | py |
Mask-aware-IoU | Mask-aware-IoU-master/setup.py | #!/usr/bin/env python
import os
import subprocess
import time
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
def readme():
with open('README.md', encoding='utf-8') as f:
co... | 10,622 | 33.829508 | 125 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/test.py | import argparse
import os
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from tools.fuse_conv_bn import fuse_module
from mmdet.apis import multi_gpu_test, single_gpu_test... | 5,467 | 35.453333 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/benchmark.py | import argparse
import time
import torch
from mmcv import Config
from mmcv.parallel import MMDataParallel
from mmcv.runner import load_checkpoint
from tools.fuse_conv_bn import fuse_module
from mmdet.core import wrap_fp16_model
from mmdet.datasets import build_dataloader, build_dataset
from mmdet.models import build_... | 2,802 | 28.819149 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/fuse_conv_bn.py | import argparse
import torch
import torch.nn as nn
from mmcv.runner import save_checkpoint
from mmdet.apis import init_detector
def fuse_conv_bn(conv, bn):
""" During inference, the functionary of batch norm layers is turned off
but only the mean and var alone channels are used, which exposes the
chance... | 2,200 | 30.898551 | 77 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/get_flops.py | import argparse
import torch
from mmcv import Config
from mmdet.models import build_detector
try:
from mmcv.cnn import get_model_complexity_info
except ImportError:
raise ImportError('Please upgrade mmcv to >0.6.2')
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
... | 1,732 | 26.507937 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/publish_model.py | import argparse
import subprocess
import torch
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', help='output checkpoint filename')
args = par... | 1,072 | 27.236842 | 77 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/regnet2mmdet.py | import argparse
from collections import OrderedDict
import torch
def convert_stem(model_key, model_weight, state_dict, converted_names):
new_key = model_key.replace('stem.conv', 'conv1')
new_key = new_key.replace('stem.bn', 'bn1')
state_dict[new_key] = model_weight
converted_names.add(model_key)
... | 3,015 | 32.511111 | 77 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/pytorch2onnx.py | import argparse
import io
import mmcv
import onnx
import torch
from mmcv.runner import load_checkpoint
from onnx import optimizer
from torch.onnx import OperatorExportTypes
from mmdet.models import build_detector
from mmdet.ops import RoIAlign, RoIPool
def export_onnx_model(model, inputs, passes):
"""
Trace... | 3,996 | 30.722222 | 76 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/upgrade_model_version.py | import argparse
import re
import tempfile
from collections import OrderedDict
import torch
from mmcv import Config
def is_head(key):
valid_head_list = [
'bbox_head', 'mask_head', 'semantic_head', 'grid_head', 'mask_iou_head'
]
return any(key.startswith(h) for h in valid_head_list)
def parse_co... | 6,215 | 31.041237 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/test_robustness.py | import argparse
import copy
import os
import os.path as osp
import shutil
import tempfile
import mmcv
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from pycocotools.coco import COCO
fro... | 17,153 | 36.372549 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/train.py | import argparse
import copy
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.runner import init_dist
from mmdet import __version__
from mmdet.apis import set_random_seed, train_detector
from mmdet.datasets import build_dataset
from mmdet.models import ... | 5,345 | 33.714286 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tools/detectron2pytorch.py | import argparse
from collections import OrderedDict
import mmcv
import torch
arch_settings = {50: (3, 4, 6, 3), 101: (3, 4, 23, 3)}
def convert_bn(blobs, state_dict, caffe_name, torch_name, converted_names):
# detectron replace bn with affine channel layer
state_dict[torch_name + '.bias'] = torch.from_numpy... | 3,530 | 41.542169 | 78 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/async_benchmark.py | import asyncio
import os
import shutil
import urllib
import mmcv
import torch
from mmdet.apis import (async_inference_detector, inference_detector,
init_detector, show_result)
from mmdet.utils.contextmanagers import concurrent
from mmdet.utils.profiling import profile_time
async def main():
... | 3,124 | 29.048077 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_roi_extractor.py | import pytest
import torch
from mmdet.models.roi_heads.roi_extractors import GenericRoIExtractor
def test_groie():
# test with pre/post
cfg = dict(
roi_layer=dict(type='RoIAlign', out_size=7, sample_num=2),
out_channels=256,
featmap_strides=[4, 8, 16, 32],
pre_cfg=dict(
... | 3,174 | 26.850877 | 74 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_anchor.py | """
CommandLine:
pytest tests/test_anchor.py
xdoctest tests/test_anchor.py zero
"""
import torch
def test_standard_anchor_generator():
from mmdet.core.anchor import build_anchor_generator
anchor_generator_cfg = dict(
type='AnchorGenerator',
scales=[8],
ratios=[0.5, 1.0, 2.0],
... | 16,127 | 42.826087 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_forward.py | """
pytest tests/test_forward.py
"""
import copy
from os.path import dirname, exists, join
import numpy as np
import pytest
import torch
def _get_config_directory():
""" Find the predefined detector config directory """
try:
# Assume we are running in the source mmdetection repo
repo_dpath = ... | 12,049 | 30.380208 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_async.py | """Tests for async interface."""
import asyncio
import os
import sys
import asynctest
import mmcv
import torch
from mmdet.apis import async_inference_detector, init_detector
if sys.version_info >= (3, 7):
from mmdet.utils.contextmanagers import concurrent
class AsyncTestCase(asynctest.TestCase):
use_defau... | 2,560 | 29.855422 | 75 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_config.py | from os.path import dirname, exists, join, relpath
import torch
from mmcv.runner import build_optimizer
from mmdet.core import BitmapMasks, PolygonMasks
def _get_config_directory():
""" Find the predefined detector config directory """
try:
# Assume we are running in the source mmdetection repo
... | 14,223 | 38.62117 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_necks.py | import pytest
import torch
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.models.necks import FPN
def test_fpn():
"""Tests fpn """
s = 64
in_channels = [8, 16, 32, 64]
feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8]
out_channels = 8
# `num_outs` is not equal to len... | 6,570 | 31.529703 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_sampler.py | import torch
from mmdet.core.bbox.assigners import MaxIoUAssigner
from mmdet.core.bbox.samplers import (OHEMSampler, RandomSampler,
ScoreHLRSampler)
def test_random_sampler():
assigner = MaxIoUAssigner(
pos_iou_thr=0.5,
neg_iou_thr=0.5,
ignore_iof_thr... | 9,906 | 28.750751 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/tests/test_heads.py | import mmcv
import torch
from mmdet.core import bbox2roi, build_assigner, build_sampler
from mmdet.models.dense_heads import (AnchorHead, FCOSHead, FSAFHead,
GuidedAnchorHead, YOLACTHead,
YOLACTProtonet, YOLACTSegmHead)
from mmdet.models.roi_h... | 27,057 | 34.32376 | 79 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.