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 |
---|---|---|---|---|---|---|
Squeezeformer | Squeezeformer-main/src/utils/file_util.py | # Copyright 2020 Huy Le Nguyen (@usimarit)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import yaml
import tempfile
import contextlib
from typing import Union, List
import tensorflow as tf
def load_yaml(path):
# Fix yaml numbers https://stackoverflow.com/a/30462009/11037553
loader = yaml.SafeLoader
loader.add_implicit_resolver(
u'tag:yaml.org,2002:float',
re.compile(u'''^(?:
[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
|\\.[0-9_]+(?:[eE][-+][0-9]+)?
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
|[-+]?\\.(?:inf|Inf|INF)
|\\.(?:nan|NaN|NAN))$''', re.X),
list(u'-+0123456789.'))
with open(path, "r", encoding="utf-8") as file:
return yaml.load(file, Loader=loader)
def is_hdf5_filepath(filepath: str) -> bool:
return (filepath.endswith('.h5') or filepath.endswith('.keras') or filepath.endswith('.hdf5'))
def is_cloud_path(path: str) -> bool:
""" Check if the path is on cloud (which requires tf.io.gfile)
Args:
path (str): Path to directory or file
Returns:
bool: True if path is on cloud, False otherwise
"""
return bool(re.match(r"^[a-z]+://", path))
def preprocess_paths(paths: Union[List[str], str], isdir: bool = False) -> Union[List[str], str]:
""" Expand the path to the root "/" and makedirs
Args:
paths (Union[List, str]): A path or list of paths
Returns:
Union[List, str]: A processed path or list of paths, return None if it's not path
"""
if isinstance(paths, list):
paths = [path if is_cloud_path(path) else os.path.abspath(os.path.expanduser(path)) for path in paths]
for path in paths:
dirpath = path if isdir else os.path.dirname(path)
if not tf.io.gfile.exists(dirpath): tf.io.gfile.makedirs(dirpath)
return paths
if isinstance(paths, str):
paths = paths if is_cloud_path(paths) else os.path.abspath(os.path.expanduser(paths))
dirpath = paths if isdir else os.path.dirname(paths)
if not tf.io.gfile.exists(dirpath): tf.io.gfile.makedirs(dirpath)
return paths
return None
@contextlib.contextmanager
def save_file(filepath: str):
if is_cloud_path(filepath) and is_hdf5_filepath(filepath):
_, ext = os.path.splitext(filepath)
with tempfile.NamedTemporaryFile(suffix=ext) as tmp:
yield tmp.name
tf.io.gfile.copy(tmp.name, filepath, overwrite=True)
else:
yield filepath
@contextlib.contextmanager
def read_file(filepath: str):
if is_cloud_path(filepath) and is_hdf5_filepath(filepath):
_, ext = os.path.splitext(filepath)
with tempfile.NamedTemporaryFile(suffix=ext) as tmp:
tf.io.gfile.copy(filepath, tmp.name, overwrite=True)
yield tmp.name
else:
yield filepath
| 3,440 | 33.41 | 110 | py |
Squeezeformer | Squeezeformer-main/src/utils/layer_util.py |
# Copyright 2020 Huy Le Nguyen (@usimarit)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
def get_rnn(rnn_type: str):
assert rnn_type in ["lstm", "gru", "rnn"]
if rnn_type == "lstm": return tf.keras.layers.LSTM
if rnn_type == "gru": return tf.keras.layers.GRU
return tf.keras.layers.SimpleRNN
def get_conv(conv_type):
assert conv_type in ["conv1d", "conv2d"]
if conv_type == "conv1d": return tf.keras.layers.Conv1D
return tf.keras.layers.Conv2D
| 1,002 | 32.433333 | 74 | py |
Squeezeformer | Squeezeformer-main/src/utils/training_utils.py | import tensorflow as tf
from tensorflow.python.keras import backend
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import ops
from tensorflow.python.eager import context
from tensorflow.python.util import nest
from tensorflow.python.ops import variables
from tensorflow.python.ops import summary_ops_v2
from tensorflow.python.ops import array_ops
from tensorflow.python.distribute import collective_all_reduce_strategy
from tensorflow.python.distribute import values as ds_values
def _minimum_control_deps(outputs):
"""Returns the minimum control dependencies to ensure step succeeded."""
if context.executing_eagerly():
return [] # Control dependencies not needed.
outputs = nest.flatten(outputs, expand_composites=True)
for out in outputs:
# Variables can't be control dependencies.
if not isinstance(out, variables.Variable):
return [out] # Return first Tensor or Op from outputs.
return [] # No viable Tensor or Op to use for control deps.
def reduce_per_replica(values, strategy):
"""Reduce PerReplica objects.
Args:
values: Structure of `PerReplica` objects or `Tensor`s. `Tensor`s are
returned as-is.
strategy: `tf.distribute.Strategy` object.
reduction: One of 'first', 'concat'.
Returns:
Structure of `Tensor`s.
"""
def _reduce(v):
"""Reduce a single `PerReplica` object."""
if _collective_all_reduce_multi_worker(strategy):
return _multi_worker_concat(v, strategy)
if not isinstance(v, ds_values.PerReplica):
return v
if _is_tpu_multi_host(strategy):
return _tpu_multi_host_concat(v, strategy)
else:
return concat(strategy.unwrap(v))
return nest.map_structure(_reduce, values)
def concat(tensors, axis=0):
if len(tensors[0].shape) == 0:
return tf.math.add_n(tensors)
"""Concats `tensor`s along `axis`."""
if isinstance(tensors[0], sparse_tensor.SparseTensor):
return sparse_ops.sparse_concat_v2(axis=axis, sp_inputs=tensors)
return array_ops.concat(tensors, axis=axis)
def _collective_all_reduce_multi_worker(strategy):
return (isinstance(strategy,
collective_all_reduce_strategy.CollectiveAllReduceStrategy)
) and strategy.extended._in_multi_worker_mode() # pylint: disable=protected-access
def _is_scalar(x):
return isinstance(x, (ops.Tensor, variables.Variable)) and x.shape.rank == 0
def write_scalar_summaries(logs, step):
for name, value in logs.items():
if _is_scalar(value):
summary_ops_v2.scalar('batch_' + name, value, step=step)
def _is_tpu_multi_host(strategy):
return (backend.is_tpu_strategy(strategy) and
strategy.extended.num_hosts > 1)
def _tpu_multi_host_concat(v, strategy):
"""Correctly order TPU PerReplica objects."""
replicas = strategy.unwrap(v)
# When distributed datasets are created from Tensors / NumPy,
# TPUStrategy.experimental_distribute_dataset shards data in
# (Replica, Host) order, and TPUStrategy.unwrap returns it in
# (Host, Replica) order.
# TODO(b/150317897): Figure out long-term plan here.
num_replicas_per_host = strategy.extended.num_replicas_per_host
ordered_replicas = []
for replica_id in range(num_replicas_per_host):
ordered_replicas += replicas[replica_id::num_replicas_per_host]
return concat(ordered_replicas)
| 3,574 | 37.44086 | 97 | py |
Squeezeformer | Squeezeformer-main/src/utils/logging_util.py | import wandb
import tensorflow as tf
import numpy as np
from numpy import linalg as la
from . import env_util
logger = env_util.setup_environment()
class StepLossMetric(tf.keras.metrics.Metric):
def __init__(self, name='step_loss', **kwargs):
super(StepLossMetric, self).__init__(name=name, **kwargs)
self.loss = tf.zeros(())
def update_state(self, loss):
self.loss = loss
def result(self):
return self.loss
def reset_states(self):
self.loss = tf.zeros(())
class LoggingCallback(tf.keras.callbacks.Callback):
def __init__(
self,
optimizer,
model,
):
super(LoggingCallback, self).__init__()
self.optimizer = optimizer
self.model = model
def on_epoch_end(self, epoch, logs=None):
logger.info("saving checkpoint")
iterations = self.optimizer.iterations
lr = self.optimizer.learning_rate(iterations)
logger.info(f"[LR Logger] Epoch: {epoch}, lr: {lr}")
wandb.log({"epoch": epoch, "lr": lr, "iterations": iterations.numpy()})
| 1,090 | 24.97619 | 79 | py |
Squeezeformer | Squeezeformer-main/src/losses/ctc_loss.py | # Copyright 2020 Huy Le Nguyen (@usimarit)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
class CtcLoss(tf.keras.losses.Loss):
def __init__(self, blank=0, name=None):
super(CtcLoss, self).__init__(reduction=tf.keras.losses.Reduction.NONE, name=name)
self.blank = blank
def call(self, y_true, y_pred):
loss = ctc_loss(
y_pred=y_pred["logits"],
input_length=y_pred["logits_length"],
y_true=y_true["labels"],
label_length=y_true["labels_length"],
blank=self.blank,
name=self.name
)
return tf.nn.compute_average_loss(loss)
@tf.function
def ctc_loss(y_true, y_pred, input_length, label_length, blank, name=None):
return tf.nn.ctc_loss(
labels=tf.cast(y_true, tf.int32),
logit_length=tf.cast(input_length, tf.int32),
logits=tf.cast(y_pred, tf.float32),
label_length=tf.cast(label_length, tf.int32),
logits_time_major=False,
blank_index=blank,
name=name
)
| 1,560 | 34.477273 | 90 | py |
NeuralKG | NeuralKG-main/main.py | # -*- coding: utf-8 -*-
# from torch._C import T
# from train import Trainer
import pytorch_lightning as pl
from pytorch_lightning import seed_everything
from IPython import embed
import wandb
from neuralkg.utils import setup_parser
from neuralkg.utils.tools import *
from neuralkg.data.Sampler import *
from neuralkg.data.Grounding import GroundAllRules
def main():
parser = setup_parser() #设置参数
args = parser.parse_args()
if args.load_config:
args = load_config(args, args.config_path)
seed_everything(args.seed)
"""set up sampler to datapreprocess""" #设置数据处理的采样过程
train_sampler_class = import_class(f"neuralkg.data.{args.train_sampler_class}")
train_sampler = train_sampler_class(args) # 这个sampler是可选择的
#print(train_sampler)
test_sampler_class = import_class(f"neuralkg.data.{args.test_sampler_class}")
test_sampler = test_sampler_class(train_sampler) # test_sampler是一定要的
"""set up datamodule""" #设置数据模块
data_class = import_class(f"neuralkg.data.{args.data_class}") #定义数据类 DataClass
kgdata = data_class(args, train_sampler, test_sampler)
"""set up model"""
model_class = import_class(f"neuralkg.model.{args.model_name}")
if args.model_name == "RugE":
ground = GroundAllRules(args)
ground.PropositionalizeRule()
if args.model_name == "ComplEx_NNE_AER":
model = model_class(args, train_sampler.rel2id)
elif args.model_name == "IterE":
print(f"data.{args.train_sampler_class}")
model = model_class(args, train_sampler, test_sampler)
else:
model = model_class(args)
if args.model_name == 'SEGNN':
src_list = train_sampler.get_train_1.src_list
dst_list = train_sampler.get_train_1.dst_list
rel_list = train_sampler.get_train_1.rel_list
"""set up lit_model"""
litmodel_class = import_class(f"neuralkg.lit_model.{args.litmodel_name}")
if args.model_name =='SEGNN':
lit_model = litmodel_class(model, args, src_list, dst_list, rel_list)
else:
lit_model = litmodel_class(model, args)
"""set up logger"""
logger = pl.loggers.TensorBoardLogger("training/logs")
if args.use_wandb:
log_name = "_".join([args.model_name, args.dataset_name, str(args.lr)])
logger = pl.loggers.WandbLogger(name=log_name, project="NeuralKG")
logger.log_hyperparams(vars(args))
"""early stopping"""
early_callback = pl.callbacks.EarlyStopping(
monitor="Eval|mrr",
mode="max",
patience=args.early_stop_patience,
# verbose=True,
check_on_train_epoch_end=False,
)
"""set up model save method"""
# 目前是保存在验证集上mrr结果最好的模型
# 模型保存的路径
dirpath = "/".join(["output", args.eval_task, args.dataset_name, args.model_name])
model_checkpoint = pl.callbacks.ModelCheckpoint(
monitor="Eval|mrr",
mode="max",
filename="{epoch}-{Eval|mrr:.3f}",
dirpath=dirpath,
save_weights_only=True,
save_top_k=1,
)
callbacks = [early_callback, model_checkpoint]
# initialize trainer
if args.model_name == "IterE":
trainer = pl.Trainer.from_argparse_args(
args,
callbacks=callbacks,
logger=logger,
default_root_dir="training/logs",
gpus="0,",
check_val_every_n_epoch=args.check_per_epoch,
reload_dataloaders_every_n_epochs=1 # IterE
)
else:
trainer = pl.Trainer.from_argparse_args(
args,
callbacks=callbacks,
logger=logger,
default_root_dir="training/logs",
gpus="0,",
check_val_every_n_epoch=args.check_per_epoch,
)
'''保存参数到config'''
if args.save_config:
save_config(args)
if args.use_wandb:
logger.watch(lit_model)
if not args.test_only:
# train&valid
trainer.fit(lit_model, datamodule=kgdata)
# 加载本次实验中dev上表现最好的模型,进行test
path = model_checkpoint.best_model_path
else:
path = args.checkpoint_dir
lit_model.load_state_dict(torch.load(path)["state_dict"])
lit_model.eval()
trainer.test(lit_model, datamodule=kgdata)
if __name__ == "__main__":
main()
| 4,261 | 33.934426 | 86 | py |
NeuralKG | NeuralKG-main/setup.py | #!/usr/bin/env python
# coding: utf-8
import setuptools
import os
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='neuralkg',
version='1.0.21',
author='ZJUKG',
author_email='[email protected]',
url='https://github.com/zjukg/NeuralKG',
description='An Open Source Library for Diverse Representation Learning of Knowledge Graphs',
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
long_description=long_description,
long_description_content_type="text/markdown",
install_requires=[
'pytorch_lightning==1.5.10',
'PyYAML>=6.0',
'wandb>=0.12.7',
'IPython>=5.0.0'
],
python_requires=">=3.6"
)
| 907 | 24.942857 | 97 | py |
NeuralKG | NeuralKG-main/demo.py | # -*- coding: utf-8 -*-
# from torch._C import T
# from train import Trainer
import pytorch_lightning as pl
from pytorch_lightning import seed_everything
from IPython import embed
import wandb
from neuralkg.utils import setup_parser
from neuralkg.utils.tools import *
from neuralkg.data.Sampler import *
from neuralkg.data.Grounding import GroundAllRules
def main(arg_path):
print('This demo is powered by \033[1;32mNeuralKG \033[0m')
args = setup_parser() #设置参数
args = load_config(args, arg_path)
seed_everything(args.seed)
"""set up sampler to datapreprocess""" #设置数据处理的采样过程
train_sampler_class = import_class(f"neuralkg.data.{args.train_sampler_class}")
train_sampler = train_sampler_class(args) # 这个sampler是可选择的
#print(train_sampler)
test_sampler_class = import_class(f"neuralkg.data.{args.test_sampler_class}")
test_sampler = test_sampler_class(train_sampler) # test_sampler是一定要的
"""set up datamodule""" #设置数据模块
data_class = import_class(f"neuralkg.data.{args.data_class}") #定义数据类 DataClass
kgdata = data_class(args, train_sampler, test_sampler)
"""set up model"""
model_class = import_class(f"neuralkg.model.{args.model_name}")
if args.model_name == "RugE":
ground = GroundAllRules(args)
ground.PropositionalizeRule()
if args.model_name == "ComplEx_NNE_AER":
model = model_class(args, train_sampler.rel2id)
elif args.model_name == "IterE":
print(f"data.{args.train_sampler_class}")
model = model_class(args, train_sampler, test_sampler)
else:
model = model_class(args)
"""set up lit_model"""
litmodel_class = import_class(f"neuralkg.lit_model.{args.litmodel_name}")
lit_model = litmodel_class(model, args)
"""set up logger"""
logger = pl.loggers.TensorBoardLogger("training/logs")
if args.use_wandb:
log_name = "_".join([args.model_name, args.dataset_name, str(args.lr)])
logger = pl.loggers.WandbLogger(name=log_name, project="NeuralKG")
logger.log_hyperparams(vars(args))
"""early stopping"""
early_callback = pl.callbacks.EarlyStopping(
monitor="Eval|mrr",
mode="max",
patience=args.early_stop_patience,
# verbose=True,
check_on_train_epoch_end=False,
)
"""set up model save method"""
# 目前是保存在验证集上mrr结果最好的模型
# 模型保存的路径
dirpath = "/".join(["output", args.eval_task, args.dataset_name, args.model_name])
model_checkpoint = pl.callbacks.ModelCheckpoint(
monitor="Eval|mrr",
mode="max",
filename="{epoch}-{Eval|mrr:.3f}",
dirpath=dirpath,
save_weights_only=True,
save_top_k=1,
)
callbacks = [early_callback, model_checkpoint]
# initialize trainer
if args.model_name == "IterE":
trainer = pl.Trainer.from_argparse_args(
args,
callbacks=callbacks,
logger=logger,
default_root_dir="training/logs",
gpus="0,",
check_val_every_n_epoch=args.check_per_epoch,
reload_dataloaders_every_n_epochs=1 # IterE
)
else:
trainer = pl.Trainer.from_argparse_args(
args,
callbacks=callbacks,
logger=logger,
default_root_dir="training/logs",
gpus="0,",
check_val_every_n_epoch=args.check_per_epoch,
)
'''保存参数到config'''
if args.save_config:
save_config(args)
if not args.test_only:
# train&valid
trainer.fit(lit_model, datamodule=kgdata)
# 加载本次实验中dev上表现最好的模型,进行test
path = model_checkpoint.best_model_path
else:
# path = args.checkpoint_dir
path = "./output/link_prediction/FB15K237/TransE/epoch=24-Eval|mrr=0.300.ckpt"
lit_model.load_state_dict(torch.load(path)["state_dict"])
lit_model.eval()
score = lit_model.model(torch.tensor(train_sampler.test_triples), mode='tail-batch')
value, index = score.topk(10, dim=1)
index = index.squeeze(0).tolist()
top10_ent = [train_sampler.id2ent[i] for i in index]
rank = index.index(train_sampler.ent2id['杭州市']) + 1
print('\033[1;32mInteresting display! \033[0m')
print('Use the trained KGE to predict entity')
print("\033[1;32mQuery: \033[0m (浙江大学, 位于市, ?)")
print(f"\033[1;32mTop 10 Prediction:\033[0m{top10_ent}")
print(f"\033[1;32mGroud Truth: \033[0m杭州市 \033[1;32mRank: \033[0m{rank}")
print('This demo is powered by \033[1;32mNeuralKG \033[0m')
if __name__ == "__main__":
main(arg_path = 'config/TransE_demo_kg.yaml')
| 4,592 | 36.647541 | 88 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/RugELitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from neuralkg import loss
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
from neuralkg.data import RuleDataLoader
from tqdm import tqdm
import pdb
class RugELitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
self.args = args
self.temp_list = []
self.rule_dataloader = RuleDataLoader(self.args)
tq = tqdm(self.rule_dataloader, desc='{}'.format('rule'), ncols=0)
print('start first load')
for new_data in tq:
self.temp_list.append(new_data)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
pos_sample = batch["positive_sample"]
neg_sample = batch["negative_sample"]
mode = batch["mode"]
pos_score = self.model(pos_sample)
neg_score = self.model(pos_sample, neg_sample, mode)
rule, confidence, triple_num = self.temp_list[0][0], self.temp_list[0][1], self.temp_list[0][2]
loss = self.loss(pos_score, neg_score, rule, confidence, triple_num, len(pos_sample))
self.temp_list.remove(self.temp_list[0])
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def training_epoch_end(self, training_step_outputs):
self.temp_list = []
print('start reload')
tq = tqdm(self.rule_dataloader, desc='{}'.format('rule'), ncols=0)
for new_data in tq:
self.temp_list.append(new_data)
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
# milestones = int(self.args.max_epochs / 2)
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr)
# StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[milestones], gamma=0.1)
optim_dict = {'optimizer': optimizer}
return optim_dict
| 3,391 | 35.869565 | 103 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/XTransELitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class XTransELitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
triples = batch["positive_sample"]
neg = batch["negative_sample"]
neighbor = batch["neighbor"]
mask = batch['mask']
mode = batch['mode']
pos_score = self.model(triples, neighbor, mask)
neg_score = self.model(triples, neighbor, mask, neg, mode=mode)
loss = self.loss(pos_score, neg_score)
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
milestones = int(self.args.max_epochs / 2)
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr)
StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[milestones], gamma=0.1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 2,658 | 35.930556 | 100 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/SEGNNLitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
import dgl
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class SEGNNLitModel(BaseLitModel):
def __init__(self, model, args, src_list, dst_list, rel_list):
super().__init__(model, args)
self.src_list = src_list
self.dst_list = dst_list
self.rel_list = rel_list
self.kg = self.get_kg(src_list, dst_list, rel_list)
def forward(self, x):
return self.model(x)
def training_step(self, batch):
optimizer = self.optimizers()
#optimizer = optimizer.optimizer
optimizer.zero_grad()
(head, rel, _), label, rm_edges= batch
kg = self.get_kg(self.src_list, self.dst_list, self.rel_list)
kg = kg.to(torch.device("cuda:0"))
if self.args.rm_rate > 0:
kg.remove_edges(rm_edges)
score = self.model(head, rel, kg)
loss = self.loss(score, label)
self.manual_backward(loss)
optimizer.step()
sch = self.lr_schedulers()
sch.step()
return loss
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict_SEGNN(batch, self.kg, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
#results['mr'] = results.get('mr', 0.) + ranks.sum().item()
results['mrr'] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks<=k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict_SEGNN(batch, self.kg, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
#results['mr'] = results.get('MR', 0.) + ranks.sum().item()
results['mrr'] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def get_kg(self, src_list, dst_list, rel_list):
n_ent = self.args.num_ent
kg = dgl.graph((src_list, dst_list), num_nodes=n_ent)
kg.edata['rel_id'] = rel_list
return kg
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
def lr_lambda(current_step):
"""
Compute a ratio according to current step,
by which the optimizer's lr will be mutiplied.
:param current_step:
:return:
"""
assert current_step <= self.args.maxsteps
if current_step < self.args.warm_up_steps:
return current_step / self.args.warm_up_steps
else:
return (self.args.maxsteps - current_step) / (self.args.maxsteps - self.args.warm_up_steps)
assert self.args.maxsteps >= self.args.warm_up_steps
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, self.model.parameters()), lr = self.args.lr)
#StepLR = torch.optim.lr_scheduler.StepLR(optimizer, step_size=200, gamma=0.5, last_epoch=-1)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch=-1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler':scheduler}
return optim_dict
| 4,053 | 34.876106 | 115 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/RGCNLitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class RGCNLitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
graph = batch["graph"]
triples = batch["triples"]
label = batch["label"]
entity = batch['entity']
relation = batch['relation']
norm = batch['norm']
score = self.model(graph, entity, relation, norm, triples)
loss = self.loss(score, label)
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
milestones = int(self.args.max_epochs / 2)
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr)
StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[milestones], gamma=0.1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 2,602 | 36.185714 | 100 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/KGELitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from .BaseLitModel import BaseLitModel
from IPython import embed
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class KGELitModel(BaseLitModel):
"""Processing of training, evaluation and testing.
"""
def __init__(self, model, args):
super().__init__(model, args)
def forward(self, x):
return self.model(x)
@staticmethod
def add_to_argparse(parser):
parser.add_argument("--lr", type=float, default=0.1)
parser.add_argument("--weight_decay", type=float, default=0.01)
return parser
def training_step(self, batch, batch_idx):
"""Getting samples and training in KG model.
Args:
batch: The training data.
batch_idx: The dict_key in batch, type: list.
Returns:
loss: The training loss for back propagation.
"""
pos_sample = batch["positive_sample"]
neg_sample = batch["negative_sample"]
mode = batch["mode"]
pos_score = self.model(pos_sample)
neg_score = self.model(pos_sample, neg_sample, mode)
if self.args.use_weight:
subsampling_weight = batch["subsampling_weight"]
loss = self.loss(pos_score, neg_score, subsampling_weight)
else:
loss = self.loss(pos_score, neg_score)
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
"""Getting samples and validation in KG model.
Args:
batch: The evalutaion data.
batch_idx: The dict_key in batch, type: list.
Returns:
results: mrr and hits@1,3,10.
"""
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
"""Getting samples and test in KG model.
Args:
batch: The evaluation data.
batch_idx: The dict_key in batch, type: list.
Returns:
results: mrr and hits@1,3,10.
"""
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def configure_optimizers(self):
"""Setting optimizer and lr_scheduler.
Returns:
optim_dict: Record the optimizer and lr_scheduler, type: dict.
"""
milestones = int(self.args.max_epochs / 2)
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr)
StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[milestones], gamma=0.1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 3,834 | 32.938053 | 100 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/CrossELitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class CrossELitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
sample = batch["sample"]
hr_label = batch["hr_label"]
tr_label = batch["tr_label"]
# sample_id = batch["sample_id"]
# sample_score = self.model(sample, sample_id)
hr_score, tr_score = self.model(sample)
hr_loss = self.loss(hr_score, hr_label)
tr_loss = self.loss(tr_score, tr_label)
loss = hr_loss + tr_loss
regularize_loss = self.args.weight_decay * self.model.regularize_loss(1)
loss += regularize_loss
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
milestones = int(self.args.max_epochs / 2)
# optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr, weight_decay = self.args.weight_decay)
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr)
StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[milestones], gamma=0.1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 2,908 | 37.276316 | 123 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/BaseLitModel.py | import argparse
import pytorch_lightning as pl
import torch
from collections import defaultdict as ddict
from neuralkg import loss
import numpy as np
class Config(dict):
def __getattr__(self, name):
return self.get(name)
def __setattr__(self, name, val):
self[name] = val
class BaseLitModel(pl.LightningModule):
"""
Generic PyTorch-Lightning class that must be initialized with a PyTorch module.
"""
def __init__(self, model, args: argparse.Namespace = None, src_list = None, dst_list=None, rel_list=None):
super().__init__()
self.model = model
self.args = args
optim_name = args.optim_name
self.optimizer_class = getattr(torch.optim, optim_name)
loss_name = args.loss_name
self.loss_class = getattr(loss, loss_name)
self.loss = self.loss_class(args, model)
if self.args.model_name == 'SEGNN':
self.automatic_optimization = False
#TODO:SEGNN
@staticmethod
def add_to_argparse(parser):
parser.add_argument("--lr", type=float, default=0.1)
parser.add_argument("--weight_decay", type=float, default=0.01)
return parser
def configure_optimizers(self):
raise NotImplementedError
def forward(self, x):
raise NotImplementedError
def training_step(self, batch, batch_idx): # pylint: disable=unused-argument
raise NotImplementedError
def validation_step(self, batch, batch_idx): # pylint: disable=unused-argument
raise NotImplementedError
def test_step(self, batch, batch_idx): # pylint: disable=unused-argument
raise NotImplementedError
def get_results(self, results, mode):
"""Summarize the results of each batch and calculate the final result of the epoch
Args:
results ([type]): The results of each batch
mode ([type]): Eval or Test
Returns:
dict: The final result of the epoch
"""
outputs = ddict(float)
count = np.array([o["count"] for o in results]).sum()
for metric in list(results[0].keys())[1:]:
final_metric = "|".join([mode, metric])
outputs[final_metric] = np.around(np.array([o[metric] for o in results]).sum() / count, decimals=3).item()
return outputs
| 2,337 | 31.472222 | 118 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/CompGCNLitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class CompGCNLitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
graph = batch["graph"] #和RGCNLitModel差别很小 形式上只有entity的区别,是否要改动
sample = batch["sample"]
label = batch["label"]
relation = batch['relation']
norm = batch['norm']
score = self.model(graph, relation, norm, sample)
label = ((1.0 - self.args.smoothing) * label) + (
1.0 / self.args.num_ent
)
loss = self.loss(score, label)
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
milestones = int(self.args.max_epochs / 2)
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr, weight_decay = 1e-7)
StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[milestones], gamma=0.1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 2,737 | 36.506849 | 103 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/ConvELitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class ConvELitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
sample = batch["sample"]
label = batch["label"]
sample_score = self.model(sample)
label = ((1.0 - self.args.smoothing) * label) + (
1.0 / self.args.num_ent
)
loss = self.loss(sample_score,label)
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='tail')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
milestones = int(self.args.max_epochs / 2)
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr, weight_decay=0)
StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[milestones], gamma=0.1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 2,572 | 34.246575 | 100 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/IterELitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
import pickle
import time
from functools import partial
class IterELitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
self.epoch=0
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
pos_sample = batch["positive_sample"]
neg_sample = batch["negative_sample"]
mode = batch["mode"]
pos_score = self.model(pos_sample)
neg_score = self.model(pos_sample, neg_sample, mode)
if self.args.use_weight:
subsampling_weight = batch["subsampling_weight"]
loss = self.loss(pos_score, neg_score, subsampling_weight)
else:
loss = self.loss(pos_score, neg_score)
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def training_epoch_end(self, results):
self.epoch+=1
if self.epoch % self.args.update_axiom_per == 0 and self.epoch !=0:
# axioms include probability for each axiom in axiom pool
# order: ref, sym, tran, inver, sub, equi, inferC
# update_axioms:
# 1) calculate probability for each axiom in axiom pool with current embeddings
# 2) update the valid_axioms
axioms_probability = self.update_axiom()
updated_train_data = self.model.update_train_triples(epoch = self.epoch, update_per= self.args.update_axiom_per)
if updated_train_data:
self.trainer.datamodule.data_train=updated_train_data
self.trainer.datamodule.train_sampler.count = self.trainer.datamodule.train_sampler.count_frequency(updated_train_data)
def update_axiom(self):
time_s = time.time()
axiom_pro = self.model.run_axiom_probability()
time_e = time.time()
print('calculate axiom score:', time_e -time_s)
with open('./save_axiom_prob/axiom_prob.pickle', 'wb') as f: pickle.dump(axiom_pro, f, pickle.HIGHEST_PROTOCOL)
with open('./save_axiom_prob/axiom_pools.pickle', 'wb') as f: pickle.dump(self.model.axiompool, f, pickle.HIGHEST_PROTOCOL)
self.model.update_valid_axioms(axiom_pro)
return self.model.run_axiom_probability()
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
milestones = [5,50]
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr)
StepLR = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=milestones, gamma=0.1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 4,230 | 40.07767 | 139 | py |
NeuralKG | NeuralKG-main/src/neuralkg/lit_model/KBATLitModel.py | from logging import debug
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import json
from collections import defaultdict as ddict
from IPython import embed
from .BaseLitModel import BaseLitModel
from neuralkg.eval_task import *
from IPython import embed
from functools import partial
class KBATLitModel(BaseLitModel):
def __init__(self, model, args):
super().__init__(model, args)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
num_epoch = self.current_epoch
if num_epoch < self.args.epoch_GAT:
model = "GAT"
adj = batch['adj_matrix']
n_hop = batch['n_hop']
pos_triple = batch['triples_GAT_pos']
neg_triple = batch['triples_GAT_neg']
pos_score = self.model(pos_triple, model, adj, n_hop)
neg_score = self.model(neg_triple, model, adj, n_hop)
loss = self.loss(model, pos_score, neg_score)
else:
model = "ConvKB"
triples = batch['triples_Con']
label = batch['label']
score = self.model(triples, model)
loss = self.loss(model, score, label=label)
self.log("Train|loss", loss, on_step=False, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
# pos_triple, tail_label, head_label = batch
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def validation_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Eval")
# self.log("Eval|mrr", outputs["Eval|mrr"], on_epoch=True)
self.log_dict(outputs, prog_bar=True, on_epoch=True)
def test_step(self, batch, batch_idx):
results = dict()
ranks = link_predict(batch, self.model, prediction='all')
results["count"] = torch.numel(ranks)
results["mrr"] = torch.sum(1.0 / ranks).item()
for k in self.args.calc_hits:
results['hits@{}'.format(k)] = torch.numel(ranks[ranks <= k])
return results
def test_epoch_end(self, results) -> None:
outputs = self.get_results(results, "Test")
self.log_dict(outputs, prog_bar=True, on_epoch=True)
'''这里设置优化器和lr_scheduler'''
def configure_optimizers(self):
if self.current_epoch < self.args.epoch_GAT:
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr, weight_decay=1e-6)
StepLR = torch.optim.lr_scheduler.StepLR(optimizer, step_size=500, gamma=0.5, last_epoch=-1)
else:
optimizer = self.optimizer_class(self.model.parameters(), lr=self.args.lr, weight_decay=1e-5)
StepLR = torch.optim.lr_scheduler.StepLR(optimizer, step_size=200, gamma=0.5, last_epoch=-1)
optim_dict = {'optimizer': optimizer, 'lr_scheduler': StepLR}
return optim_dict
| 3,269 | 37.928571 | 105 | py |
NeuralKG | NeuralKG-main/src/neuralkg/eval_task/link_prediction_SEGNN.py | import torch
import os
from IPython import embed
#TODO: SEGNN
def link_predict_SEGNN(batch, kg, model, prediction="all"):
"""The evaluate task is predicting the head entity or tail entity in incomplete triples.
Args:
batch: The batch of the triples for validation or test.
model: The KG model for training.
predicion: mode of link prediction.
Returns:
ranks: The rank of the triple to be predicted.
"""
ent_emb, rel_emb = model.aggragate_emb(kg)
if prediction == "all":
tail_ranks = tail_predict_SEGNN(batch, ent_emb, rel_emb, model)
head_ranks = head_predict_SEGNN(batch, ent_emb, rel_emb, model)
ranks = torch.cat([tail_ranks, head_ranks])
elif prediction == "head":
ranks = head_predict_SEGNN(batch, ent_emb, rel_emb, model)
elif prediction == "tail":
ranks = tail_predict_SEGNN(batch, ent_emb, rel_emb, model)
return ranks.float()
def head_predict_SEGNN(batch, ent_emb, rel_emb, model):
"""Getting head entity ranks.
Args:
batch: The batch of the triples for validation or test
model: The KG model for training.
Returns:
tensor: The rank of the head entity to be predicted, dim [batch_size]
"""
pos_triple = batch["positive_sample"]
head_idx = pos_triple[:, 0]
tail_idx = pos_triple[:, 2]
rel_idx = [pos_triple[:, 1][i] + 11 for i in range(len(pos_triple[:, 1]))]
rel_idx = torch.tensor(rel_idx)
filter_head = batch["filter_head"]
pred_score = model.predictor.score_func(ent_emb[tail_idx], rel_emb[rel_idx], ent_emb)
return calc_ranks_SEGNN(head_idx, filter_head, pred_score)
def tail_predict_SEGNN(batch, ent_emb, rel_emb, model):
"""Getting tail entity ranks.
Args:
batch: The batch of the triples for validation or test
model: The KG model for training.
Returns:
tensor: The rank of the tail entity to be predicted, dim [batch_size]
"""
pos_triple = batch["positive_sample"]
head_idx = pos_triple[:, 0]
rel_idx = pos_triple[:, 1]
tail_idx = pos_triple[:, 2]
filter_tail = batch["filter_tail"]
pred_score = model.predictor.score_func(ent_emb[head_idx], rel_emb[rel_idx], ent_emb)
return calc_ranks_SEGNN(tail_idx, filter_tail, pred_score)
def calc_ranks_SEGNN(idx, filter_label, pred_score):
"""Calculating triples score ranks.
Args:
idx ([type]): The id of the entity to be predicted.
label ([type]): The id of existing triples, to calc filtered results.
pred_score ([type]): The score of the triple predicted by the model.
Returns:
ranks: The rank of the triple to be predicted, dim [batch_size].
"""
score = pred_score + filter_label
size = filter_label.shape[0]
pred_score1 = score[torch.arange(size), idx].unsqueeze(dim=1)
compare_up = torch.gt(score, pred_score1)
compare_low = torch.ge(score, pred_score1)
ranking_up = compare_up.to(dtype=torch.float).sum(dim=1) + 1 # (bs, )
ranking_low = compare_low.to(dtype=torch.float).sum(dim=1) # include the pos one itself, no need to +1
ranking = (ranking_up + ranking_low) / 2
return ranking | 3,206 | 35.443182 | 107 | py |
NeuralKG | NeuralKG-main/src/neuralkg/eval_task/link_prediction.py | import torch
import os
from IPython import embed
def link_predict(batch, model, prediction="all"):
"""The evaluate task is predicting the head entity or tail entity in incomplete triples.
Args:
batch: The batch of the triples for validation or test.
model: The KG model for training.
predicion: mode of link prediction.
Returns:
ranks: The rank of the triple to be predicted.
"""
if prediction == "all":
tail_ranks = tail_predict(batch, model)
head_ranks = head_predict(batch, model)
ranks = torch.cat([tail_ranks, head_ranks])
elif prediction == "head":
ranks = head_predict(batch, model)
elif prediction == "tail":
ranks = tail_predict(batch, model)
return ranks.float()
def head_predict(batch, model):
"""Getting head entity ranks.
Args:
batch: The batch of the triples for validation or test
model: The KG model for training.
Returns:
tensor: The rank of the head entity to be predicted, dim [batch_size]
"""
pos_triple = batch["positive_sample"]
idx = pos_triple[:, 0]
label = batch["head_label"]
pred_score = model.get_score(batch, "head_predict")
return calc_ranks(idx, label, pred_score)
def tail_predict(batch, model):
"""Getting tail entity ranks.
Args:
batch: The batch of the triples for validation or test
model: The KG model for training.
Returns:
tensor: The rank of the tail entity to be predicted, dim [batch_size]
"""
pos_triple = batch["positive_sample"]
idx = pos_triple[:, 2]
label = batch["tail_label"]
pred_score = model.get_score(batch, "tail_predict")
return calc_ranks(idx, label, pred_score)
def calc_ranks(idx, label, pred_score):
"""Calculating triples score ranks.
Args:
idx ([type]): The id of the entity to be predicted.
label ([type]): The id of existing triples, to calc filtered results.
pred_score ([type]): The score of the triple predicted by the model.
Returns:
ranks: The rank of the triple to be predicted, dim [batch_size].
"""
b_range = torch.arange(pred_score.size()[0])
target_pred = pred_score[b_range, idx]
pred_score = torch.where(label.bool(), -torch.ones_like(pred_score) * 10000000, pred_score)
pred_score[b_range, idx] = target_pred
ranks = (
1
+ torch.argsort(
torch.argsort(pred_score, dim=1, descending=True), dim=1, descending=False
)[b_range, idx]
)
return ranks | 2,582 | 29.034884 | 95 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/KBAT_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
class KBAT_Loss(nn.Module):
def __init__(self, args, model):
super(KBAT_Loss, self).__init__()
self.args = args
self.model = model
self.GAT_loss = nn.MarginRankingLoss(self.args.margin)
self.Con_loss = nn.SoftMarginLoss()
def forward(self, model, score, neg_score=None, label=None):
if model == 'GAT':
y = -torch.ones( 2 * self.args.num_neg * self.args.train_bs).type_as(score)
score = torch.tile(score, (2*self.args.num_neg, 1)).reshape(-1)
loss = self.GAT_loss(score, neg_score, y)
elif model == 'ConvKB':
loss = self.Con_loss(score.view(-1), label.view(-1))
return loss | 774 | 34.227273 | 91 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/ComplEx_NNE_AER_Loss.py | import torch
import torch.nn as nn
from IPython import embed
from neuralkg.data import KGData
class ComplEx_NNE_AER_Loss(nn.Module):
def __init__(self, args, model):
super(ComplEx_NNE_AER_Loss, self).__init__()
self.args = args
self.model = model
self.rule_p, self.rule_q = model.rule
self.confidence = model.conf
def forward(self, pos_score, neg_score):
logistic_neg = torch.log(1 + torch.exp(neg_score)).sum(dim=1)
logistic_pos = torch.log(1 + torch.exp(-pos_score)).sum(dim=1)
logistic_loss = logistic_neg + logistic_pos
re_p, im_p = self.model.rel_emb(self.rule_p).chunk(2, dim=-1)
re_q, im_q = self.model.rel_emb(self.rule_q).chunk(2, dim=-1)
entail_loss_re = self.args.mu * torch.sum(
self.confidence * (re_p - re_q).clamp(min=0).sum(dim=-1)
)
entail_loss_im = self.args.mu * torch.sum(
self.confidence * (im_p - im_q).pow(2).sum(dim=-1)
)
entail_loss = entail_loss_re + entail_loss_im
loss = logistic_loss + entail_loss
# return loss
if self.args.regularization != 0.0:
# Use L2 regularization for ComplEx_NNE_AER
regularization = self.args.regularization * (
self.model.ent_emb.weight.norm(p=2) ** 2
+ self.model.rel_emb.weight.norm(p=2) ** 2
)
loss = loss + regularization
loss = loss.mean()
return loss
| 1,497 | 36.45 | 70 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/Cross_Entropy_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from IPython import embed
class Cross_Entropy_Loss(nn.Module):
"""Binary CrossEntropyLoss
Attributes:
args: Some pre-set parameters, etc
model: The KG model for training.
"""
def __init__(self, args, model):
super(Cross_Entropy_Loss, self).__init__()
self.args = args
self.model = model
self.loss = torch.nn.BCELoss()
def forward(self, pred, label):
"""Creates a criterion that measures the Binary Cross Entropy between the target and
the input probabilities. In math:
l_n = - w_n \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right],
Args:
pred: The score of all samples.
label: Vectors used to distinguish positive and negative samples.
Returns:
loss: The training loss for back propagation.
"""
loss = self.loss(pred, label)
return loss | 1,003 | 30.375 | 92 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/SimplE_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from IPython import embed
class SimplE_Loss(nn.Module):
def __init__(self, args, model):
super(SimplE_Loss, self).__init__()
self.args = args
self.model = model
def forward(self, pos_score, neg_score):
pos_score = -pos_score
score = torch.cat((neg_score, pos_score), dim = -1) #shape:[bs, neg_num+1]
loss = torch.sum(F.softplus(score)) + self.args.regularization * self.model.l2_loss()
return loss
| 542 | 26.15 | 93 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/RugE_Loss.py | import torch
import torch.nn as nn
import math
from torch.autograd import Variable
from IPython import embed
class RugE_Loss(nn.Module):
def __init__(self,args, model):
super(RugE_Loss, self).__init__()
self.args = args
self.model = model
def forward(self, pos_score, neg_score, rule, confidence, triple_num, pos_len):
entroy = nn.BCELoss()
# 这段代码写的太简陋了 先跑通再说
pos_label = torch.ones([pos_len, 1])
neg_label = torch.zeros([pos_len, self.args.num_neg])
one = torch.ones([1])
zero = torch.zeros([1])
pos_label = Variable(pos_label).to(self.args.gpu, dtype=torch.float)
neg_label = Variable(neg_label).to(self.args.gpu, dtype=torch.float)
one = Variable(one).to(self.args.gpu, dtype=torch.float)
zero = Variable(zero).to(self.args.gpu, dtype=torch.float)
sigmoid_neg = torch.sigmoid(neg_score)
sigmoid_pos = torch.sigmoid(pos_score)
postive_loss = entroy(sigmoid_pos, pos_label)
negative_loss = entroy(sigmoid_neg, neg_label)
pi_gradient = dict()
# 感觉应该放在这个大函数的外面,不然每次被清空也没什么用
sigmoid_value = dict()
# 在计算每个grounding rule中的unlable的三元组对应的类似gradient
for i in range(len(rule[0])):
if triple_num[i] == 2:
p1_rule = rule[0][i]
unlabel_rule = rule[1][i]
if p1_rule not in sigmoid_value:
p1_rule_score = self.model(p1_rule.unsqueeze(0))
sigmoid_rule = torch.sigmoid(p1_rule_score)
sigmoid_value[p1_rule] = sigmoid_rule
else:
sigmoid_rule = sigmoid_value[p1_rule]
if unlabel_rule not in pi_gradient:
pi_gradient[unlabel_rule] = self.args.slackness_penalty * confidence[i] * sigmoid_rule
else:
pi_gradient[unlabel_rule] += self.args.slackness_penalty * confidence[i] * sigmoid_rule
elif triple_num[i] == 3:
p1_rule = rule[0][i]
p2_rule = rule[1][i]
unlabel_rule = rule[2][i]
if p1_rule not in sigmoid_value:
p1_rule_score = self.model(p1_rule.unsqueeze(0))
sigmoid_rule = torch.sigmoid(p1_rule_score)
sigmoid_value[p1_rule] = sigmoid_rule
else:
sigmoid_rule = sigmoid_value[p1_rule]
if p2_rule not in sigmoid_value:
p2_rule_score = self.model(p2_rule.unsqueeze(0))
sigmoid_rule2 = torch.sigmoid(p2_rule_score)
sigmoid_value[p2_rule] = sigmoid_rule
else:
sigmoid_rule2 = sigmoid_value[p2_rule]
if unlabel_rule not in pi_gradient:
pi_gradient[unlabel_rule] = self.args.slackness_penalty * confidence[i] * sigmoid_rule * sigmoid_rule2
else:
pi_gradient[unlabel_rule] += self.args.slackness_penalty * confidence[i] * sigmoid_rule * sigmoid_rule2
unlabel_loss = 0.
unlabel_triples = []
gradient = []
# 对于pi_gradient中的每个三元组(不重复)的 根据公式计算s函数
for unlabel_triple in pi_gradient.keys():
unlabel_triples.append(unlabel_triple.cpu().numpy())
gradient.append(pi_gradient[unlabel_triple].cpu().detach().numpy())
unlabel_triples = torch.tensor(unlabel_triples).to(self.args.gpu)
gradient = torch.tensor(gradient).to(self.args.gpu).view(-1, 1)
unlabel_triple_score = self.model(unlabel_triples)
unlabel_triple_score = torch.sigmoid(unlabel_triple_score)
unlabel_scores = []
for i in range(0, len(gradient)):
unlabel_score = (torch.min(torch.max(unlabel_triple_score[i] + gradient[i], zero), one)).cpu().detach().numpy()
unlabel_scores.append(unlabel_score[0])
unlabel_scores = torch.tensor(unlabel_scores).to(self.args.gpu)
unlabel_scores = unlabel_scores.unsqueeze(1)
unlabel_loss = entroy(unlabel_triple_score, unlabel_scores)
# for unlabel_triple in pi_gradient.keys():
# unlabelrule_score = model(unlabel_triple.unsqueeze(0))
# sigmoid_unlabelrule = torch.sigmoid(unlabelrule_score)
# unlabel_score = torch.min(torch.max(sigmoid_unlabelrule + args.slackness_penalty * pi_gradient[unlabel_triple], zero), one)
# loss_part = entroy(sigmoid_unlabelrule, unlabel_score.to(args.gpu).detach())
# unlabel_loss = unlabel_loss + loss_part
# 所有的grounding的unlbeled的两个值sigmoid和s函数都存在list中,需要转成tensor,然后一起计算loss
loss = postive_loss + negative_loss + unlabel_loss
if self.args.weight_decay != 0.0:
#Use L2 regularization for ComplEx_NNE_AER
ent_emb_all = self.model.ent_emb(torch.arange(self.args.num_ent).to(self.args.gpu))
rel_emb_all = self.model.rel_emb(torch.arange(self.args.num_rel).to(self.args.gpu))
regularization = self.args.weight_decay * (
ent_emb_all.norm(p = 2)**2 + rel_emb_all.norm(p=2)**2
)
# print(postive_loss)
# print(negative_loss)
# print(unlabel_loss)
loss += regularization
return loss
| 5,328 | 42.325203 | 137 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/CrossE_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from IPython import embed
class CrossE_Loss(nn.Module):
def __init__(self, args, model):
super(CrossE_Loss, self).__init__()
self.args = args
self.model = model
def forward(self, score, label):
pos = torch.log(torch.clamp(score, 1e-10, 1.0)) * torch.clamp(label, 0.0, 1.0)
neg = torch.log(torch.clamp(1-score, 1e-10, 1.0)) * torch.clamp(-label, 0.0, 1.0)
num_pos = torch.sum(torch.clamp(label, 0.0, 1.0), -1)
num_neg = torch.sum(torch.clamp(-label, 0.0, 1.0), -1)
loss = - torch.sum(torch.sum(pos, -1)/num_pos) - torch.sum(torch.sum(neg, -1)/num_neg)
return loss
| 713 | 34.7 | 94 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/Margin_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from IPython import embed
class Margin_Loss(nn.Module):
"""Margin Ranking Loss
Attributes:
args: Some pre-set parameters, etc
model: The KG model for training.
"""
def __init__(self, args, model):
super(Margin_Loss, self).__init__()
self.args = args
self.model = model
self.loss = nn.MarginRankingLoss(self.args.margin)
def forward(self, pos_score, neg_score):
"""Creates a criterion that measures the loss given inputs pos_score and neg_score. In math:
\text{loss}(x1, x2, y) = \max(0, -y * (x1 - x2) + \text{margin})
Args:
pos_score: The score of positive samples.
neg_score: The score of negative samples.
Returns:
loss: The training loss for back propagation.
"""
label = torch.Tensor([1]).type_as(pos_score)
loss = self.loss(pos_score, neg_score, label)
return loss | 1,040 | 30.545455 | 100 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/RGCN_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
class RGCN_Loss(nn.Module):
def __init__(self, args, model):
super(RGCN_Loss, self).__init__()
self.args = args
self.model = model
def reg_loss(self):
return torch.mean(self.model.Loss_emb.pow(2)) + torch.mean(self.model.rel_emb.pow(2))
def forward(self, score, labels):
loss = F.binary_cross_entropy_with_logits(score, labels)
regu = self.args.regularization * self.reg_loss()
loss += regu
return loss | 558 | 28.421053 | 93 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/Adv_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from IPython import embed
class Adv_Loss(nn.Module):
"""Negative sampling loss with self-adversarial training.
Attributes:
args: Some pre-set parameters, such as self-adversarial temperature, etc.
model: The KG model for training.
"""
def __init__(self, args, model):
super(Adv_Loss, self).__init__()
self.args = args
self.model = model
def forward(self, pos_score, neg_score, subsampling_weight=None):
"""Negative sampling loss with self-adversarial training. In math:
L=-\log \sigma\left(\gamma-d_{r}(\mathbf{h}, \mathbf{t})\right)-\sum_{i=1}^{n} p\left(h_{i}^{\prime}, r, t_{i}^{\prime}\right) \log \sigma\left(d_{r}\left(\mathbf{h}_{i}^{\prime}, \mathbf{t}_{i}^{\prime}\right)-\gamma\right)
Args:
pos_score: The score of positive samples.
neg_score: The score of negative samples.
subsampling_weight: The weight for correcting pos_score and neg_score.
Returns:
loss: The training loss for back propagation.
"""
if self.args.negative_adversarial_sampling:
neg_score = (F.softmax(neg_score * self.args.adv_temp, dim=1).detach()
* F.logsigmoid(-neg_score)).sum(dim=1) #shape:[bs]
else:
neg_score = F.logsigmoid(-neg_score).mean(dim = 1)
pos_score = F.logsigmoid(pos_score).view(neg_score.shape[0]) #shape:[bs]
# from IPython import embed;embed();exit()
if self.args.use_weight:
positive_sample_loss = - (subsampling_weight * pos_score).sum()/subsampling_weight.sum()
negative_sample_loss = - (subsampling_weight * neg_score).sum()/subsampling_weight.sum()
else:
positive_sample_loss = - pos_score.mean()
negative_sample_loss = - neg_score.mean()
loss = (positive_sample_loss + negative_sample_loss) / 2
if self.args.model_name == 'ComplEx' or self.args.model_name == 'DistMult' or self.args.model_name == 'BoxE' or self.args.model_name=="IterE":
#Use L3 regularization for ComplEx and DistMult
regularization = self.args.regularization * (
self.model.ent_emb.weight.norm(p = 3)**3 + \
self.model.rel_emb.weight.norm(p = 3)**3
)
# embed();exit()
loss = loss + regularization
return loss
def normalize(self):
"""calculating the regularization.
"""
regularization = self.args.regularization * (
self.model.ent_emb.weight.norm(p = 3)**3 + \
self.model.rel_emb.weight.norm(p = 3)**3
)
return regularization | 2,791 | 41.30303 | 232 | py |
NeuralKG | NeuralKG-main/src/neuralkg/loss/Softplus_Loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from IPython import embed
class Softplus_Loss(nn.Module):
"""softplus loss.
Attributes:
args: Some pre-set parameters, etc.
model: The KG model for training.
"""
def __init__(self, args, model):
super(Softplus_Loss, self).__init__()
self.criterion = nn.Softplus()
self.args = args
self.model = model
def forward(self, pos_score, neg_score, subsampling_weight=None):
"""Negative sampling loss Softplus_Loss. In math:
\begin{aligned}
L(\boldsymbol{Q}, \boldsymbol{W})=& \sum_{r(h, t) \in \Omega \cup \Omega^{-}} \log \left(1+\exp \left(-Y_{h r t} \phi(h, r, t)\right)\right) \\
&+\lambda_1\|\boldsymbol{Q}\|_2^2+\lambda_2\|\boldsymbol{W}\|_2^2
\end{aligned}
Args:
pos_score: The score of positive samples (with regularization if DualE).
neg_score: The score of negative samples (with regularization if DualE).
Returns:
loss: The training loss for back propagation.
"""
if self.args.model_name == 'DualE':
p_score, pos_regul_1, pos_regul_2 = pos_score
n_score, neg_regul_1, neg_regul_2 = neg_score
score = torch.cat((-p_score,n_score))
loss = torch.mean(self.criterion(score))
if self.args.model_name == 'DualE':
regularization1 = (pos_regul_1+neg_regul_1*self.args.num_neg)/(self.args.num_neg+1)*self.args.regularization
regularization2 = (pos_regul_2+neg_regul_2*self.args.num_neg)/(self.args.num_neg+1)*self.args.regularization_two
loss = loss+regularization1+regularization2
return loss | 1,754 | 39.813953 | 155 | py |
NeuralKG | NeuralKG-main/src/neuralkg/utils/setup_parser.py | # -*- coding: utf-8 -*-
import argparse
import os
import yaml
import pytorch_lightning as pl
from neuralkg import lit_model
from neuralkg import data
def setup_parser():
"""Set up Python's ArgumentParser with data, model, trainer, and other arguments."""
parser = argparse.ArgumentParser(add_help=False)
# Add Trainer specific arguments, such as --max_epochs, --gpus, --precision
trainer_parser = pl.Trainer.add_argparse_args(parser)
trainer_parser._action_groups[1].title = "Trainer Args" # pylint: disable=protected-access
parser = argparse.ArgumentParser(add_help=False, parents=[trainer_parser])
# Basic arguments
parser.add_argument('--model_name', default="TransE", type=str, help='The name of model.')
parser.add_argument('--dataset_name', default="FB15K237", type=str, help='The name of dataset.')
parser.add_argument('--data_class', default="KGDataModule", type=str, help='The name of data preprocessing module, default KGDataModule.')
parser.add_argument("--litmodel_name", default="KGELitModel", type=str, help='The name of processing module of training, evaluation and testing, default KGELitModel.')
parser.add_argument("--train_sampler_class",default="UniSampler",type=str, help='Sampling method used in training, default UniSampler.')
parser.add_argument("--test_sampler_class",default="TestSampler",type=str, help='Sampling method used in validation and testing, default TestSampler.')
parser.add_argument('--loss_name', default="Adv_Loss", type=str, help='The name of loss function.')
parser.add_argument('--negative_adversarial_sampling','-adv', default=True, action='store_false', help='Use self-adversarial negative sampling.')
parser.add_argument('--optim_name', default="Adam", type=str, help='The name of optimizer')
parser.add_argument("--seed", default=321, type=int, help='Random seed.')
parser.add_argument('--margin', default=12.0, type=float, help='The fixed margin in loss function. ')
parser.add_argument('--adv_temp', default=1.0, type=float, help='The temperature of sampling in self-adversarial negative sampling.')
parser.add_argument('--emb_dim', default=200, type=int, help='The embedding dimension in KGE model.')
parser.add_argument('--out_dim', default=200, type=int, help='The output embedding dimmension in some KGE model.')
parser.add_argument('--num_neg', default=10, type=int, help='The number of negative samples corresponding to each positive sample')
parser.add_argument('--num_ent', default=None, type=int, help='The number of entity, autogenerate.')
parser.add_argument('--num_rel', default=None, type=int, help='The number of relation, autogenerate.')
parser.add_argument('--check_per_epoch', default=5, type=int, help='Evaluation per n epoch of training.')
parser.add_argument('--early_stop_patience', default=5, type=int, help='If the number of consecutive bad results is n, early stop.')
parser.add_argument("--num_layers", default=2, type=int, help='The number of layers in some GNN model.')
parser.add_argument('--regularization', '-r', default=0.0, type=float)
parser.add_argument("--decoder_model", default=None, type=str, help='The name of decoder model, in some model.')
parser.add_argument('--eval_task', default="link_prediction", type=str, help='The task of validation, default link_prediction.')
parser.add_argument("--calc_hits", default=[1,3,10], type=lambda s: [int(item) for item in s.split(',')], help='calc hits list')
parser.add_argument('--filter_flag', default=True, action='store_false', help='Filter in negative sampling.')
parser.add_argument('--gpu', default='cuda:0', type=str, help='Select the GPU in training, default cuda:0.')
parser.add_argument("--use_wandb", default=False, action='store_true',help='Use "weight and bias" to record the result.')
parser.add_argument('--use_weight', default=False, action='store_true', help='Use subsampling weight.')
parser.add_argument('--checkpoint_dir', default="", type=str, help='The checkpoint model path')
parser.add_argument('--save_config', default=False, action='store_true', help='Save paramters config file.')
parser.add_argument('--load_config', default=False, action='store_true', help='Load parametes config file.')
parser.add_argument('--config_path', default="", type=str, help='The config file path.')
parser.add_argument('--freq_init', default=4, type=int)
parser.add_argument('--test_only', default=False, action='store_true')
parser.add_argument('--shuffle', default=True, action='store_false')
parser.add_argument('--norm_flag', default=False, action='store_true')
#parser only for Ruge
parser.add_argument('--slackness_penalty', default=0.01, type=float)
#parser only for CompGCN
parser.add_argument("--opn", default='corr',type=str, help="only on CompGCN, choose Composition Operation")
#parser only for BoxE
parser.add_argument("--dis_order", default=2, type=int, help="only on BoxE, the distance order of score")
# parser only for ComplEx_NNE
parser.add_argument('--mu', default=10, type=float, help='only on ComplEx_NNE,penalty coefficient for ComplEx_NNE')
# paerser only for KBAT
parser.add_argument('--epoch_GAT', default=3000, type=int, help='only on KBAT, the epoch of GAT model')
parser.add_argument("-p2hop", "--partial_2hop", default=False, action='store_true')
# parser only for CrossE
parser.add_argument('--dropout', default=0.5, type=float, help='only on CrossE,for Dropout')
parser.add_argument('--neg_weight', default=50, type=int, help='only on CrossE, make up label')
# parer only for ConvE
parser.add_argument('--emb_shape', default=20, type=int, help='only on ConvE,The first dimension of the reshaped 2D embedding')
parser.add_argument('--inp_drop', default=0.2, type=float, help='only on ConvE,Dropout for the input embeddings')
parser.add_argument('--hid_drop', default=0.3, type=float, help='only on ConvE,Dropout for the hidden layer')
parser.add_argument('--fet_drop', default=0.2, type=float, help='only on ConvE,Dropout for the convolutional features')
parser.add_argument('--hid_size_component', default=3648, type=int, help='only on ConvE,The side of the hidden layer. The required size changes with the size of the embeddings.')
parser.add_argument('--hid_size', default=9728, type=int, help='only on ConvE,The side of the hidden layer. The required size changes with the size of the embeddings.')
parser.add_argument('--smoothing', default=0.1, type=float, help='only on ConvE,Make the label smooth')
parser.add_argument("--out_channel", default=32, type=int, help="in ConvE.py")
parser.add_argument("--ker_sz", default=3, type=int, help="in ConvE.py")
parser.add_argument("--ent_drop_pred", default=0.3, type=float, help="in ConvE.py")
parser.add_argument("--k_h", default=10, type=int, help="in ConvE.py")
parser.add_argument("--k_w", default=20, type=int, help="in ConvE.py")
#parser only for SEGNN
parser.add_argument("--kg_layer", default=1, type=int, help="in SEGNN.py")
parser.add_argument("--rm_rate", default=0.5, type=float, help= "in SEGNN.py")
parser.add_argument("--ent_drop", default=0.2, type=float, help="in SEGNN.py")
parser.add_argument("--rel_drop", default=0, type=float, help="in SEGNN.py")
parser.add_argument("--fc_drop", default = 0.1, type=float, help = "in SEGNN.py")
parser.add_argument("--comp_op", default='mul', type=str, help="in SEGNN.py")
#WN18RR
#parser.add_argument("--bn", default=True, action='store_true')
#FB15K237
parser.add_argument("--bn", default=False, action='store_true')
parser.add_argument("--warmup_epoch", default=5, type=int, help="in SEGNN.py")
parser.add_argument("--warm_up_steps", default=None, type=int, help="in SEGNN.py")
parser.add_argument("--maxsteps", default=None, type=int, help="in SEGNN.py")
#WN18RR
#parser.add_argument("--pred_rel_w", default=True, action="store_true")
#FB15K237
parser.add_argument("--pred_rel_w", default=False, action="store_true")
parser.add_argument("--label_smooth", default=0.1, type=float, help="in SEGNN.py")
# parser only for IterE
parser.add_argument("--max_entialments", default=2000, type=int, help="in IterE.py")
parser.add_argument("--axiom_types", default=10, type=int, help="in IterE.py")
parser.add_argument("--select_probability", default=0.8, type=float, help="in IterE.py")
parser.add_argument("--axiom_weight", default=1.0, type=float, help="in IterE.py")
parser.add_argument("--inject_triple_percent", default=1.0, type=float, help="in IterE.py")
parser.add_argument("--update_axiom_per",default=2, type=int, help='in IterELitModel.py')
#parser only for HAKE
parser.add_argument("--phase_weight", default=1.0, type=float, help='only on HAKE,The weight of phase part')
parser.add_argument("--modulus_weight", default=1.0, type=float, help='only on HAKE,The weight of modulus part')
#parser only for DualE
parser.add_argument("--regularization_two", default=0, type=float, help='only on DualE, regularization_two')
# Get data, model, and LitModel specific arguments
lit_model_group = parser.add_argument_group("LitModel Args")
lit_model.BaseLitModel.add_to_argparse(lit_model_group)
data_group = parser.add_argument_group("Data Args")
data.BaseDataModule.add_to_argparse(data_group)
parser.add_argument("--help", "-h", action="help")
return parser
| 9,625 | 69.262774 | 182 | py |
NeuralKG | NeuralKG-main/src/neuralkg/utils/tools.py | import importlib
from IPython import embed
import os
import time
import yaml
import torch
from torch.nn import Parameter
from torch.nn.init import xavier_normal_
def import_class(module_and_class_name: str) -> type:
"""Import class from a module, e.g. 'model.TransE'"""
module_name, class_name = module_and_class_name.rsplit(".", 1)
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)
return class_
def save_config(args):
args.save_config = False #防止和load_config冲突,导致把加载的config又保存了一遍
if not os.path.exists("config"):
os.mkdir("config")
config_file_name = time.strftime(str(args.model_name)+"_"+str(args.dataset_name)) + ".yaml"
day_name = time.strftime("%Y-%m-%d")
if not os.path.exists(os.path.join("config", day_name)):
os.makedirs(os.path.join("config", day_name))
config = vars(args)
with open(os.path.join(os.path.join("config", day_name), config_file_name), "w") as file:
file.write(yaml.dump(config))
def load_config(args, config_path):
with open(config_path, "r") as f:
config = yaml.safe_load(f)
args.__dict__.update(config)
return args
def get_param(*shape):
param = Parameter(torch.zeros(shape))
xavier_normal_(param)
return param | 1,287 | 32.025641 | 95 | py |
NeuralKG | NeuralKG-main/src/neuralkg/data/KGDataModule.py | """Base DataModule class."""
from pathlib import Path
from typing import Dict
import argparse
import os
from torch.utils.data import DataLoader
from .base_data_module import *
import pytorch_lightning as pl
class KGDataModule(BaseDataModule):
"""
Base DataModule.
Learn more at https://pytorch-lightning.readthedocs.io/en/stable/datamodules.html
"""
def __init__(
self, args: argparse.Namespace = None, train_sampler=None, test_sampler=None
) -> None:
super().__init__(args)
self.eval_bs = self.args.eval_bs
self.num_workers = self.args.num_workers
self.train_sampler = train_sampler
self.test_sampler = test_sampler
#for SEGNN
#TODO:SEGNN
if self.args.model_name == 'SEGNN':
self.data_train = self.train_sampler.get_train()
single_epoch_step = len(self.train_dataloader()) + 1
self.args.maxsteps = self.args.max_epochs * single_epoch_step
self.args.warm_up_steps = int(single_epoch_step * self.args.warmup_epoch)
def get_data_config(self):
"""Return important settings of the dataset, which will be passed to instantiate models."""
return {
"num_training_steps": self.num_training_steps,
"num_labels": self.num_labels,
}
def prepare_data(self):
"""
Use this method to do things that might write to disk or that need to be done only from a single GPU in distributed settings (so don't set state `self.x = y`).
"""
pass
def setup(self, stage=None):
"""
Split into train, val, test, and set dims.
Should assign `torch Dataset` objects to self.data_train, self.data_val, and optionally self.data_test.
"""
self.data_train = self.train_sampler.get_train()
self.data_val = self.train_sampler.get_valid()
self.data_test = self.train_sampler.get_test()
def get_train_bs(self):
"""Get batch size for training.
If the num_batches isn`t zero, it will divide data_train by num_batches to get batch size.
And if user don`t give batch size and num_batches=0, it will raise ValueError.
Returns:
self.args.train_bs: The batch size for training.
"""
if self.args.num_batches != 0:
self.args.train_bs = len(self.data_train) // self.args.num_batches
elif self.args.train_bs == 0:
raise ValueError("train_bs or num_batches must specify one")
return self.args.train_bs
def train_dataloader(self):
self.train_bs = self.get_train_bs()
return DataLoader(
self.data_train,
shuffle=True,
batch_size=self.train_bs,
num_workers=self.num_workers,
pin_memory=True,
drop_last=True,
collate_fn=self.train_sampler.sampling,
)
def val_dataloader(self):
return DataLoader(
self.data_val,
shuffle=False,
batch_size=self.eval_bs,
num_workers=self.num_workers,
pin_memory=True,
collate_fn=self.test_sampler.sampling,
)
def test_dataloader(self):
return DataLoader(
self.data_test,
shuffle=False,
batch_size=self.eval_bs,
num_workers=self.num_workers,
pin_memory=True,
collate_fn=self.test_sampler.sampling,
) | 3,501 | 33.333333 | 167 | py |
NeuralKG | NeuralKG-main/src/neuralkg/data/base_data_module.py | """Base DataModule class."""
from pathlib import Path
from typing import Dict
import argparse
import os
import pytorch_lightning as pl
from torch.utils.data import DataLoader
class Config(dict):
def __getattr__(self, name):
return self.get(name)
def __setattr__(self, name, val):
self[name] = val
BATCH_SIZE = 8
NUM_WORKERS = 8
class BaseDataModule(pl.LightningDataModule):
"""
Base DataModule.
Learn more at https://pytorch-lightning.readthedocs.io/en/stable/datamodules.html
"""
def __init__(self, args) -> None:
super().__init__()
self.args = args
@staticmethod
def add_to_argparse(parser):
parser.add_argument(
"--train_bs",
type=int,
default=0,
help="Number of examples to operate on per forward step.",
)
parser.add_argument(
"--num_batches",
type=int,
default=0,
help="Number of examples to operate on per forward step.",
)
parser.add_argument(
"--eval_bs",
type=int,
default=16,
help="Number of examples to operate on per forward step.",
)
parser.add_argument(
"--num_workers",
type=int,
default=8,
help="Number of additional processes to load data.",
)
parser.add_argument(
"--data_path",
type=str,
default="./dataset/WN18RR",
help="Number of additional processes to load data.",
)
return parser
def prepare_data(self):
"""
Use this method to do things that might write to disk or that need to be done only from a single GPU in distributed settings (so don't set state `self.x = y`).
"""
pass
def setup(self, stage=None):
"""
Split into train, val, test, and set dims.
Should assign `torch Dataset` objects to self.data_train, self.data_val, and optionally self.data_test.
"""
self.data_train = None
self.data_val = None
self.data_test = None
def train_dataloader(self):
return DataLoader(self.data_train, shuffle=True, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=True)
def val_dataloader(self):
return DataLoader(self.data_val, shuffle=False, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=True)
def test_dataloader(self):
return DataLoader(self.data_test, shuffle=False, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=True)
def get_config(self):
return dict(num_labels=self.num_labels) | 2,731 | 28.06383 | 167 | py |
NeuralKG | NeuralKG-main/src/neuralkg/data/DataPreprocess.py | import numpy as np
from torch.utils.data import Dataset
import torch
import os
from collections import defaultdict as ddict
from IPython import embed
class KGData(object):
"""Data preprocessing of kg data.
Attributes:
args: Some pre-set parameters, such as dataset path, etc.
ent2id: Encoding the entity in triples, type: dict.
rel2id: Encoding the relation in triples, type: dict.
id2ent: Decoding the entity in triples, type: dict.
id2rel: Decoding the realtion in triples, type: dict.
train_triples: Record the triples for training, type: list.
valid_triples: Record the triples for validation, type: list.
test_triples: Record the triples for testing, type: list.
all_true_triples: Record all triples including train,valid and test, type: list.
TrainTriples
Relation2Tuple
RelSub2Obj
hr2t_train: Record the tail corresponding to the same head and relation, type: defaultdict(class:set).
rt2h_train: Record the head corresponding to the same tail and relation, type: defaultdict(class:set).
h2rt_train: Record the tail, relation corresponding to the same head, type: defaultdict(class:set).
t2rh_train: Record the head, realtion corresponding to the same tail, type: defaultdict(class:set).
"""
# TODO:把里面的函数再分一分,最基础的部分再初始化的使用调用,其他函数具体情况再调用
def __init__(self, args):
self.args = args
# 基础部分
self.ent2id = {}
self.rel2id = {}
# predictor需要
self.id2ent = {}
self.id2rel = {}
# 存放三元组的id
self.train_triples = []
self.valid_triples = []
self.test_triples = []
self.all_true_triples = set()
# grounding 使用
self.TrainTriples = {}
self.Relation2Tuple = {}
self.RelSub2Obj = {}
self.hr2t_train = ddict(set)
self.rt2h_train = ddict(set)
self.h2rt_train = ddict(set)
self.t2rh_train = ddict(set)
self.get_id()
self.get_triples_id()
if args.use_weight:
self.count = self.count_frequency(self.train_triples)
def get_id(self):
"""Get entity/relation id, and entity/relation number.
Update:
self.ent2id: Entity to id.
self.rel2id: Relation to id.
self.id2ent: id to Entity.
self.id2rel: id to Relation.
self.args.num_ent: Entity number.
self.args.num_rel: Relation number.
"""
with open(os.path.join(self.args.data_path, "entities.dict")) as fin:
for line in fin:
eid, entity = line.strip().split("\t")
self.ent2id[entity] = int(eid)
self.id2ent[int(eid)] = entity
with open(os.path.join(self.args.data_path, "relations.dict")) as fin:
for line in fin:
rid, relation = line.strip().split("\t")
self.rel2id[relation] = int(rid)
self.id2rel[int(rid)] = relation
self.args.num_ent = len(self.ent2id)
self.args.num_rel = len(self.rel2id)
def get_triples_id(self):
"""Get triples id, save in the format of (h, r, t).
Update:
self.train_triples: Train dataset triples id.
self.valid_triples: Valid dataset triples id.
self.test_triples: Test dataset triples id.
"""
with open(os.path.join(self.args.data_path, "train.txt")) as f:
for line in f.readlines():
h, r, t = line.strip().split()
self.train_triples.append(
(self.ent2id[h], self.rel2id[r], self.ent2id[t])
)
tmp = str(self.ent2id[h]) + '\t' + str(self.rel2id[r]) + '\t' + str(self.ent2id[t])
self.TrainTriples[tmp] = True
iRelationID = self.rel2id[r]
strValue = str(h) + "#" + str(t)
if not iRelationID in self.Relation2Tuple:
tmpLst = []
tmpLst.append(strValue)
self.Relation2Tuple[iRelationID] = tmpLst
else:
self.Relation2Tuple[iRelationID].append(strValue)
iRelationID = self.rel2id[r]
iSubjectID = self.ent2id[h]
iObjectID = self.ent2id[t]
tmpMap = {}
tmpMap_in = {}
if not iRelationID in self.RelSub2Obj:
if not iSubjectID in tmpMap:
tmpMap_in.clear()
tmpMap_in[iObjectID] = True
tmpMap[iSubjectID] = tmpMap_in
else:
tmpMap[iSubjectID][iObjectID] = True
self.RelSub2Obj[iRelationID] = tmpMap
else:
tmpMap = self.RelSub2Obj[iRelationID]
if not iSubjectID in tmpMap:
tmpMap_in.clear()
tmpMap_in[iObjectID] = True
tmpMap[iSubjectID] = tmpMap_in
else:
tmpMap[iSubjectID][iObjectID] = True
self.RelSub2Obj[iRelationID] = tmpMap # 是不是应该要加?
with open(os.path.join(self.args.data_path, "valid.txt")) as f:
for line in f.readlines():
h, r, t = line.strip().split()
self.valid_triples.append(
(self.ent2id[h], self.rel2id[r], self.ent2id[t])
)
with open(os.path.join(self.args.data_path, "test.txt")) as f:
for line in f.readlines():
h, r, t = line.strip().split()
self.test_triples.append(
(self.ent2id[h], self.rel2id[r], self.ent2id[t])
)
self.all_true_triples = set(
self.train_triples + self.valid_triples + self.test_triples
)
def get_hr2t_rt2h_from_train(self):
"""Get the set of hr2t and rt2h from train dataset, the data type is numpy.
Update:
self.hr2t_train: The set of hr2t.
self.rt2h_train: The set of rt2h.
"""
for h, r, t in self.train_triples:
self.hr2t_train[(h, r)].add(t)
self.rt2h_train[(r, t)].add(h)
for h, r in self.hr2t_train:
self.hr2t_train[(h, r)] = np.array(list(self.hr2t_train[(h, r)]))
for r, t in self.rt2h_train:
self.rt2h_train[(r, t)] = np.array(list(self.rt2h_train[(r, t)]))
@staticmethod
def count_frequency(triples, start=4):
'''Get frequency of a partial triple like (head, relation) or (relation, tail).
The frequency will be used for subsampling like word2vec.
Args:
triples: Sampled triples.
start: Initial count number.
Returns:
count: Record the number of (head, relation).
'''
count = {}
for head, relation, tail in triples:
if (head, relation) not in count:
count[(head, relation)] = start
else:
count[(head, relation)] += 1
if (tail, -relation-1) not in count:
count[(tail, -relation-1)] = start
else:
count[(tail, -relation-1)] += 1
return count
def get_h2rt_t2hr_from_train(self):
"""Get the set of h2rt and t2hr from train dataset, the data type is numpy.
Update:
self.h2rt_train: The set of h2rt.
self.t2rh_train: The set of t2hr.
"""
for h, r, t in self.train_triples:
self.h2rt_train[h].add((r, t))
self.t2rh_train[t].add((r, h))
for h in self.h2rt_train:
self.h2rt_train[h] = np.array(list(self.h2rt_train[h]))
for t in self.t2rh_train:
self.t2rh_train[t] = np.array(list(self.t2rh_train[t]))
def get_hr_trian(self):
'''Change the generation mode of batch.
Merging triples which have same head and relation for 1vsN training mode.
Returns:
self.train_triples: The tuple(hr, t) list for training
'''
self.t_triples = self.train_triples
self.train_triples = [ (hr, list(t)) for (hr,t) in self.hr2t_train.items()]
class BaseSampler(KGData):
"""Traditional random sampling mode.
"""
def __init__(self, args):
super().__init__(args)
self.get_hr2t_rt2h_from_train()
def corrupt_head(self, t, r, num_max=1):
"""Negative sampling of head entities.
Args:
t: Tail entity in triple.
r: Relation in triple.
num_max: The maximum of negative samples generated
Returns:
neg: The negative sample of head entity filtering out the positive head entity.
"""
tmp = torch.randint(low=0, high=self.args.num_ent, size=(num_max,)).numpy()
if not self.args.filter_flag:
return tmp
mask = np.in1d(tmp, self.rt2h_train[(r, t)], assume_unique=True, invert=True)
neg = tmp[mask]
return neg
def corrupt_tail(self, h, r, num_max=1):
"""Negative sampling of tail entities.
Args:
h: Head entity in triple.
r: Relation in triple.
num_max: The maximum of negative samples generated
Returns:
neg: The negative sample of tail entity filtering out the positive tail entity.
"""
tmp = torch.randint(low=0, high=self.args.num_ent, size=(num_max,)).numpy()
if not self.args.filter_flag:
return tmp
mask = np.in1d(tmp, self.hr2t_train[(h, r)], assume_unique=True, invert=True)
neg = tmp[mask]
return neg
def head_batch(self, h, r, t, neg_size=None):
"""Negative sampling of head entities.
Args:
h: Head entity in triple
t: Tail entity in triple.
r: Relation in triple.
neg_size: The size of negative samples.
Returns:
The negative sample of head entity. [neg_size]
"""
neg_list = []
neg_cur_size = 0
while neg_cur_size < neg_size:
neg_tmp = self.corrupt_head(t, r, num_max=(neg_size - neg_cur_size) * 2)
neg_list.append(neg_tmp)
neg_cur_size += len(neg_tmp)
return np.concatenate(neg_list)[:neg_size]
def tail_batch(self, h, r, t, neg_size=None):
"""Negative sampling of tail entities.
Args:
h: Head entity in triple
t: Tail entity in triple.
r: Relation in triple.
neg_size: The size of negative samples.
Returns:
The negative sample of tail entity. [neg_size]
"""
neg_list = []
neg_cur_size = 0
while neg_cur_size < neg_size:
neg_tmp = self.corrupt_tail(h, r, num_max=(neg_size - neg_cur_size) * 2)
neg_list.append(neg_tmp)
neg_cur_size += len(neg_tmp)
return np.concatenate(neg_list)[:neg_size]
def get_train(self):
return self.train_triples
def get_valid(self):
return self.valid_triples
def get_test(self):
return self.test_triples
def get_all_true_triples(self):
return self.all_true_triples
class RevSampler(KGData):
"""Adding reverse triples in traditional random sampling mode.
For each triple (h, r, t), generate the reverse triple (t, r`, h).
r` = r + num_rel.
Attributes:
hr2t_train: Record the tail corresponding to the same head and relation, type: defaultdict(class:set).
rt2h_train: Record the head corresponding to the same tail and relation, type: defaultdict(class:set).
"""
def __init__(self, args):
super().__init__(args)
self.hr2t_train = ddict(set)
self.rt2h_train = ddict(set)
self.add_reverse_relation()
self.add_reverse_triples()
self.get_hr2t_rt2h_from_train()
def add_reverse_relation(self):
"""Get entity/relation/reverse relation id, and entity/relation number.
Update:
self.ent2id: Entity id.
self.rel2id: Relation id.
self.args.num_ent: Entity number.
self.args.num_rel: Relation number.
"""
with open(os.path.join(self.args.data_path, "relations.dict")) as fin:
len_rel2id = len(self.rel2id)
for line in fin:
rid, relation = line.strip().split("\t")
self.rel2id[relation + "_reverse"] = int(rid) + len_rel2id
self.id2rel[int(rid) + len_rel2id] = relation + "_reverse"
self.args.num_rel = len(self.rel2id)
def add_reverse_triples(self):
"""Generate reverse triples (t, r`, h).
Update:
self.train_triples: Triples for training.
self.valid_triples: Triples for validation.
self.test_triples: Triples for testing.
self.all_ture_triples: All triples including train, valid and test.
"""
with open(os.path.join(self.args.data_path, "train.txt")) as f:
for line in f.readlines():
h, r, t = line.strip().split()
self.train_triples.append(
(self.ent2id[t], self.rel2id[r + "_reverse"], self.ent2id[h])
)
with open(os.path.join(self.args.data_path, "valid.txt")) as f:
for line in f.readlines():
h, r, t = line.strip().split()
self.valid_triples.append(
(self.ent2id[t], self.rel2id[r + "_reverse"], self.ent2id[h])
)
with open(os.path.join(self.args.data_path, "test.txt")) as f:
for line in f.readlines():
h, r, t = line.strip().split()
self.test_triples.append(
(self.ent2id[t], self.rel2id[r + "_reverse"], self.ent2id[h])
)
self.all_true_triples = set(
self.train_triples + self.valid_triples + self.test_triples
)
def get_train(self):
return self.train_triples
def get_valid(self):
return self.valid_triples
def get_test(self):
return self.test_triples
def get_all_true_triples(self):
return self.all_true_triples
def corrupt_head(self, t, r, num_max=1):
"""Negative sampling of head entities.
Args:
t: Tail entity in triple.
r: Relation in triple.
num_max: The maximum of negative samples generated
Returns:
neg: The negative sample of head entity filtering out the positive head entity.
"""
tmp = torch.randint(low=0, high=self.args.num_ent, size=(num_max,)).numpy()
if not self.args.filter_flag:
return tmp
mask = np.in1d(tmp, self.rt2h_train[(r, t)], assume_unique=True, invert=True)
neg = tmp[mask]
return neg
def corrupt_tail(self, h, r, num_max=1):
"""Negative sampling of tail entities.
Args:
h: Head entity in triple.
r: Relation in triple.
num_max: The maximum of negative samples generated
Returns:
neg: The negative sample of tail entity filtering out the positive tail entity.
"""
tmp = torch.randint(low=0, high=self.args.num_ent, size=(num_max,)).numpy()
if not self.args.filter_flag:
return tmp
mask = np.in1d(tmp, self.hr2t_train[(h, r)], assume_unique=True, invert=True)
neg = tmp[mask]
return neg
def head_batch(self, h, r, t, neg_size=None):
"""Negative sampling of head entities.
Args:
h: Head entity in triple
t: Tail entity in triple.
r: Relation in triple.
neg_size: The size of negative samples.
Returns:
The negative sample of head entity. [neg_size]
"""
neg_list = []
neg_cur_size = 0
while neg_cur_size < neg_size:
neg_tmp = self.corrupt_head(t, r, num_max=(neg_size - neg_cur_size) * 2)
neg_list.append(neg_tmp)
neg_cur_size += len(neg_tmp)
return np.concatenate(neg_list)[:neg_size]
def tail_batch(self, h, r, t, neg_size=None):
"""Negative sampling of tail entities.
Args:
h: Head entity in triple
t: Tail entity in triple.
r: Relation in triple.
neg_size: The size of negative samples.
Returns:
The negative sample of tail entity. [neg_size]
"""
neg_list = []
neg_cur_size = 0
while neg_cur_size < neg_size:
neg_tmp = self.corrupt_tail(h, r, num_max=(neg_size - neg_cur_size) * 2)
neg_list.append(neg_tmp)
neg_cur_size += len(neg_tmp)
return np.concatenate(neg_list)[:neg_size] | 17,102 | 34.930672 | 110 | py |
NeuralKG | NeuralKG-main/src/neuralkg/data/Sampler.py | from numpy.random.mtrand import normal
import torch
import numpy as np
from torch.utils.data import Dataset
from collections import defaultdict as ddict
import random
from .DataPreprocess import *
from IPython import embed
import dgl
import torch.nn.functional as F
import time
import queue
from os.path import join
import math
class UniSampler(BaseSampler):
"""Random negative sampling
Filtering out positive samples and selecting some samples randomly as negative samples.
Attributes:
cross_sampling_flag: The flag of cross sampling head and tail negative samples.
"""
def __init__(self, args):
super().__init__(args)
self.cross_sampling_flag = 0
def sampling(self, data):
"""Filtering out positive samples and selecting some samples randomly as negative samples.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The training data.
"""
batch_data = {}
neg_ent_sample = []
subsampling_weight = []
self.cross_sampling_flag = 1 - self.cross_sampling_flag
if self.cross_sampling_flag == 0:
batch_data['mode'] = "head-batch"
for h, r, t in data:
neg_head = self.head_batch(h, r, t, self.args.num_neg)
neg_ent_sample.append(neg_head)
if self.args.use_weight:
weight = self.count[(h, r)] + self.count[(t, -r-1)]
subsampling_weight.append(weight)
else:
batch_data['mode'] = "tail-batch"
for h, r, t in data:
neg_tail = self.tail_batch(h, r, t, self.args.num_neg)
neg_ent_sample.append(neg_tail)
if self.args.use_weight:
weight = self.count[(h, r)] + self.count[(t, -r-1)]
subsampling_weight.append(weight)
batch_data["positive_sample"] = torch.LongTensor(np.array(data))
batch_data['negative_sample'] = torch.LongTensor(np.array(neg_ent_sample))
if self.args.use_weight:
batch_data["subsampling_weight"] = torch.sqrt(1/torch.tensor(subsampling_weight))
return batch_data
def uni_sampling(self, data):
batch_data = {}
neg_head_list = []
neg_tail_list = []
for h, r, t in data:
neg_head = self.head_batch(h, r, t, self.args.num_neg)
neg_head_list.append(neg_head)
neg_tail = self.tail_batch(h, r, t, self.args.num_neg)
neg_tail_list.append(neg_tail)
batch_data["positive_sample"] = torch.LongTensor(np.array(data))
batch_data['negative_head'] = torch.LongTensor(np.arrary(neg_head_list))
batch_data['negative_tail'] = torch.LongTensor(np.arrary(neg_tail_list))
return batch_data
def get_sampling_keys(self):
return ['positive_sample', 'negative_sample', 'mode']
class BernSampler(BaseSampler):
"""Using bernoulli distribution to select whether to replace the head entity or tail entity.
Attributes:
lef_mean: Record the mean of head entity
rig_mean: Record the mean of tail entity
"""
def __init__(self, args):
super().__init__(args)
self.lef_mean, self.rig_mean = self.calc_bern()
def __normal_batch(self, h, r, t, neg_size):
"""Generate replace head/tail list according to Bernoulli distribution.
Args:
h: The head of triples.
r: The relation of triples.
t: The tail of triples.
neg_size: The number of negative samples corresponding to each triple
Returns:
numpy.array: replace head list and replace tail list.
"""
neg_size_h = 0
neg_size_t = 0
prob = self.rig_mean[r] / (self.rig_mean[r] + self.lef_mean[r])
for i in range(neg_size):
if random.random() > prob:
neg_size_h += 1
else:
neg_size_t += 1
res = []
neg_list_h = []
neg_cur_size = 0
while neg_cur_size < neg_size_h:
neg_tmp_h = self.corrupt_head(t, r, num_max=(neg_size_h - neg_cur_size) * 2)
neg_list_h.append(neg_tmp_h)
neg_cur_size += len(neg_tmp_h)
if neg_list_h != []:
neg_list_h = np.concatenate(neg_list_h)
for hh in neg_list_h[:neg_size_h]:
res.append((hh, r, t))
neg_list_t = []
neg_cur_size = 0
while neg_cur_size < neg_size_t:
neg_tmp_t = self.corrupt_tail(h, r, num_max=(neg_size_t - neg_cur_size) * 2)
neg_list_t.append(neg_tmp_t)
neg_cur_size += len(neg_tmp_t)
if neg_list_t != []:
neg_list_t = np.concatenate(neg_list_t)
for tt in neg_list_t[:neg_size_t]:
res.append((h, r, tt))
return res
def sampling(self, data):
"""Using bernoulli distribution to select whether to replace the head entity or tail entity.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The training data.
"""
batch_data = {}
neg_ent_sample = []
batch_data['mode'] = 'bern'
for h, r, t in data:
neg_ent = self.__normal_batch(h, r, t, self.args.num_neg)
neg_ent_sample += neg_ent
batch_data["positive_sample"] = torch.LongTensor(np.array(data))
batch_data["negative_sample"] = torch.LongTensor(np.array(neg_ent_sample))
return batch_data
def calc_bern(self):
"""Calculating the lef_mean and rig_mean.
Returns:
lef_mean: Record the mean of head entity.
rig_mean: Record the mean of tail entity.
"""
h_of_r = ddict(set)
t_of_r = ddict(set)
freqRel = ddict(float)
lef_mean = ddict(float)
rig_mean = ddict(float)
for h, r, t in self.train_triples:
freqRel[r] += 1.0
h_of_r[r].add(h)
t_of_r[r].add(t)
for r in h_of_r:
lef_mean[r] = freqRel[r] / len(h_of_r[r])
rig_mean[r] = freqRel[r] / len(t_of_r[r])
return lef_mean, rig_mean
@staticmethod
def sampling_keys():
return ['positive_sample', 'negative_sample', 'mode']
class AdvSampler(BaseSampler):
"""Self-adversarial negative sampling, in math:
p\left(h_{j}^{\prime}, r, t_{j}^{\prime} \mid\left\{\left(h_{i}, r_{i}, t_{i}\right)\right\}\right)=\frac{\exp \alpha f_{r}\left(\mathbf{h}_{j}^{\prime}, \mathbf{t}_{j}^{\prime}\right)}{\sum_{i} \exp \alpha f_{r}\left(\mathbf{h}_{i}^{\prime}, \mathbf{t}_{i}^{\prime}\right)}
Attributes:
freq_hr: The count of (h, r) pairs.
freq_tr: The count of (t, r) pairs.
"""
def __init__(self, args):
super().__init__(args)
self.freq_hr, self.freq_tr = self.calc_freq()
def sampling(self, pos_sample):
"""Self-adversarial negative sampling.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The training data.
"""
data = pos_sample.numpy().tolist()
adv_sampling = []
for h, r, t in data:
weight = self.freq_hr[(h, r)] + self.freq_tr[(t, r)]
adv_sampling.append(weight)
adv_sampling = torch.tensor(adv_sampling, dtype=torch.float32).cuda()
adv_sampling = torch.sqrt(1 / adv_sampling)
return adv_sampling
def calc_freq(self):
"""Calculating the freq_hr and freq_tr.
Returns:
freq_hr: The count of (h, r) pairs.
freq_tr: The count of (t, r) pairs.
"""
freq_hr, freq_tr = {}, {}
for h, r, t in self.train_triples:
if (h, r) not in freq_hr:
freq_hr[(h, r)] = self.args.freq_init
else:
freq_hr[(h, r)] += 1
if (t, r) not in freq_tr:
freq_tr[(t, r)] = self.args.freq_init
else:
freq_tr[(t, r)] += 1
return freq_hr, freq_tr
class AllSampler(RevSampler):
"""Merging triples which have same head and relation, all false tail entities are taken as negative samples.
"""
def __init__(self, args):
super().__init__(args)
# self.num_rel_without_rev = self.args.num_rel // 2
def sampling(self, data):
"""Randomly sampling from the merged triples.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The training data.
"""
# sample_id = [] #确定triple里的relation是否是reverse的。reverse为1,不是为0
batch_data = {}
table = torch.zeros(len(data), self.args.num_ent)
for id, (h, r, _) in enumerate(data):
hr_sample = self.hr2t_train[(h, r)]
table[id][hr_sample] = 1
# if r > self.num_rel_without_rev:
# sample_id.append(1)
# else:
# sample_id.append(0)
batch_data["sample"] = torch.LongTensor(np.array(data))
batch_data["label"] = table.float()
# batch_data["sample_id"] = torch.LongTensor(sample_id)
return batch_data
def sampling_keys(self):
return ["sample", "label"]
class CrossESampler(BaseSampler):
# TODO:类名还需要商榷下
def __init__(self, args):
super().__init__(args)
self.neg_weight = float(self.args.neg_weight / self.args.num_ent)
def sampling(self, data):
'''一个样本同时做head/tail prediction'''
batch_data = {}
hr_label = self.init_label(len(data))
tr_label = self.init_label(len(data))
for id, (h, r, t) in enumerate(data):
hr_sample = self.hr2t_train[(h, r)]
hr_label[id][hr_sample] = 1.0
tr_sample = self.rt2h_train[(r, t)]
tr_label[id][tr_sample] = 1.0
batch_data["sample"] = torch.LongTensor(data)
batch_data["hr_label"] = hr_label.float()
batch_data["tr_label"] = tr_label.float()
return batch_data
def init_label(self, row):
label = torch.rand(row, self.args.num_ent)
label = (label > self.neg_weight).float()
label -= 1.0
return label
def sampling_keys(self):
return ["sample", "label"]
class ConvSampler(RevSampler): #TODO:SEGNN
"""Merging triples which have same head and relation, all false tail entities are taken as negative samples.
The triples which have same head and relation are treated as one triple.
Attributes:
label: Mask the false tail as negative samples.
triples: The triples used to be sampled.
"""
def __init__(self, args):
self.label = None
self.triples = None
super().__init__(args)
super().get_hr_trian()
def sampling(self, pos_hr_t):
"""Randomly sampling from the merged triples.
Args:
pos_hr_t: The triples ((head,relation) pairs) used to be sampled.
Returns:
batch_data: The training data.
"""
batch_data = {}
t_triples = []
self.label = torch.zeros(self.args.train_bs, self.args.num_ent)
self.triples = torch.LongTensor([hr for hr , _ in pos_hr_t])
for hr, t in pos_hr_t:
t_triples.append(t)
for id, hr_sample in enumerate([t for _ ,t in pos_hr_t]):
self.label[id][hr_sample] = 1
batch_data["sample"] = self.triples
batch_data["label"] = self.label
batch_data["t_triples"] = t_triples
return batch_data
def sampling_keys(self):
return ["sample", "label", "t_triples"]
class XTransESampler(RevSampler):
"""Random negative sampling and recording neighbor entities.
Attributes:
triples: The triples used to be sampled.
neg_sample: The negative samples.
h_neighbor: The neighbor of sampled entites.
h_mask: The tag of effecitve neighbor.
max_neighbor: The maximum of the neighbor entities.
"""
def __init__(self, args):
super().__init__(args)
super().get_h2rt_t2hr_from_train()
self.triples = None
self.neg_sample = None
self.h_neighbor = None
self.h_mask = None
self.max_neighbor = 200
def sampling(self, data):
"""Random negative sampling and recording neighbor entities.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The training data.
"""
batch_data = {}
neg_ent_sample = []
mask = np.zeros([self.args.train_bs, 20000], dtype=float)
h_neighbor = np.zeros([self.args.train_bs, 20000, 2])
for id, triples in enumerate(data):
h,r,t = triples
num_h_neighbor = len(self.h2rt_train[h])
h_neighbor[id][0:num_h_neighbor] = np.array(self.h2rt_train[h])
mask[id][0:num_h_neighbor] = np.ones([num_h_neighbor])
neg_tail = self.tail_batch(h, r, t, self.args.num_neg)
neg_ent_sample.append(neg_tail)
self.triples = data
self.neg_sample = neg_ent_sample
self.h_neighbor = h_neighbor[:, :self.max_neighbor]
self.h_mask = mask[:, :self.max_neighbor]
batch_data["positive_sample"] = torch.LongTensor(self.triples)
batch_data['negative_sample'] = torch.LongTensor(self.neg_sample)
batch_data['neighbor'] = torch.LongTensor(self.h_neighbor)
batch_data['mask'] = torch.LongTensor(self.h_mask)
batch_data['mode'] = "tail-batch"
return batch_data
def get_sampling_keys(self):
return ['positive_sample', 'negative_sample', 'neighbor', 'mask', 'mode']
class GraphSampler(RevSampler):
"""Graph based sampling in neural network.
Attributes:
entity: The entities of sampled triples.
relation: The relation of sampled triples.
triples: The sampled triples.
graph: The graph structured sampled triples by dgl.graph in DGL.
norm: The edge norm in graph.
label: Mask the false tail as negative samples.
"""
def __init__(self, args):
super().__init__(args)
self.entity = None
self.relation = None
self.triples = None
self.graph = None
self.norm = None
self.label = None
def sampling(self, pos_triples):
"""Graph based sampling in neural network.
Args:
pos_triples: The triples used to be sampled.
Returns:
batch_data: The training data.
"""
batch_data = {}
pos_triples = np.array(pos_triples)
pos_triples, self.entity = self.sampling_positive(pos_triples)
head_triples = self.sampling_negative('head', pos_triples, self.args.num_neg)
tail_triples = self.sampling_negative('tail', pos_triples, self.args.num_neg)
self.triples = np.concatenate((pos_triples,head_triples,tail_triples))
batch_data['entity'] = self.entity
batch_data['triples'] = self.triples
self.label = torch.zeros((len(self.triples),1))
self.label[0 : self.args.train_bs] = 1
batch_data['label'] = self.label
split_size = int(self.args.train_bs * 0.5)
graph_split_ids = np.random.choice(
self.args.train_bs,
size=split_size,
replace=False
)
head,rela,tail = pos_triples.transpose()
head = torch.tensor(head[graph_split_ids], dtype=torch.long).contiguous()
rela = torch.tensor(rela[graph_split_ids], dtype=torch.long).contiguous()
tail = torch.tensor(tail[graph_split_ids], dtype=torch.long).contiguous()
self.graph, self.relation, self.norm = self.build_graph(len(self.entity), (head,rela,tail), -1)
batch_data['graph'] = self.graph
batch_data['relation'] = self.relation
batch_data['norm'] = self.norm
return batch_data
def get_sampling_keys(self):
return ['graph','triples','label','entity','relation','norm']
def sampling_negative(self, mode, pos_triples, num_neg):
"""Random negative sampling without filtering
Args:
mode: The mode of negtive sampling.
pos_triples: The positive triples.
num_neg: The number of negative samples corresponding to each triple.
Results:
neg_samples: The negative triples.
"""
neg_random = np.random.choice(
len(self.entity),
size = num_neg * len(pos_triples)
)
neg_samples = np.tile(pos_triples, (num_neg, 1))
if mode == 'head':
neg_samples[:,0] = neg_random
elif mode == 'tail':
neg_samples[:,2] = neg_random
return neg_samples
def build_graph(self, num_ent, triples, power):
"""Using sampled triples to build a graph by dgl.graph in DGL.
Args:
num_ent: The number of entities.
triples: The positive sampled triples.
power: The power index for normalization.
Returns:
rela: The relation of sampled triples.
graph: The graph structured sampled triples by dgl.graph in DGL.
edge_norm: The edge norm in graph.
"""
head, rela, tail = triples[0], triples[1], triples[2]
graph = dgl.graph(([], []))
graph.add_nodes(num_ent)
graph.add_edges(head, tail)
node_norm = self.comp_deg_norm(graph, power)
edge_norm = self.node_norm_to_edge_norm(graph,node_norm)
rela = torch.tensor(rela)
return graph, rela, edge_norm
def comp_deg_norm(self, graph, power=-1):
"""Calculating the normalization node weight.
Args:
graph: The graph structured sampled triples by dgl.graph in DGL.
power: The power index for normalization.
Returns:
tensor: The node weight of normalization.
"""
graph = graph.local_var()
in_deg = graph.in_degrees(range(graph.number_of_nodes())).float().numpy()
norm = in_deg.__pow__(power)
norm[np.isinf(norm)] = 0
return torch.from_numpy(norm)
def node_norm_to_edge_norm(slef, graph, node_norm):
"""Calculating the normalization edge weight.
Args:
graph: The graph structured sampled triples by dgl.graph in DGL.
node_norm: The node weight of normalization.
Returns:
tensor: The edge weight of normalization.
"""
graph = graph.local_var()
# convert to edge norm
graph.ndata['norm'] = node_norm.view(-1,1)
graph.apply_edges(lambda edges : {'norm' : edges.dst['norm']})
return graph.edata['norm']
def sampling_positive(self,positive_triples):
"""Regenerate positive sampling.
Args:
positive_triples: The positive sampled triples.
Results:
The regenerate triples and entities filter invisible entities.
"""
edges = np.random.choice(
np.arange(len(positive_triples)),
size = self.args.train_bs,
replace=False
)
edges = positive_triples[edges]
head, rela, tail = np.array(edges).transpose()
entity, index = np.unique((head, tail), return_inverse=True)
head, tail = np.reshape(index, (2, -1))
return np.stack((head,rela,tail)).transpose(), \
torch.from_numpy(entity).view(-1,1).long()
class KBATSampler(BaseSampler):
"""Graph based n_hop neighbours in neural network.
Attributes:
n_hop: The graph of n_hop neighbours.
graph: The adjacency graph.
neighbours: The neighbours of sampled triples.
adj_matrix:The triples of sampled.
triples: The sampled triples.
triples_GAT_pos: Positive triples.
triples_GAT_neg: Negative triples.
triples_Con: All triples including positive triples and negative triples.
label: Mask the false tail as negative samples.
"""
def __init__(self, args):
super().__init__(args)
self.n_hop = None
self.graph = None
self.neighbours = None
self.adj_matrix = None
self.entity = None
self.triples_GAT_pos = None
self.triples_GAT_neg = None
self.triples_Con = None
self.label = None
self.get_neighbors()
def sampling(self, pos_triples):
"""Graph based n_hop neighbours in neural network.
Args:
pos_triples: The triples used to be sampled.
Returns:
batch_data: The training data.
"""
batch_data = {}
#--------------------KBAT-Sampler------------------------------------------
self.entity = self.get_unique_entity(pos_triples)
head_triples = self.sam_negative('head', pos_triples, self.args.num_neg)
tail_triples = self.sam_negative('tail', pos_triples, self.args.num_neg)
self.triples_GAT_neg = torch.tensor(np.concatenate((head_triples, tail_triples)))
batch_data['triples_GAT_pos'] = torch.tensor(pos_triples)
batch_data['triples_GAT_neg'] = self.triples_GAT_neg
head, rela, tail = torch.tensor(self.train_triples).t()
self.adj_matrix = (torch.stack((tail, head)), rela)
batch_data['adj_matrix'] = self.adj_matrix
self.n_hop = self.get_batch_nhop_neighbors_all()
batch_data['n_hop'] = self.n_hop
#--------------------ConvKB-Sampler------------------------------------------
head_triples = self.sampling_negative('head', pos_triples, self.args.num_neg)
tail_triples = self.sampling_negative('tail', pos_triples, self.args.num_neg)
self.triples_Con = np.concatenate((pos_triples, head_triples, tail_triples))
self.label = -torch.ones((len(self.triples_Con),1))
self.label[0 : self.args.train_bs] = 1
batch_data['triples_Con'] = self.triples_Con
batch_data['label'] = self.label
return batch_data
def get_sampling_keys(self):
return ['adj_matrix', 'n_hop', 'triples_GAT_pos',
'triples_GAT_neg', 'triples_Con' , 'label']
def bfs(self, graph, source, nbd_size=2):
"""Using depth first search algorithm to generate n_hop neighbor graph.
Args:
graph: The adjacency graph.
source: Head node.
nbd_size: The number of hops.
Returns:
neighbors: N_hop neighbor graph.
"""
visit = {}
distance = {}
parent = {}
distance_lengths = {}
visit[source] = 1
distance[source] = 0
parent[source] = (-1, -1)
q = queue.Queue()
q.put((source, -1))
while(not q.empty()):
top = q.get()
if top[0] in graph.keys():
for target in graph[top[0]].keys():
if(target in visit.keys()):
continue
else:
q.put((target, graph[top[0]][target]))
distance[target] = distance[top[0]] + 1
visit[target] = 1
if distance[target] > 2:
continue
parent[target] = (top[0], graph[top[0]][target]) # 记录父亲节点id和关系id
if distance[target] not in distance_lengths.keys():
distance_lengths[distance[target]] = 1
neighbors = {}
for target in visit.keys():
if(distance[target] != nbd_size):
continue
edges = [-1, parent[target][1]]
relations = []
entities = [target]
temp = target
while(parent[temp] != (-1, -1)):
relations.append(parent[temp][1])
entities.append(parent[temp][0])
temp = parent[temp][0]
if(distance[target] in neighbors.keys()):
neighbors[distance[target]].append(
(tuple(relations), tuple(entities[:-1]))) #删除已知的source 记录前两跳实体及关系
else:
neighbors[distance[target]] = [
(tuple(relations), tuple(entities[:-1]))]
return neighbors
def get_neighbors(self, nbd_size=2):
"""Getting the relation and entity of the source in the n_hop neighborhood.
Args:
nbd_size: The number of hops.
Returns:
self.neighbours: Record the relation and entity of the source in the n_hop neighborhood.
"""
self.graph = {}
for triple in self.train_triples:
head = triple[0]
rela = triple[1]
tail = triple[2]
if(head not in self.graph.keys()):
self.graph[head] = {}
self.graph[head][tail] = rela
else:
self.graph[head][tail] = rela
neighbors = {}
'''
import pickle
print("Opening node_neighbors pickle object")
file = self.args.data_path + "/2hop.pickle"
with open(file, 'rb') as handle:
self.neighbours = pickle.load(handle)
return
'''
start_time = time.time()
print("Start Graph BFS")
for head in self.graph.keys():
temp_neighbors = self.bfs(self.graph, head, nbd_size)
for distance in temp_neighbors.keys():
if(head in neighbors.keys()):
if(distance in neighbors[head].keys()):
neighbors[head][distance].append(
temp_neighbors[distance])
else:
neighbors[head][distance] = temp_neighbors[distance]
else:
neighbors[head] = {}
neighbors[head][distance] = temp_neighbors[distance]
print("Finish BFS, time taken ", time.time() - start_time)
self.neighbours = neighbors
def get_unique_entity(self, triples):
"""Getting the set of entity.
Args:
triples: The sampled triples.
Returns:
numpy.array: The set of entity
"""
train_triples = np.array(triples)
train_entities = np.concatenate((train_triples[:,0], train_triples[:,2]))
return np.unique(train_entities)
def get_batch_nhop_neighbors_all(self, nbd_size=2):
"""Getting n_hop neighbors of all entities in batch.
Args:
nbd_size: The number of hops.
Returns:
The set of n_hop neighbors.
"""
batch_source_triples = []
for source in self.entity:
if source in self.neighbours.keys():
nhop_list = self.neighbours[source][nbd_size]
for i, tup in enumerate(nhop_list):
if(self.args.partial_2hop and i >= 2):
break
batch_source_triples.append([source,
tup[0][-1],
tup[0][0],
tup[1][0]])
n_hop = np.array(batch_source_triples).astype(np.int32)
return torch.autograd.Variable(torch.LongTensor(n_hop))
def sampling_negative(self, mode, pos_triples, num_neg):
"""Random negative sampling.
Args:
mode: The mode of negtive sampling.
pos_triples: The positive triples.
num_neg: The number of negative samples corresponding to each triple.
Results:
neg_samples: The negative triples.
"""
neg_samples = np.tile(pos_triples, (num_neg, 1))
if mode == 'head':
neg_head = []
for h, r, t in pos_triples:
neg_head.append(self.head_batch(h, r, t, num_neg))
neg_samples[:,0] = torch.tensor(neg_head).t().reshape(-1)
elif mode == 'tail':
neg_tail = []
for h, r, t in pos_triples:
neg_tail.append(self.tail_batch(h, r, t, num_neg))
neg_samples[:,2] = torch.tensor(neg_tail).t().reshape(-1)
return neg_samples
def sam_negative(self, mode, pos_triples, num_neg):
"""Random negative sampling without filter.
Args:
mode: The mode of negtive sampling.
pos_triples: The positive triples.
num_neg: The number of negative samples corresponding to each triple.
Results:
neg_samples: The negative triples.
"""
neg_random = np.random.choice(
len(self.entity),
size = num_neg * len(pos_triples)
)
neg_samples = np.tile(pos_triples, (num_neg, 1))
if mode == 'head':
neg_samples[:,0] = neg_random
elif mode == 'tail':
neg_samples[:,2] = neg_random
return neg_samples
class CompGCNSampler(GraphSampler):
"""Graph based sampling in neural network.
Attributes:
relation: The relation of sampled triples.
triples: The sampled triples.
graph: The graph structured sampled triples by dgl.graph in DGL.
norm: The edge norm in graph.
label: Mask the false tail as negative samples.
"""
def __init__(self, args):
super().__init__(args)
self.relation = None
self.triples = None
self.graph = None
self.norm = None
self.label = None
super().get_hr_trian()
self.graph, self.relation, self.norm = \
self.build_graph(self.args.num_ent, np.array(self.t_triples).transpose(), -0.5)
def sampling(self, pos_hr_t):
"""Graph based n_hop neighbours in neural network.
Args:
pos_hr_t: The triples(hr, t) used to be sampled.
Returns:
batch_data: The training data.
"""
batch_data = {}
self.label = torch.zeros(self.args.train_bs, self.args.num_ent)
self.triples = torch.LongTensor([hr for hr , _ in pos_hr_t])
for id, hr_sample in enumerate([t for _ ,t in pos_hr_t]):
self.label[id][hr_sample] = 1
batch_data['sample'] = self.triples
batch_data['label'] = self.label
batch_data['graph'] = self.graph
batch_data['relation'] = self.relation
batch_data['norm'] = self.norm
return batch_data
def get_sampling_keys(self):
return ['sample','label','graph','relation','norm']
def node_norm_to_edge_norm(self, graph, node_norm):
"""Calculating the normalization edge weight.
Args:
graph: The graph structured sampled triples by dgl.graph in DGL.
node_norm: The node weight of normalization.
Returns:
norm: The edge weight of normalization.
"""
graph.ndata['norm'] = node_norm
graph.apply_edges(lambda edges: {'norm': edges.dst['norm'] * edges.src['norm']})
norm = graph.edata.pop('norm').squeeze()
return norm
class TestSampler(object):
"""Sampling triples and recording positive triples for testing.
Attributes:
sampler: The function of training sampler.
hr2t_all: Record the tail corresponding to the same head and relation.
rt2h_all: Record the head corresponding to the same tail and relation.
num_ent: The count of entities.
"""
def __init__(self, sampler):
self.sampler = sampler
self.hr2t_all = ddict(set)
self.rt2h_all = ddict(set)
self.get_hr2t_rt2h_from_all()
self.num_ent = sampler.args.num_ent
def get_hr2t_rt2h_from_all(self):
"""Get the set of hr2t and rt2h from all datasets(train, valid, and test), the data type is tensor.
Update:
self.hr2t_all: The set of hr2t.
self.rt2h_all: The set of rt2h.
"""
self.all_true_triples = self.sampler.get_all_true_triples()
for h, r, t in self.all_true_triples:
self.hr2t_all[(h, r)].add(t)
self.rt2h_all[(r, t)].add(h)
for h, r in self.hr2t_all:
self.hr2t_all[(h, r)] = torch.tensor(list(self.hr2t_all[(h, r)]))
for r, t in self.rt2h_all:
self.rt2h_all[(r, t)] = torch.tensor(list(self.rt2h_all[(r, t)]))
def sampling(self, data):
"""Sampling triples and recording positive triples for testing.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The data used to be evaluated.
"""
batch_data = {}
head_label = torch.zeros(len(data), self.num_ent)
tail_label = torch.zeros(len(data), self.num_ent)
for idx, triple in enumerate(data):
head, rel, tail = triple
head_label[idx][self.rt2h_all[(rel, tail)]] = 1.0
tail_label[idx][self.hr2t_all[(head, rel)]] = 1.0
batch_data["positive_sample"] = torch.tensor(data)
batch_data["head_label"] = head_label
batch_data["tail_label"] = tail_label
return batch_data
def get_sampling_keys(self):
return ["positive_sample", "head_label", "tail_label"]
class GraphTestSampler(object):
"""Sampling graph for testing.
Attributes:
sampler: The function of training sampler.
hr2t_all: Record the tail corresponding to the same head and relation.
rt2h_all: Record the head corresponding to the same tail and relation.
num_ent: The count of entities.
triples: The training triples.
"""
def __init__(self, sampler):
self.sampler = sampler
self.hr2t_all = ddict(set)
self.rt2h_all = ddict(set)
self.get_hr2t_rt2h_from_all()
self.num_ent = sampler.args.num_ent
self.triples = sampler.train_triples
def get_hr2t_rt2h_from_all(self):
"""Get the set of hr2t and rt2h from all datasets(train, valid, and test), the data type is tensor.
Update:
self.hr2t_all: The set of hr2t.
self.rt2h_all: The set of rt2h.
"""
self.all_true_triples = self.sampler.get_all_true_triples()
for h, r, t in self.all_true_triples:
self.hr2t_all[(h, r)].add(t)
self.rt2h_all[(r, t)].add(h)
for h, r in self.hr2t_all:
self.hr2t_all[(h, r)] = torch.tensor(list(self.hr2t_all[(h, r)]))
for r, t in self.rt2h_all:
self.rt2h_all[(r, t)] = torch.tensor(list(self.rt2h_all[(r, t)]))
def sampling(self, data):
"""Sampling graph for testing.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The data used to be evaluated.
"""
batch_data = {}
head_label = torch.zeros(len(data), self.num_ent)
tail_label = torch.zeros(len(data), self.num_ent)
for idx, triple in enumerate(data):
# from IPython import embed;embed();exit()
head, rel, tail = triple
head_label[idx][self.rt2h_all[(rel, tail)]] = 1.0
tail_label[idx][self.hr2t_all[(head, rel)]] = 1.0
batch_data["positive_sample"] = torch.tensor(data)
batch_data["head_label"] = head_label
batch_data["tail_label"] = tail_label
head, rela, tail = np.array(self.triples).transpose()
graph, rela, norm = self.sampler.build_graph(self.num_ent, (head, rela, tail), -1)
batch_data["graph"] = graph
batch_data["rela"] = rela
batch_data["norm"] = norm
batch_data["entity"] = torch.arange(0, self.num_ent, dtype=torch.long).view(-1,1)
return batch_data
def get_sampling_keys(self):
return ["positive_sample", "head_label", "tail_label",\
"graph", "rela", "norm", "entity"]
class CompGCNTestSampler(object):
"""Sampling graph for testing.
Attributes:
sampler: The function of training sampler.
hr2t_all: Record the tail corresponding to the same head and relation.
rt2h_all: Record the head corresponding to the same tail and relation.
num_ent: The count of entities.
triples: The training triples.
"""
def __init__(self, sampler):
self.sampler = sampler
self.hr2t_all = ddict(set)
self.rt2h_all = ddict(set)
self.get_hr2t_rt2h_from_all()
self.num_ent = sampler.args.num_ent
self.triples = sampler.t_triples
def get_hr2t_rt2h_from_all(self):
"""Get the set of hr2t and rt2h from all datasets(train, valid, and test), the data type is tensor.
Update:
self.hr2t_all: The set of hr2t.
self.rt2h_all: The set of rt2h.
"""
self.all_true_triples = self.sampler.get_all_true_triples()
for h, r, t in self.all_true_triples:
self.hr2t_all[(h, r)].add(t)
self.rt2h_all[(r, t)].add(h)
for h, r in self.hr2t_all:
self.hr2t_all[(h, r)] = torch.tensor(list(self.hr2t_all[(h, r)]))
for r, t in self.rt2h_all:
self.rt2h_all[(r, t)] = torch.tensor(list(self.rt2h_all[(r, t)]))
def sampling(self, data):
"""Sampling graph for testing.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The data used to be evaluated.
"""
batch_data = {}
head_label = torch.zeros(len(data), self.num_ent)
tail_label = torch.zeros(len(data), self.num_ent)
for idx, triple in enumerate(data):
# from IPython import embed;embed();exit()
head, rel, tail = triple
head_label[idx][self.rt2h_all[(rel, tail)]] = 1.0
tail_label[idx][self.hr2t_all[(head, rel)]] = 1.0
batch_data["positive_sample"] = torch.tensor(data)
batch_data["head_label"] = head_label
batch_data["tail_label"] = tail_label
graph, relation, norm = \
self.sampler.build_graph(self.num_ent, np.array(self.triples).transpose(), -0.5)
batch_data["graph"] = graph
batch_data["rela"] = relation
batch_data["norm"] = norm
batch_data["entity"] = torch.arange(0, self.num_ent, dtype=torch.long).view(-1,1)
return batch_data
def get_sampling_keys(self):
return ["positive_sample", "head_label", "tail_label",\
"graph", "rela", "norm", "entity"]
class SEGNNTrainProcess(RevSampler):
def __init__(self, args):
super().__init__(args)
self.args = args
self.use_weight = self.args.use_weight
#Parameters when constructing graph
self.src_list = []
self.dst_list = []
self.rel_list = []
self.hr2eid = ddict(list)
self.rt2eid = ddict(list)
self.ent_head = []
self.ent_tail = []
self.rel = []
self.query = []
self.label = []
self.rm_edges = []
self.set_scaling_weight = []
self.hr2t_train_1 = ddict(set)
self.ht2r_train_1 = ddict(set)
self.rt2h_train_1 = ddict(set)
self.get_h2rt_t2hr_from_train()
self.construct_kg()
self.get_sampling()
def get_h2rt_t2hr_from_train(self):
for h, r, t in self.train_triples:
if r <= self.args.num_rel:
self.ent_head.append(h)
self.rel.append(r)
self.ent_tail.append(t)
self.hr2t_train_1[(h, r)].add(t)
self.rt2h_train_1[(r, t)].add(h)
for h, r in self.hr2t_train:
self.hr2t_train_1[(h, r)] = np.array(list(self.hr2t_train[(h, r)]))
for r, t in self.rt2h_train:
self.rt2h_train_1[(r, t)] = np.array(list(self.rt2h_train[(r, t)]))
def __len__(self):
return len(self.label)
def __getitem__(self, item):
h, r, t = self.query[item]
label = self.get_onehot_label(self.label[item])
rm_edges = torch.tensor(self.rm_edges[item], dtype=torch.int64)
rm_num = math.ceil(rm_edges.shape[0] * self.args.rm_rate)
rm_inds = torch.randperm(rm_edges.shape[0])[:rm_num]
rm_edges = rm_edges[rm_inds]
return (h, r, t), label, rm_edges
def get_onehot_label(self, label):
onehot_label = torch.zeros(self.args.num_ent)
onehot_label[label] = 1
if self.args.label_smooth != 0.0:
onehot_label = (1.0 - self.args.label_smooth) * onehot_label + (1.0 / self.args.num_ent)
return onehot_label
def get_sampling(self):
for k, v in self.hr2t_train_1.items():
self.query.append((k[0], k[1], -1))
self.label.append(list(v))
self.rm_edges.append(self.hr2eid[k])
for k, v in self.rt2h_train_1.items():
self.query.append((k[1], k[0] + self.args.num_rel, -1))
self.label.append(list(v))
self.rm_edges.append(self.rt2eid[k])
def construct_kg(self, directed=False):
"""
construct kg.
:param directed: whether add inverse version for each edge, to make a undirected graph.
False when training SE-GNN model, True for comuting SE metrics.
:return:
"""
# eid: record the edge id of queries, for randomly removing some edges when training
eid = 0
for h, t, r in zip(self.ent_head, self.ent_tail, self.rel):
if directed:
self.src_list.extend([h])
self.dst_list.extend([t])
self.rel_list.extend([r])
self.hr2eid[(h, r)].extend([eid])
self.rt2eid[(r, t)].extend([eid])
eid += 1
else:
# include the inverse edges
# inverse rel id: original id + rel num
self.src_list.extend([h, t])
self.dst_list.extend([t, h])
self.rel_list.extend([r, r + self.args.num_rel])
self.hr2eid[(h, r)].extend([eid, eid + 1])
self.rt2eid[(r, t)].extend([eid, eid + 1])
eid += 2
self.src_list, self.dst_list,self.rel_list = torch.tensor(self.src_list), torch.tensor(self.dst_list), torch.tensor(self.rel_list)
class SEGNNTrainSampler(object):
def __init__(self, args):
self.args = args
self.get_train_1 = SEGNNTrainProcess(args)
self.get_valid_1 = SEGNNTrainProcess(args).get_valid()
self.get_test_1 = SEGNNTrainProcess(args).get_test()
def get_train(self):
return self.get_train_1
def get_valid(self):
return self.get_valid_1
def get_test(self):
return self.get_test_1
def sampling(self, data):
src = [d[0][0] for d in data]
rel = [d[0][1] for d in data]
dst = [d[0][2] for d in data]
label = [d[1] for d in data] # list of list
rm_edges = [d[2] for d in data]
src = torch.tensor(src, dtype=torch.int64)
rel = torch.tensor(rel, dtype=torch.int64)
dst = torch.tensor(dst, dtype=torch.int64)
label = torch.stack(label, dim=0)
rm_edges = torch.cat(rm_edges, dim=0)
return (src, rel, dst), label, rm_edges
class SEGNNTestSampler(Dataset):
def __init__(self, sampler):
super().__init__()
self.sampler = sampler
#Parameters when constructing graph
self.hr2t_all = ddict(set)
self.rt2h_all = ddict(set)
self.get_hr2t_rt2h_from_all()
def get_hr2t_rt2h_from_all(self):
"""Get the set of hr2t and rt2h from all datasets(train, valid, and test), the data type is tensor.
Update:
self.hr2t_all: The set of hr2t.
self.rt2h_all: The set of rt2h.
"""
for h, r, t in self.sampler.get_train_1.all_true_triples:
self.hr2t_all[(h, r)].add(t)
# self.rt2h_all[(r, t)].add(h)
for h, r in self.hr2t_all:
self.hr2t_all[(h, r)] = torch.tensor(list(self.hr2t_all[(h, r)]))
# for r, t in self.rt2h_all:
# self.rt2h_all[(r, t)] = torch.tensor(list(self.rt2h_all[(r, t)]))
def sampling(self, data):
"""Sampling triples and recording positive triples for testing.
Args:
data: The triples used to be sampled.
Returns:
batch_data: The data used to be evaluated.
"""
batch_data = {}
head_label = torch.zeros(len(data), self.sampler.args.num_ent)
tail_label = torch.zeros(len(data), self.sampler.args.num_ent)
filter_head = torch.zeros(len(data), self.sampler.args.num_ent)
filter_tail = torch.zeros(len(data), self.sampler.args.num_ent)
for idx, triple in enumerate(data):
head, rel, tail = triple
filter_tail[idx][self.hr2t_all[(head, rel)]] = -float('inf')
filter_tail[idx][tail] = 0
tail_label[idx][self.hr2t_all[(head, rel)]] = 1.0
batch_data["positive_sample"] = torch.tensor(data)
batch_data["filter_tail"] = filter_tail
batch_data["tail_label"] = tail_label
return batch_data
def get_sampling_keys(self):
return ["positive_sample", "filter_tail", "tail_label"]
'''继承torch.Dataset'''
class KGDataset(Dataset):
def __init__(self, triples):
self.triples = triples
def __len__(self):
return len(self.triples)
def __getitem__(self, idx):
return self.triples[idx] | 46,126 | 34.757364 | 278 | py |
NeuralKG | NeuralKG-main/src/neuralkg/data/RuleDataLoader.py | import random
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import os
from collections import defaultdict as ddict
from IPython import embed
class RuleDataset(Dataset):
def __init__(self, args):
self.args = args
self.rule_p, self.rule_q, self.rule_r, self.confidences, self.tripleNum = [], [], [], [], []
with open(os.path.join(args.data_path, 'groudings.txt')) as f:
for line in f.readlines():
token = line.strip().split('\t')
for i in range(len(token)):
token[i] = token[i].strip('(').strip(')')
iUnseenPos = int(token[0])
self.tripleNum.append(iUnseenPos)
iFstHead = int(token[1])
iFstTail = int(token[3])
iFstRelation = int(token[2])
self.rule_p.append([iFstHead, iFstRelation, iFstTail])
iSndHead = int(token[4])
iSndTail = int(token[6])
iSndRelation = int(token[5])
self.rule_q.append([iSndHead, iSndRelation, iSndTail])
if len(token) == 8:
confidence = float(token[7])
self.rule_r.append([0, 0, 0])
else:
confidence = float(token[10])
iTrdHead = int(token[7])
iTrdTail = int(token[9])
iTrdRelation = int(token[8])
self.rule_r.append([iTrdHead, iTrdRelation, iTrdTail])
self.confidences.append(confidence)
self.len = len(self.confidences)
self.rule_p = torch.tensor(self.rule_p).to(self.args.gpu)
self.rule_q = torch.tensor(self.rule_q).to(self.args.gpu)
self.rule_r = torch.tensor(self.rule_r).to(self.args.gpu)
self.confidences = torch.tensor(self.confidences).to(self.args.gpu)
self.tripleNum = torch.tensor(self.tripleNum).to(self.args.gpu)
def __len__(self):
return self.len
def __getitem__(self, idx):
return (self.rule_p[idx], self.rule_q[idx], self.rule_r[idx]), self.confidences[idx], self.tripleNum[idx]
class RuleDataLoader(DataLoader):
def __init__(self, args):
dataset = RuleDataset(args)
super(RuleDataLoader, self).__init__(
dataset=dataset,
batch_size=int(dataset.__len__()/args.num_batches),
shuffle=args.shuffle) | 2,474 | 37.671875 | 113 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/GNNModel/SEGNN.py | import torch
import torch.nn as nn
import dgl
import dgl.function as fn
from neuralkg import utils
from neuralkg.utils.tools import get_param
from neuralkg.model import ConvE
class SEGNN(nn.Module):
def __init__(self, args):
super(SEGNN, self).__init__()
self.device = torch.device("cuda:0")
self.args = args #得到的全部配置参数
self.dataset = self.args.dataset_name #数据集的名称 WN18RR
self.n_ent = self.args.num_ent #WN18RR数据集实体数量 40943
self.n_rel = self.args.num_rel #关系数量 11
self.emb_dim = self.args.emb_dim
# entity embedding
self.ent_emb = get_param(self.n_ent, self.emb_dim) #初始化实体的embedding
# gnn layer
self.kg_n_layer = self.args.kg_layer #1
# relation SE layer
self.edge_layers = nn.ModuleList([EdgeLayer(self.args) for _ in range(self.kg_n_layer)])
# entity SE layer
self.node_layers = nn.ModuleList([NodeLayer(self.args) for _ in range(self.kg_n_layer)])
# triple SE layer
self.comp_layers = nn.ModuleList([CompLayer(self.args) for _ in range(self.kg_n_layer)])
# relation embedding for aggregation
self.rel_embs = nn.ParameterList([get_param(self.n_rel * 2, self.emb_dim) for _ in range(self.kg_n_layer)])
#parameterList()就是一种和列表、元组之类一样的一种新的数据格式,用于保存神经网络权重及参数。
# relation embedding for prediction
if self.args.pred_rel_w: #true
self.rel_w = get_param(self.emb_dim * self.kg_n_layer, self.emb_dim).to(self.device)
else:
self.pred_rel_emb = get_param(self.n_rel * 2, self.emb_dim)
self.predictor = ConvE(self.args) #(200, 250, 7)
self.ent_drop = nn.Dropout(self.args.ent_drop) #0.2
self.rel_drop = nn.Dropout(self.args.rel_drop) #0
self.act = nn.Tanh()
def forward(self, h_id, r_id, kg):
"""
matching computation between query (h, r) and answer t.
:param h_id: head entity id, (bs, )
:param r_id: relation id, (bs, )
:param kg: aggregation graph
:return: matching score, (bs, n_ent)
"""
# aggregate embedding
kg = kg.to(self.device)
ent_emb, rel_emb = self.aggragate_emb(kg)
head = ent_emb[h_id]
rel = rel_emb[r_id]
# (bs, n_ent)
score = self.predictor.score_func(head, rel, ent_emb) #[256, 40943]
return score
def aggragate_emb(self, kg):
"""
aggregate embedding.
:param kg:
:return:
"""
ent_emb = self.ent_emb
rel_emb_list = []
for edge_layer, node_layer, comp_layer, rel_emb in zip(self.edge_layers, self.node_layers, self.comp_layers, self.rel_embs):
ent_emb, rel_emb = self.ent_drop(ent_emb), self.rel_drop(rel_emb)
ent_emb = ent_emb.to(self.device)
rel_emb = rel_emb.to(self.device)
edge_ent_emb = edge_layer(kg, ent_emb, rel_emb)
node_ent_emb = node_layer(kg, ent_emb)
comp_ent_emb = comp_layer(kg, ent_emb, rel_emb)
ent_emb = ent_emb + edge_ent_emb + node_ent_emb + comp_ent_emb
rel_emb_list.append(rel_emb)
if self.args.pred_rel_w:
pred_rel_emb = torch.cat(rel_emb_list, dim=1).to(self.device)
pred_rel_emb = pred_rel_emb.mm(self.rel_w)
else:
pred_rel_emb = self.pred_rel_emb
return ent_emb, pred_rel_emb
class CompLayer(nn.Module):
def __init__(self, args):
super(CompLayer, self).__init__()
self.device = torch.device("cuda:0")
self.args = args
self.dataset = self.args.dataset_name
self.n_ent = self.args.num_ent
self.n_rel = self.args.num_rel
self.emb_dim = self.args.emb_dim
self.comp_op = self.args.comp_op #'mul'
assert self.comp_op in ['add', 'mul']
self.neigh_w = get_param(self.emb_dim, self.emb_dim).to(self.device)
self.act = nn.Tanh()
if self.args.bn:
self.bn = torch.nn.BatchNorm1d(self.emb_dim).to(self.device)
else:
self.bn = None
def forward(self, kg, ent_emb, rel_emb):
assert kg.number_of_nodes() == ent_emb.shape[0]
assert rel_emb.shape[0] == 2 * self.n_rel
ent_emb = ent_emb.to(self.device)
rel_emb = rel_emb.to(self.device)
kg = kg.to(self.device)
with kg.local_scope():
kg.ndata['emb'] = ent_emb
rel_id = kg.edata['rel_id']
kg.edata['emb'] = rel_emb[rel_id]
# neihgbor entity and relation composition
if self.args.comp_op == 'add':
kg.apply_edges(fn.u_add_e('emb', 'emb', 'comp_emb'))
elif self.args.comp_op == 'mul':
kg.apply_edges(fn.u_mul_e('emb', 'emb', 'comp_emb'))
else:
raise NotImplementedError
# attention
kg.apply_edges(fn.e_dot_v('comp_emb', 'emb', 'norm')) # (n_edge, 1)
kg.edata['norm'] = dgl.ops.edge_softmax(kg, kg.edata['norm'])
# agg
kg.edata['comp_emb'] = kg.edata['comp_emb'] * kg.edata['norm']
kg.update_all(fn.copy_e('comp_emb', 'm'), fn.sum('m', 'neigh'))
neigh_ent_emb = kg.ndata['neigh']
neigh_ent_emb = neigh_ent_emb.mm(self.neigh_w)
if callable(self.bn):
neigh_ent_emb = self.bn(neigh_ent_emb)
neigh_ent_emb = self.act(neigh_ent_emb)
return neigh_ent_emb
class NodeLayer(nn.Module):
def __init__(self, args):
super(NodeLayer, self).__init__()
self.device = torch.device("cuda:0")
self.args = args
self.dataset = self.args.dataset_name
self.n_ent = self.args.num_ent
self.n_rel = self.args.num_rel
self.emb_dim = self.args.emb_dim
self.neigh_w = get_param(self.emb_dim, self.emb_dim).to(self.device)
self.act = nn.Tanh()
if self.args.bn:
self.bn = torch.nn.BatchNorm1d(self.emb_dim).to(self.device)
else:
self.bn = None
def forward(self, kg, ent_emb):
assert kg.number_of_nodes() == ent_emb.shape[0]
kg = kg.to(self.device)
ent_emb = ent_emb.to(self.device)
with kg.local_scope():
kg.ndata['emb'] = ent_emb
# attention
kg.apply_edges(fn.u_dot_v('emb', 'emb', 'norm')) # (n_edge, 1)
kg.edata['norm'] = dgl.ops.edge_softmax(kg, kg.edata['norm'])
# agg
kg.update_all(fn.u_mul_e('emb', 'norm', 'm'), fn.sum('m', 'neigh'))
neigh_ent_emb = kg.ndata['neigh']
neigh_ent_emb = neigh_ent_emb.mm(self.neigh_w)
if callable(self.bn):
neigh_ent_emb = self.bn(neigh_ent_emb)
neigh_ent_emb = self.act(neigh_ent_emb)
return neigh_ent_emb
class EdgeLayer(nn.Module):
def __init__(self, args):
super(EdgeLayer, self).__init__()
self.device = torch.device("cuda:0")
self.args = args
self.dataset = self.args.dataset_name
self.n_ent = self.args.num_ent
self.n_rel = self.args.num_rel
self.emb_dim = self.args.emb_dim
self.neigh_w = utils.get_param(self.emb_dim, self.emb_dim).to(self.device)
self.act = nn.Tanh()
if self.args.bn: # True
self.bn = torch.nn.BatchNorm1d(self.emb_dim).to(self.device)
else:
self.bn = None
def forward(self, kg, ent_emb, rel_emb):
assert kg.number_of_nodes() == ent_emb.shape[0]
assert rel_emb.shape[0] == 2 * self.n_rel
kg = kg.to(self.device)
ent_emb = ent_emb.to(self.device)
rel_emb = rel_emb.to(self.device)
with kg.local_scope():
kg.ndata['emb'] = ent_emb
rel_id = kg.edata['rel_id']
kg.edata['emb'] = rel_emb[rel_id]
# attention
kg.apply_edges(fn.e_dot_v('emb', 'emb', 'norm')) # (n_edge, 1)
kg.edata['norm'] = dgl.ops.edge_softmax(kg, kg.edata['norm'])
# agg
kg.edata['emb'] = kg.edata['emb'] * kg.edata['norm']
kg.update_all(fn.copy_e('emb', 'm'), fn.sum('m', 'neigh'))
neigh_ent_emb = kg.ndata['neigh']
neigh_ent_emb = neigh_ent_emb.mm(self.neigh_w)
if callable(self.bn):
neigh_ent_emb = self.bn(neigh_ent_emb)
neigh_ent_emb = self.act(neigh_ent_emb)
return neigh_ent_emb
| 8,520 | 35.105932 | 132 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/GNNModel/CompGCN.py | import torch
from torch import nn
import dgl
import dgl.function as fn
import torch.nn.functional as F
from neuralkg.model import ConvE
class CompGCN(nn.Module):
"""`Composition-based multi-relational graph convolutional networks`_ (CompGCN),
which jointly embeds both nodes and relations in a relational graph.
Attributes:
args: Model configuration parameters.
.. _Composition-based multi-relational graph convolutional networks:
https://arxiv.org/pdf/1911.03082.pdf
"""
def __init__(self, args):
super(CompGCN, self).__init__()
self.args = args
self.ent_emb = None
self.rel_emb = None
self.GraphCov = None
self.init_model()
def init_model(self):
"""Initialize the CompGCN model and embeddings
Args:
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
GraphCov: The comp graph convolution layers.
conv1: The convolution layer.
fc: The full connection layer.
bn0, bn1, bn2: The batch Normalization layer.
inp_drop, hid_drop, feg_drop: The dropout layer.
"""
#------------------------------CompGCN--------------------------------------------------------------------
self.ent_emb = nn.Parameter(torch.Tensor(self.args.num_ent, self.args.emb_dim))
self.rel_emb = nn.Parameter(torch.Tensor(self.args.num_rel, self.args.emb_dim))
nn.init.xavier_normal_(self.ent_emb, gain=nn.init.calculate_gain('relu'))
nn.init.xavier_normal_(self.rel_emb, gain=nn.init.calculate_gain('relu'))
self.GraphCov = CompGCNCov(self.args.emb_dim, self.args.emb_dim * 2, torch.tanh, \
bias = 'False', drop_rate = 0.1, opn = self.args.opn)
self.bias = nn.Parameter(torch.zeros(self.args.num_ent))
self.drop = nn.Dropout(0.3)
#-----------------------------ConvE-----------------------------------------------------------------------
self.emb_ent = torch.nn.Embedding(self.args.num_ent, self.args.emb_dim*2)
self.inp_drop = torch.nn.Dropout(self.args.inp_drop)
self.hid_drop = torch.nn.Dropout(self.args.hid_drop)
self.feg_drop = torch.nn.Dropout2d(self.args.fet_drop)
self.conv1 = torch.nn.Conv2d(1, 200, (7, 7), 1, 0, bias=False)
self.bn0 = torch.nn.BatchNorm2d(1)
self.bn1 = torch.nn.BatchNorm2d(200)
self.bn2 = torch.nn.BatchNorm1d(200)
self.register_parameter('b', torch.nn.Parameter(torch.zeros(self.args.num_ent)))
self.fc = torch.nn.Linear(39200, self.args.out_dim)
def forward(self, graph, relation, norm, triples):
"""The functions used in the training phase
Args:
graph: The knowledge graph recorded in dgl.graph()
relation: The relation id sampled in triples
norm: The edge norm in graph
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
Returns:
score: The score of triples.
"""
head, rela = triples[:,0], triples[:, 1]
x, r = self.ent_emb, self.rel_emb # embedding of relations
x, r = self.GraphCov(graph, x, r, relation, norm)
x = self.drop(x) # embeddings of entities [num_ent, dim]
head_emb = torch.index_select(x, 0, head) # filter out embeddings of subjects in this batch
#head_in_emb = head_emb.view(-1, 1, 10, 20)
rela_emb = torch.index_select(r, 0, rela) # filter out embeddings of relations in this batch
#rela_in_emb = rela_emb.view(-1, 1, 10, 20)
if self.args.decoder_model.lower() == 'conve':
# score = ConvE.score_func(self, head_in_emb, rela_in_emb, x)
score = self.ConvE(head_emb, rela_emb, x)
elif self.args.decoder_model.lower() == 'distmult':
score = self.DistMult(head_emb, rela_emb)
else:
raise ValueError("please choose decoder (DistMult/ConvE)")
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch['positive_sample']
graph = batch['graph']
relation = batch['rela']
norm = batch['norm']
head, rela = triples[:,0], triples[:, 1]
x, r = self.ent_emb, self.rel_emb # embedding of relations
x, r = self.GraphCov(graph, x, r, relation, norm)
x = self.drop(x) # embeddings of entities [num_ent, dim]
head_emb = torch.index_select(x, 0, head) # filter out embeddings of subjects in this batch
#head_in_emb = head_emb.view(-1, 1, 10, 20)
rela_emb = torch.index_select(r, 0, rela) # filter out embeddings of relations in this batch
#rela_in_emb = rela_emb.view(-1, 1, 10, 20)
if self.args.decoder_model.lower() == 'conve':
# score = ConvE.score_func(self, head_in_emb, rela_in_emb, x)
score = self.ConvE(head_emb, rela_emb, x)
elif self.args.decoder_model.lower() == 'distmult':
score = self.DistMult(head_emb, rela_emb)
else:
raise ValueError("please choose decoder (DistMult/ConvE)")
return score
def DistMult(self, head_emb, rela_emb):
"""Calculating the score of triples with DistMult model."""
obj_emb = head_emb * rela_emb # [batch_size, emb_dim]
x = torch.mm(obj_emb, self.emb_ent.weight.transpose(1, 0)) # [batch_size, ent_num]
x += self.bias.expand_as(x)
score = torch.sigmoid(x)
return score
def concat(self, ent_embed, rel_embed):
ent_embed = ent_embed.view(-1, 1, 200)
rel_embed = rel_embed.view(-1, 1, 200)
stack_input = torch.cat([ent_embed, rel_embed], 1) # [batch_size, 2, embed_dim]
stack_input = stack_input.reshape(-1, 1, 2 * 10, 20) # reshape to 2D [batch, 1, 2*k_h, k_w]
return stack_input
def ConvE(self, sub_emb, rel_emb, all_ent):
"""Calculating the score of triples with ConvE model."""
stack_input = self.concat(sub_emb, rel_emb) # [batch_size, 1, 2*k_h, k_w]
x = self.bn0(stack_input)
x = self.conv1(x) # [batch_size, num_filt, flat_sz_h, flat_sz_w]
x = self.bn1(x)
x = F.relu(x)
x = self.feg_drop(x)
x = x.view(x.shape[0], -1) # [batch_size, flat_sz]
x = self.fc(x) # [batch_size, embed_dim]
x = self.hid_drop(x)
x = self.bn2(x)
x = F.relu(x)
x = torch.mm(x, all_ent.transpose(1, 0)) # [batch_size, ent_num]
x += self.bias.expand_as(x)
score = torch.sigmoid(x)
return score
class CompGCNCov(nn.Module):
""" The comp graph convolution layers, similar to https://github.com/malllabiisc/CompGCN"""
def __init__(self, in_channels, out_channels, act=lambda x: x, bias=True, drop_rate=0., opn='corr'):
super(CompGCNCov, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.act = act # activation function
self.device = None
self.rel = None
self.opn = opn
# relation-type specific parameter
self.in_w = self.get_param([in_channels, out_channels])
self.out_w = self.get_param([in_channels, out_channels])
self.loop_w = self.get_param([in_channels, out_channels])
self.w_rel = self.get_param([in_channels, out_channels]) # transform embedding of relations to next layer
self.loop_rel = self.get_param([1, in_channels]) # self-loop embedding
self.drop = nn.Dropout(drop_rate)
self.bn = torch.nn.BatchNorm1d(out_channels)
self.bias = nn.Parameter(torch.zeros(out_channels)) if bias else None
self.rel_wt = None
def get_param(self, shape):
param = nn.Parameter(torch.Tensor(*shape))
nn.init.xavier_normal_(param, gain=nn.init.calculate_gain('relu'))
return param
def message_func(self, edges: dgl.udf.EdgeBatch):
edge_type = edges.data['type'] # [E, 1]
edge_num = edge_type.shape[0]
edge_data = self.comp(edges.src['h'], self.rel[edge_type]) # [E, in_channel]
# msg = torch.bmm(edge_data.unsqueeze(1),
# self.w[edge_dir.squeeze()]).squeeze() # [E, 1, in_c] @ [E, in_c, out_c]
# msg = torch.bmm(edge_data.unsqueeze(1),
# self.w.index_select(0, edge_dir.squeeze())).squeeze() # [E, 1, in_c] @ [E, in_c, out_c]
# first half edges are all in-directions, last half edges are out-directions.
msg = torch.cat([torch.matmul(edge_data[:edge_num // 2, :], self.in_w),
torch.matmul(edge_data[edge_num // 2:, :], self.out_w)])
msg = msg * edges.data['norm'].reshape(-1, 1) # [E, D] * [E, 1]
return {'msg': msg}
def reduce_func(self, nodes: dgl.udf.NodeBatch):
return {'h': self.drop(nodes.data['h']) / 3}
def comp(self, h, edge_data):
def com_mult(a, b):
r1, i1 = a.real, a.imag
r2, i2 = b.real, b.imag
real = r1 * r2 - i1 * i2
imag = r1 * i2 + i1 * r2
return torch.complex(real, imag)
def conj(a):
a.imag = -a.imag
return a
def ccorr(a, b):
return torch.fft.irfft(com_mult(conj(torch.fft.rfft(a)), torch.fft.rfft(b)), a.shape[-1])
if self.opn == 'mult':
return h * edge_data
elif self.opn == 'sub':
return h - edge_data
elif self.opn == 'corr':
return ccorr(h, edge_data.expand_as(h))
else:
raise KeyError(f'composition operator {self.opn} not recognized.')
def forward(self, g: dgl.graph, x, rel_repr, edge_type, edge_norm):
self.device = x.device
g = g.local_var()
g.ndata['h'] = x
g.edata['type'] = edge_type
g.edata['norm'] = edge_norm
if self.rel_wt is None:
self.rel = rel_repr
else:
self.rel = torch.mm(self.rel_wt, rel_repr) # [num_rel*2, num_base] @ [num_base, in_c]
g.update_all(self.message_func, fn.sum(msg='msg', out='h'), self.reduce_func)
x = g.ndata.pop('h') + torch.mm(self.comp(x, self.loop_rel), self.loop_w) / 3
if self.bias is not None:
x = x + self.bias
x = self.bn(x)
return self.act(x), torch.matmul(self.rel, self.w_rel) | 10,731 | 41.251969 | 114 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/GNNModel/RGCN.py | import dgl
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.nn.pytorch import RelGraphConv
from neuralkg.model import DistMult
class RGCN(nn.Module):
"""`Modeling Relational Data with Graph Convolutional Networks`_ (RGCN), which use GCN framework to model relation data.
Attributes:
args: Model configuration parameters.
.. _Modeling Relational Data with Graph Convolutional Networks: https://arxiv.org/pdf/1703.06103.pdf
"""
def __init__(self, args):
super(RGCN, self).__init__()
self.args = args
self.ent_emb = None
self.rel_emb = None
self.RGCN = None
self.Loss_emb = None
self.build_model()
def build_model(self):
"""Initialize the RGCN model and embeddings
Args:
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
RGCN: the relation graph convolution model.
"""
self.ent_emb = nn.Embedding(self.args.num_ent,self.args.emb_dim)
self.rel_emb = nn.Parameter(torch.Tensor(self.args.num_rel, self.args.emb_dim))
nn.init.xavier_uniform_(self.rel_emb, gain=nn.init.calculate_gain('relu'))
self.RGCN = nn.ModuleList()
for idx in range(self.args.num_layers):
RGCN_idx = self.build_hidden_layer(idx)
self.RGCN.append(RGCN_idx)
def forward(self, graph, ent, rel, norm, triples, mode='single'):
"""The functions used in the training and testing phase
Args:
graph: The knowledge graph recorded in dgl.graph()
ent: The entitiy ids sampled in triples
rel: The relation ids sampled in triples
norm: The edge norm in graph
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
embedding = self.ent_emb(ent.squeeze())
for layer in self.RGCN:
embedding = layer(graph, embedding, rel, norm)
self.Loss_emb = embedding
head_emb, rela_emb, tail_emb = self.tri2emb(embedding, triples, mode)
score = DistMult.score_func(self,head_emb, rela_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch['positive_sample']
graph = batch['graph']
ent = batch['entity']
rel = batch['rela']
norm = batch['norm']
embedding = self.ent_emb(ent.squeeze())
for layer in self.RGCN:
embedding = layer(graph, embedding, rel, norm)
self.Loss_emb = embedding
head_emb, rela_emb, tail_emb = self.tri2emb(embedding, triples, mode)
score = DistMult.score_func(self,head_emb, rela_emb, tail_emb, mode)
return score
def tri2emb(self, embedding, triples, mode="single"): #TODO:和XTransE合并
"""Get embedding of triples.
This function get the embeddings of head, relation, and tail
respectively. each embedding has three dimensions.
Args:
embedding(tensor): This embedding save the entity embeddings.
triples (tensor): This tensor save triples id, which dimension is
[triples number, 3].
mode (str, optional): This arg indicates that the negative entity
will replace the head or tail entity. when it is 'single', it
means that entity will not be replaced. Defaults to 'single'.
Returns:
head_emb: Head entity embedding.
rela_emb: Relation embedding.
tail_emb: Tail entity embedding.
"""
rela_emb = self.rel_emb[triples[:, 1]].unsqueeze(1) # [bs, 1, dim]
head_emb = embedding[triples[:, 0]].unsqueeze(1) # [bs, 1, dim]
tail_emb = embedding[triples[:, 2]].unsqueeze(1) # [bs, 1, dim]
if mode == "head-batch" or mode == "head_predict":
head_emb = embedding.unsqueeze(0) # [1, num_ent, dim]
elif mode == "tail-batch" or mode == "tail_predict":
tail_emb = embedding.unsqueeze(0) # [1, num_ent, dim]
return head_emb, rela_emb, tail_emb
def build_hidden_layer(self, idx):
"""The functions used to initialize the RGCN model
Args:
idx: it`s used to identify rgcn layers. The last rgcn layer should use
relu as activation function.
Returns:
the relation graph convolution layer
"""
act = F.relu if idx < self.args.num_layers - 1 else None
return RelGraphConv(self.args.emb_dim, self.args.emb_dim, self.args.num_rel, "bdd",
num_bases=100, activation=act, self_loop=True,dropout=0.2 )
| 5,155 | 35.309859 | 124 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/GNNModel/KBAT.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import time
import os
class KBAT(nn.Module):
"""`Learning Attention-based Embeddings for Relation Prediction in Knowledge Graphs`_ (KBAT),
which introduces the attention to aggregate the neighbor node representation.
Attributes:
args: Model configuration parameters.
.. _Learning Attention-based Embeddings for Relation Prediction in Knowledge Graphs:
https://arxiv.org/pdf/1906.01195.pdf
"""
def __init__(self, args):
super(KBAT,self).__init__()
self.args = args
self.entity_embeddings = None
self.relation_embeddings = None
self.init_GAT_emb()
self.init_ConvKB_emb()
def init_GAT_emb(self):
"""Initialize the GAT model and embeddings
Args:
ent_emb_out: Entity embedding, shape:[num_ent, emb_dim].
rel_emb_out: Relation_embedding, shape:[num_rel, emb_dim].
entity_embeddings: The final embedding used in ConvKB.
relation_embeddings: The final embedding used in ConvKB.
attentions, out_att: The graph attention layers.
"""
self.num_ent = self.args.num_ent
self.num_rel = self.args.num_rel
self.emb_dim = self.args.emb_dim
self.ent_emb_out = nn.Parameter(torch.randn(self.num_ent,self.emb_dim))
self.rel_emb_out = nn.Parameter(torch.randn(self.num_rel,self.emb_dim))
self.drop = 0.3
self.alpha = 0.2
self.nheads_GAT = 2
self.out_dim = 100
self.entity_embeddings = nn.Parameter(
torch.randn(self.num_ent, self.out_dim * self.nheads_GAT))
self.relation_embeddings = nn.Parameter(
torch.randn(self.num_rel, self.out_dim * self.nheads_GAT))
self.dropout_layer = nn.Dropout(self.drop)
self.attentions = [GraphAttentionLayer(self.num_ent,
self.emb_dim,
self.out_dim,
self.emb_dim,
dropout=self.drop,
alpha=self.alpha,
concat=True)
for _ in range(self.nheads_GAT)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
# W matrix to convert h_input to h_output dimension 变换矩阵
self.W = nn.Parameter(torch.zeros(
size=(self.emb_dim, self.nheads_GAT * self.out_dim)))
nn.init.xavier_uniform_(self.W.data, gain=1.414)
self.out_att = GraphAttentionLayer(self.num_ent,
self.out_dim * self.nheads_GAT,
self.out_dim * self.nheads_GAT,
self.out_dim * self.nheads_GAT,
dropout=self.drop,
alpha=self.alpha,
concat=False
)
self.W_entities = nn.Parameter(torch.zeros(
size=(self.emb_dim, self.out_dim * self.nheads_GAT)))
nn.init.xavier_uniform_(self.W_entities.data, gain=1.414)
def init_ConvKB_emb(self):
"""Initialize the ConvKB model.
Args:
conv_layer: The convolution layer.
dropout: The dropout layer.
ReLU: Relu activation function.
fc_layer: The full connection layer.
"""
self.conv_layer = nn.Conv2d(1, 50, (1,3))
self.dropout = nn.Dropout(0.3)
self.ReLU = nn.ReLU()
self.fc_layer = nn.Linear(10000, 1)
nn.init.xavier_uniform_(self.fc_layer.weight, gain=1.414)
nn.init.xavier_uniform_(self.conv_layer.weight, gain=1.414)
def forward(self, triples, mode, adj_matrix=None, n_hop=None):
"""The functions used in the training and testing phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
mode: The mode indicates that the model will be used, when it
is 'GAT', it means graph attetion model, when it is 'ConvKB',
it means ConvKB model.
Returns:
score: The score of triples.
"""
if mode == 'GAT': # gat
score = self.forward_GAT(triples, adj_matrix, n_hop)
else:
score = self.forward_Con(triples, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
score = self.forward_Con(triples, mode)
return score
def forward_Con(self, triples, mode):
score = None
if mode == 'ConvKB':
head_emb = self.entity_embeddings[triples[:, 0]].unsqueeze(1)
rela_emb = self.relation_embeddings[triples[:, 1]].unsqueeze(1)
tail_emb = self.entity_embeddings[triples[:, 2]].unsqueeze(1)
score = self.cal_Con_score(head_emb, rela_emb, tail_emb)
elif mode == 'head_predict':
head_emb = self.entity_embeddings.unsqueeze(1) # [1, num_ent, dim]
for triple in triples:
rela_emb = self.relation_embeddings[triple[1]].\
unsqueeze(0).tile(dims=(self.num_ent,1,1))
tail_emb = self.entity_embeddings[triple[2]].\
unsqueeze(0).tile(dims=(self.num_ent,1,1))
s = self.cal_Con_score(head_emb, rela_emb, tail_emb).t()
if score == None:
score = s
else:
score = torch.cat((score, s), dim=0)
elif mode == 'tail_predict':
tail_emb = self.entity_embeddings.unsqueeze(1) # [1, num_ent, dim]
for triple in triples:
head_emb = self.entity_embeddings[triple[0]].\
unsqueeze(0).tile(dims=(self.num_ent,1,1))
rela_emb = self.relation_embeddings[triple[1]].\
unsqueeze(0).tile(dims=(self.num_ent,1,1))
s = self.cal_Con_score(head_emb, rela_emb, tail_emb).t()
if score == None:
score = s
else:
score = torch.cat((score, s), dim=0)
return score
def forward_GAT(self, triples, adj_matrix, n_hop):
edge_list = adj_matrix[0] #边节点
edge_type = adj_matrix[1] #边种类
edge_list_nhop = torch.cat((n_hop[:, 3].unsqueeze(-1),
n_hop[:, 0].unsqueeze(-1)), dim=1).t()
edge_type_nhop = torch.cat([n_hop[:, 1].unsqueeze(-1),
n_hop[:, 2].unsqueeze(-1)], dim=1)
edge_emb = self.rel_emb_out[edge_type]
self.ent_emb_out.data = F.normalize(self.ent_emb_out.data, p=2, dim=1).detach()
edge_embed_nhop = self.rel_emb_out[edge_type_nhop[:, 0]] + \
self.rel_emb_out[edge_type_nhop[:, 1]]
ent_emb_out = torch.cat([att(self.ent_emb_out, edge_list, edge_emb, edge_list_nhop,
edge_embed_nhop) for att in self.attentions], dim=1)
ent_emb_out = self.dropout_layer(ent_emb_out)
rel_emb_out = self.rel_emb_out.mm(self.W)
edge_emb = rel_emb_out[edge_type]
edge_embed_nhop = rel_emb_out[edge_type_nhop[:, 0]] + \
rel_emb_out[edge_type_nhop[:, 1]]
ent_emb_out = F.elu(self.out_att(ent_emb_out, edge_list, edge_emb,
edge_list_nhop, edge_embed_nhop))
mask_indices = torch.unique(triples[:, 2])
mask = torch.zeros(self.ent_emb_out.shape[0]).type_as(self.ent_emb_out)
mask[mask_indices] = 1.0
entities_upgraded = self.ent_emb_out.mm(self.W_entities)
ent_emb_out = entities_upgraded + \
mask.unsqueeze(-1).expand_as(ent_emb_out) * ent_emb_out
ent_emb_out = F.normalize(ent_emb_out, p=2, dim=1)
self.entity_embeddings.data = ent_emb_out.data
self.relation_embeddings.data = rel_emb_out.data
head_emb = ent_emb_out[triples[:, 0]]
rela_emb = rel_emb_out[triples[:, 1]]
tail_emb = ent_emb_out[triples[:, 2]]
return self.cal_GAT_score(head_emb, rela_emb, tail_emb)
def cal_Con_score(self, head_emb, rela_emb, tail_emb):
"""Calculating the score of triples with ConvKB model.
Args:
head_emb: The head entity embedding.
rela_emb: The relation embedding.
tail_emb: The tail entity embedding.
Returns:
score: The score of triples.
"""
conv_input = torch.cat((head_emb, rela_emb, tail_emb), dim=1)
batch_size= conv_input.shape[0]
conv_input = conv_input.transpose(1, 2)
conv_input = conv_input.unsqueeze(1)
out_conv = self.conv_layer(conv_input)
out_conv = self.ReLU(out_conv)
out_conv = self.dropout(out_conv)
out_conv = out_conv.squeeze(-1).view(batch_size, -1)
score = self.fc_layer(out_conv)
return score
def cal_GAT_score(self, head_emb, relation_emb, tail_emb):
"""Calculating the score of triples with TransE model.
Args:
head_emb: The head entity embedding.
rela_emb: The relation embedding.
tail_emb: The tail entity embedding.
Returns:
score: The score of triples.
"""
score = (head_emb + relation_emb) - tail_emb
score = torch.norm(score, p=1, dim=1)
return score
class SpecialSpmmFunctionFinal(torch.autograd.Function):
"""
Special function for only sparse region backpropataion layer, similar to https://arxiv.org/abs/1710.10903
"""
@staticmethod
def forward(ctx, edge, edge_w, N, E, out_features):
a = torch.sparse_coo_tensor(
edge, edge_w, torch.Size([N, N, out_features]))
b = torch.sparse.sum(a, dim=1)
ctx.N = b.shape[0]
ctx.outfeat = b.shape[1]
ctx.E = E
ctx.indices = a._indices()[0, :]
return b.to_dense()
@staticmethod
def backward(ctx, grad_output):
grad_values = None
if ctx.needs_input_grad[1]:
edge_sources = ctx.indices
grad_values = grad_output[edge_sources]
return None, grad_values, None, None, None
class SpecialSpmmFinal(nn.Module):
"""
Special spmm final layer, similar to https://arxiv.org/abs/1710.10903.
"""
def forward(self, edge, edge_w, N, E, out_features):
return SpecialSpmmFunctionFinal.apply(edge, edge_w, N, E, out_features)
class GraphAttentionLayer(nn.Module):
"""
Sparse version GAT layer, similar to https://arxiv.org/abs/1710.10903.
"""
def __init__(self, num_nodes, in_features, out_features, nrela_dim, dropout, alpha, concat=True):
super(GraphAttentionLayer, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.num_nodes = num_nodes
self.alpha = alpha
self.concat = concat
self.nrela_dim = nrela_dim
self.a = nn.Parameter(torch.zeros(
size=(out_features, 2 * in_features + nrela_dim)))
nn.init.xavier_normal_(self.a.data, gain=1.414)
self.a_2 = nn.Parameter(torch.zeros(size=(1, out_features)))
nn.init.xavier_normal_(self.a_2.data, gain=1.414)
self.dropout = nn.Dropout(dropout)
self.leakyrelu = nn.LeakyReLU(self.alpha)
self.special_spmm_final = SpecialSpmmFinal()
def forward(self, input, edge, edge_embed, edge_list_nhop, edge_embed_nhop):
N = input.size()[0]
# Self-attention on the nodes - Shared attention mechanism
edge = torch.cat((edge[:, :], edge_list_nhop[:, :]), dim=1)
edge_embed = torch.cat(
(edge_embed[:, :], edge_embed_nhop[:, :]), dim=0)
edge_h = torch.cat(
(input[edge[0, :], :], input[edge[1, :], :], edge_embed[:, :]), dim=1).t()
# edge_h: (2*in_dim + nrela_dim) x E
edge_m = self.a.mm(edge_h)
# edge_m: D * E
# to be checked later
powers = -self.leakyrelu(self.a_2.mm(edge_m).squeeze())
edge_e = torch.exp(powers).unsqueeze(1)
assert not torch.isnan(edge_e).any()
# edge_e: E
e_rowsum = self.special_spmm_final(
edge, edge_e, N, edge_e.shape[0], 1)
e_rowsum[e_rowsum == 0.0] = 1e-12
e_rowsum = e_rowsum
# e_rowsum: N x 1
edge_e = edge_e.squeeze(1)
edge_e = self.dropout(edge_e)
# edge_e: E
edge_w = (edge_e * edge_m).t()
# edge_w: E * D
h_prime = self.special_spmm_final(
edge, edge_w, N, edge_w.shape[0], self.out_features)
assert not torch.isnan(h_prime).any()
# h_prime: N x out
h_prime = h_prime.div(e_rowsum)
# h_prime: N x out
assert not torch.isnan(h_prime).any()
if self.concat:
# if this layer is not last layer,
return F.elu(h_prime)
else:
# if this layer is last layer,
return h_prime
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')' | 13,971 | 36.258667 | 109 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/GNNModel/XTransE.py | import torch.nn as nn
import torch
from IPython import embed
from neuralkg.model.KGEModel.model import Model
class XTransE(Model):
"""`Explainable Knowledge Graph Embedding for Link Prediction with Lifestyles in e-Commerce`_ (XTransE), which introduces the attention to aggregate the neighbor node representation.
Attributes:
args: Model configuration parameters.
.. _Explainable Knowledge Graph Embedding for Link Prediction with Lifestyles in e-Commerce: https://link.springer.com/content/pdf/10.1007%2F978-981-15-3412-6_8.pdf
"""
def __init__(self, args):
super(XTransE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
Args:
margin: Caculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
"""
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([6.0 / float(self.args.emb_dim).__pow__(0.5)]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, triples, neighbor=None, mask=None, negs=None, mode='single'):
"""Calculating the score of triples.
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
neighbor: The neighbors of tail entities.
mask: The mask of neighbor nodes
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head = triples[:,0]
rela = triples[:,1]
tail = triples[:,2]
if mode == 'tail-batch':
tail = negs.squeeze(1)
norm_emb_ent = nn.functional.normalize(self.ent_emb.weight, dim=1, p=2) # [ent, dim]
norm_emb_rel = nn.functional.normalize(self.rel_emb.weight, dim=1, p=2) # [rel, dim]
neighbor_tail_emb = norm_emb_ent[neighbor[:, :, 1]] # [batch, neighbor, dim]
neighbor_rela_emb = norm_emb_rel[neighbor[:, :, 0]] # [batch, neighbor, dim]
neighbor_head_emb = neighbor_tail_emb - neighbor_rela_emb
rela_emb = norm_emb_rel[rela] # [batch, dim]
tail_emb = norm_emb_ent[tail] # [batch, dim]
head_emb = norm_emb_ent[head]
h_rt_embedding = tail_emb - rela_emb
attention_rt = torch.zeros([self.args.train_bs, 200]).type_as(self.ent_emb.weight)
attention_rt = (neighbor_head_emb * h_rt_embedding.unsqueeze(1)).sum(dim=2) * mask
attention_rt = nn.functional.softmax(attention_rt, dim=1).unsqueeze(2)
head_emb = head_emb + \
torch.bmm(neighbor_head_emb.permute(0,2,1), attention_rt).reshape([-1,self.args.emb_dim])
score = self.margin.item() - torch.norm(head_emb + rela_emb - tail_emb, p=2, dim=1)
return score.unsqueeze(1)
def transe_func(self, head_emb, rela_emb, tail_emb):
"""Calculating the score of triples with TransE model.
Args:
head_emb: The head entity embedding.
rela_emb: The relation embedding.
tail_emb: The tail entity embedding.
Returns:
score: The score of triples.
"""
score = (head_emb + rela_emb) - tail_emb
score = self.margin.item() - torch.norm(score, p=2, dim=-1)
return score
def forward(self, triples, neighbor=None, mask=None, negs=None, mode='single'):
"""The functions used in the training and testing phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
neighbor: The neighbors of tail entities.
mask: The mask of neighbor nodes
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
TransE_score = self.transe_func(head_emb, relation_emb, tail_emb)
XTransE_score = self.score_func(triples, neighbor, mask, negs, mode)
return TransE_score + XTransE_score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.transe_func(head_emb, relation_emb, tail_emb)
return score
| 5,638 | 36.845638 | 248 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/DistMult.py | import torch.nn as nn
import torch
from .model import Model
from IPython import embed
class DistMult(Model):
"""`Embedding Entities and Relations for Learning and Inference in Knowledge Bases`_ (DistMult)
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
.. _Embedding Entities and Relations for Learning and Inference in Knowledge Bases: https://arxiv.org/abs/1412.6575
"""
def __init__(self, args):
super(DistMult, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution."""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`h^{\top} \operatorname{diag}(r) t`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
if mode == 'head-batch':
score = head_emb * (relation_emb * tail_emb)
else:
score = (head_emb * relation_emb) * tail_emb
score = score.sum(dim = -1)
return score
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
| 3,476 | 34.121212 | 120 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/PairRE.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .model import Model
class PairRE(Model):
"""`PairRE: Knowledge Graph Embeddings via Paired Relation Vectors`_ (PairRE), which paired vectors for each relation representation to model complex patterns.
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation embedding, shape:[num_rel, emb_dim * 2].
.. _PairRE: Knowledge Graph Embeddings via Paired Relation Vectors: https://arxiv.org/pdf/2011.03798.pdf
"""
def __init__(self, args):
super(PairRE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
"""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False,
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False,
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
nn.init.uniform_(
tensor=self.ent_emb.weight.data,
a = -self.embedding_range.item(),
b = self.embedding_range.item(),
)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim * 2)
nn.init.uniform_(
tensor=self.rel_emb.weight.data,
a = -self.embedding_range.item(),
b = self.embedding_range.item(),
)
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\gamma - || h \circ r^H - t \circ r^T ||`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
re_head, re_tail = torch.chunk(relation_emb, 2, dim=2)
head = F.normalize(head_emb, 2, -1)
tail = F.normalize(tail_emb, 2, -1)
score = head * re_head - tail * re_tail
return self.margin.item() - torch.norm(score, p=1, dim=2)
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch['positive_sample']
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
| 3,716 | 35.087379 | 163 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/ComplEx.py | import torch.nn as nn
import torch
from .model import Model
from IPython import embed
class ComplEx(Model):
def __init__(self, args):
"""`Complex Embeddings for Simple Link Prediction`_ (ComplEx), which is a simple approach to matrix and tensor factorization for link prediction data that uses vectors with complex values and retains the mathematical definition of the dot product.
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim * 2].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim * 2].
.. _Complex Embeddings for Simple Link Prediction: http://proceedings.mlr.press/v48/trouillon16.pdf
"""
super(ComplEx, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution."""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim * 2)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim * 2)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\operatorname{Re}\left(h^{\top} \operatorname{diag}(r) \overline{t}\right)`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
re_head, im_head = torch.chunk(head_emb, 2, dim=-1)
re_relation, im_relation = torch.chunk(relation_emb, 2, dim=-1)
re_tail, im_tail = torch.chunk(tail_emb, 2, dim=-1)
return torch.sum(
re_head * re_tail * re_relation
+ im_head * im_tail * re_relation
+ re_head * im_tail * im_relation
- im_head * re_tail * im_relation,
-1
)
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score | 3,926 | 37.5 | 255 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/RotatE.py | import torch.nn as nn
import torch
from .model import Model
from IPython import embed
class RotatE(Model):
"""`RotatE: Knowledge Graph Embedding by Relational Rotation in Complex Space`_ (RotatE), which defines each relation as a rotation from the source entity to the target entity in the complex vector space.
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim * 2].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
.. _RotatE: Knowledge Graph Embedding by Relational Rotation in Complex Space: https://openreview.net/forum?id=HkgEQnRqYQ
"""
def __init__(self, args):
super(RotatE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution."""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim * 2)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\gamma - \|h \circ r - t\|`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
pi = 3.14159265358979323846
re_head, im_head = torch.chunk(head_emb, 2, dim=-1)
re_tail, im_tail = torch.chunk(tail_emb, 2, dim=-1)
#Make phases of relations uniformly distributed in [-pi, pi]
phase_relation = relation_emb/(self.embedding_range.item()/pi)
re_relation = torch.cos(phase_relation)
im_relation = torch.sin(phase_relation)
if mode == 'head-batch':
re_score = re_relation * re_tail + im_relation * im_tail
im_score = re_relation * im_tail - im_relation * re_tail
re_score = re_score - re_head
im_score = im_score - im_head
else:
re_score = re_head * re_relation - im_head * im_relation
im_score = re_head * im_relation + im_head * re_relation
re_score = re_score - re_tail
im_score = im_score - im_tail
score = torch.stack([re_score, im_score], dim = 0)
score = score.norm(dim = 0)
score = self.margin.item() - score.sum(dim = -1)
return score
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
| 4,433 | 36.897436 | 208 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/BoxE.py | import torch.nn as nn
import torch
from torch.autograd import Variable
from .model import Model
class BoxE(Model):
"""`A Box Embedding Model for Knowledge Base Completion`_ (BoxE), which represents the bump embedding as translations in the super rectangle space.
Attributes:
args: Model configuration parameters.
.. _A Box Embedding Model for Knowledge Base Completion: https://arxiv.org/pdf/2007.06267.pdf
"""
def __init__(self, args):
super(BoxE, self).__init__(args)
self.args = args
self.arity = None
self.order = None
self.ent_emb = None
self.rel_emb = None
self.init_emb(args)
def init_emb(self,args):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
Args:
arity: The maximum ary of the knowledge graph.
epsilon: Caculate embedding_range.
order: The distance order of score.
margin: Caculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim * 2].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim * arity * 2].
"""
self.arity = 2
self.epsilon = 2.0
self.order = self.args.dis_order
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim*2)
nn.init.uniform_(tensor=self.ent_emb.weight.data[:, :self.args.emb_dim], a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.ent_emb.weight.data[:, self.args.emb_dim:], a=-self.embedding_range.item(), b=self.embedding_range.item())
size_factor = self.arity * 2
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim * size_factor)
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb_raw, relation_emb, tail_emb_raw = self.tri2emb(triples, negs, mode)
head_emb = head_emb_raw[:, :, :self.args.emb_dim] + tail_emb_raw[:, :, self.args.emb_dim:]
tail_emb = tail_emb_raw[:, :, :self.args.emb_dim] + head_emb_raw[:, :, self.args.emb_dim:]
score = self.score_func(head_emb, relation_emb, tail_emb)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb_raw, relation_emb, tail_emb_raw = self.tri2emb(triples, mode=mode)
head_emb = head_emb_raw[:, :, :self.args.emb_dim] + tail_emb_raw[:, :, self.args.emb_dim:]
tail_emb = tail_emb_raw[:, :, :self.args.emb_dim] + head_emb_raw[:, :, self.args.emb_dim:]
score = self.score_func(head_emb, relation_emb, tail_emb)
return score
def score_func(self, head_emb, relation_emb, tail_emb):
"""Calculate the score of the triple embedding.
Args:
head_emb: The embedding of head entity.
relation_emb:The embedding of relation.
tail_emb: The embedding of tail entity.
Returns:
score: The score of triples.
"""
box_bas, box_del = torch.chunk(relation_emb, 2, dim = -1)
box_sec = box_bas + 0.5 * box_del
box_fir = box_bas - 0.5 * box_del
box_low = torch.min(box_fir, box_sec)
box_hig = torch.max(box_fir, box_sec)
head_low, tail_low = torch.chunk(box_low, 2, dim = -1)
head_hig, tail_hig = torch.chunk(box_hig, 2, dim = -1)
head_score = self.calc_score(head_emb, head_low, head_hig, self.order)
tail_score = self.calc_score(tail_emb, tail_low, tail_hig, self.order)
score = self.margin.item() - (head_score + tail_score)
return score
def calc_score(self, ent_emb, box_low, box_hig, order = 2):
"""Calculate the norm of distance.
Args:
ent_emb: The embedding of entity.
box_low: The lower boundaries of the super rectangle.
box_hig: The upper boundaries of the super rectangle.
order: The order of this distance.
Returns:
The norm of distance.
"""
return torch.norm(self.dist(ent_emb, box_low, box_hig), p=order, dim=-1)
def dist(self, ent_emb, lb, ub):
"""Calculate the distance.
This function calculate the distance between the entity
and the super rectangle. If the entity is in its target
box, distance inversely correlates with box size, to
maintain low distance inside large boxes and provide a
gradient to keep points inside; if the entity is not in
its target box, box size linearly correlates with distance,
to penalize points outside larger boxes more severely.
Args:
ent_emb: The embedding of entity.
lb: The lower boundaries of the super rectangle.
ub: The upper boundaries of the super rectangle.
Returns:
The distance between entity and super rectangle.
"""
c = (lb + ub) / 2
w = ub - lb + 1
k = 0.5 * (w - 1) * (w - 1 / w)
return torch.where(torch.logical_and(torch.ge(ent_emb, lb), torch.le(ent_emb, ub)),
torch.abs(ent_emb - c) / w,
torch.abs(ent_emb - c) * w - k)
| 6,177 | 35.994012 | 151 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/SimplE.py | import torch.nn as nn
import torch
import torch.nn.functional as F
import math
from .model import Model
from IPython import embed
class SimplE(Model):
"""`SimplE Embedding for Link Prediction in Knowledge Graphs`_ (SimpleE), which presents a simple enhancement of CP (which we call SimplE) to allow the two embeddings of each entity to be learned dependently.
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_h_emb: Entity embedding, shape:[num_ent, emb_dim].
ent_t_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
rel_inv_emb: Inverse Relation_embedding, shape:[num_rel, emb_dim].
.. _SimplE Embedding for Link Prediction in Knowledge Graphs: http://papers.neurips.cc/paper/7682-simple-embedding-for-link-prediction-in-knowledge-graphs.pdf
"""
def __init__(self, args):
super(SimplE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution."""
self.ent_h_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.ent_t_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
self.rel_inv_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
sqrt_size = 6.0 / math.sqrt(self.args.emb_dim)
nn.init.uniform_(tensor=self.ent_h_emb.weight.data, a=-sqrt_size, b=sqrt_size)
nn.init.uniform_(tensor=self.ent_t_emb.weight.data, a=-sqrt_size, b=sqrt_size)
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-sqrt_size, b=sqrt_size)
nn.init.uniform_(tensor=self.rel_inv_emb.weight.data, a=-sqrt_size, b=sqrt_size)
def score_func(self, hh_emb, rel_emb, tt_emb, ht_emb, rel_inv_emb, th_emb):
"""Calculating the score of triples.
Args:
hh_emb: The head entity embedding on embedding h.
rel_emb: The relation embedding.
tt_emb: The tail entity embedding on embedding t.
ht_emb: The tail entity embedding on embedding h.
rel_inv_emb: The tail entity embedding.
th_emb: The head entity embedding on embedding t.
Returns:
score: The score of triples.
"""
# return -(torch.sum(head_emb * relation_emb * tail_emb, -1) + \
# torch.sum(head_emb * rel_inv_emb * tail_emb, -1))/2
scores1 = torch.sum(hh_emb * rel_emb * tt_emb, dim=-1)
scores2 = torch.sum(ht_emb * rel_inv_emb * th_emb, dim=-1)
return torch.clamp((scores1 + scores2) / 2, -20, 20)
def l2_loss(self):
return (self.ent_h_emb.weight.norm(p = 2) ** 2 + \
self.ent_t_emb.weight.norm(p = 2) ** 2 + \
self.rel_emb.weight.norm(p = 2) ** 2 + \
self.rel_inv_emb.weight.norm(p = 2) ** 2)
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
rel_emb, rel_inv_emb, hh_emb, th_emb, ht_emb, tt_emb = self.get_emb(triples, negs, mode)
return self.score_func(hh_emb, rel_emb, tt_emb, ht_emb, rel_inv_emb, th_emb)
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
rel_emb, rel_inv_emb, hh_emb, th_emb, ht_emb, tt_emb = self.get_emb(triples, mode=mode)
return self.score_func(hh_emb, rel_emb, tt_emb, ht_emb, rel_inv_emb, th_emb)
def get_emb(self, triples, negs=None, mode='single'):
if mode == 'single':
rel_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
rel_inv_emb = self.rel_inv_emb(triples[:, 1]).unsqueeze(1)
hh_emb = self.ent_h_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
th_emb = self.ent_t_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
ht_emb = self.ent_h_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
tt_emb = self.ent_t_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
elif mode == 'head-batch' or mode == "head_predict":
if negs is None: # 说明这个时候是在evluation,所以需要直接用所有的entity embedding
hh_emb = self.ent_h_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
th_emb = self.ent_t_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
else:
hh_emb = self.ent_h_emb(negs) # [bs, num_neg, dim]
th_emb = self.ent_t_emb(negs) # [bs, num_neg, dim]
rel_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
rel_inv_emb = self.rel_inv_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
ht_emb = self.ent_h_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
tt_emb = self.ent_t_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
elif mode == 'tail-batch' or mode == "tail_predict":
if negs is None: # 说明这个时候是在evluation,所以需要直接用所有的entity embedding
ht_emb = self.ent_h_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
tt_emb = self.ent_t_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
else:
ht_emb = self.ent_h_emb(negs) # [bs, num_neg, dim]
tt_emb = self.ent_t_emb(negs) # [bs, num_neg, dim]
rel_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
rel_inv_emb = self.rel_inv_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
hh_emb = self.ent_h_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
th_emb = self.ent_t_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
return rel_emb, rel_inv_emb, hh_emb, th_emb, ht_emb, tt_emb
| 6,453 | 47.893939 | 212 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/model.py | import torch.nn as nn
import torch
class Model(nn.Module):
def __init__(self, args):
super(Model, self).__init__()
def init_emb(self):
raise NotImplementedError
def score_func(self, head_emb, relation_emb, tail_emb):
raise NotImplementedError
def forward(self, triples, negs, mode):
raise NotImplementedError
def tri2emb(self, triples, negs=None, mode="single"):
"""Get embedding of triples.
This function get the embeddings of head, relation, and tail
respectively. each embedding has three dimensions.
Args:
triples (tensor): This tensor save triples id, which dimension is
[triples number, 3].
negs (tensor, optional): This tenosr store the id of the entity to
be replaced, which has one dimension. when negs is None, it is
in the test/eval phase. Defaults to None.
mode (str, optional): This arg indicates that the negative entity
will replace the head or tail entity. when it is 'single', it
means that entity will not be replaced. Defaults to 'single'.
Returns:
head_emb: Head entity embedding.
relation_emb: Relation embedding.
tail_emb: Tail entity embedding.
"""
if mode == "single":
head_emb = self.ent_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
relation_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
tail_emb = self.ent_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
elif mode == "head-batch" or mode == "head_predict":
if negs is None: # 说明这个时候是在evluation,所以需要直接用所有的entity embedding
head_emb = self.ent_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
else:
head_emb = self.ent_emb(negs) # [bs, num_neg, dim]
relation_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
tail_emb = self.ent_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
elif mode == "tail-batch" or mode == "tail_predict":
head_emb = self.ent_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
relation_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
if negs is None:
tail_emb = self.ent_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
else:
tail_emb = self.ent_emb(negs) # [bs, num_neg, dim]
return head_emb, relation_emb, tail_emb
| 2,572 | 40.5 | 85 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/CrossE.py | import torch.nn as nn
import torch
import torch.nn.functional as F
import math
from .model import Model
from IPython import embed
class CrossE(Model):
"""`Interaction Embeddings for Prediction and Explanation in Knowledge Graphs`_ (CrossE), which simulates crossover interactions(bi-directional effects between entities and relations)
to select related information when predicting a new triple
Attributes:
args: Model configuration parameters.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation embedding, shape:[num_rel, emb_dim].
rel_reverse_emb: Reverse Relation embedding, shape:[num_rel, emb_dim].
h_weighted_vector: Interaction matrix for head entities and relations, shape:[num_rel, emb_dim]
t_weighted_vector: Interaction matrix for tail entities and relations, shape:[num_rel, emb_dim]
hr_bias: Bias for head entity and relation
tr_bias: Bias for tail entity and relation
.. _Interaction Embeddings for Prediction and Explanation in Knowledge Graphs: https://arxiv.org/abs/1903.04750
"""
def __init__(self, args):
super(CrossE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
self.dropout = nn.Dropout(self.args.dropout)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim) #关系的rel emb
self.rel_reverse_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim) #reverse关系的rel emb
self.h_weighted_vector = nn.Embedding(self.args.num_rel, self.args.emb_dim) #interaction mactrix
self.t_weighted_vector = nn.Embedding(self.args.num_rel, self.args.emb_dim) #interaction mactrix
# self.bias = nn.Embedding(2, self.args.emb_dim)
self.hr_bias = nn.Parameter(torch.zeros([self.args.emb_dim]))
self.tr_bias = nn.Parameter(torch.zeros([self.args.emb_dim]))
sqrt_size = 6.0 / math.sqrt(self.args.emb_dim)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-sqrt_size, b=sqrt_size)
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-sqrt_size, b=sqrt_size)
nn.init.uniform_(tensor=self.rel_reverse_emb.weight.data, a=-sqrt_size, b=sqrt_size)
nn.init.uniform_(tensor=self.h_weighted_vector.weight.data, a=-sqrt_size, b=sqrt_size)
nn.init.uniform_(tensor=self.t_weighted_vector.weight.data, a=-sqrt_size, b=sqrt_size)
def score_func(self, ent_emb, rel_emb, weighted_vector, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\sigma(tanh(c_r \circ h + c_r \circ h \circ r + b)t ^ T)`
Args:
ent_emb: entity embedding
rel_emb: relation embedding
weighted_vector: Interaction matrix for entities and relations
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
x = ent_emb * weighted_vector + rel_emb * ent_emb * weighted_vector
if mode == "tail_predict":
x = torch.tanh(x + self.hr_bias)
else:
x = torch.tanh(x + self.tr_bias)
x = self.dropout(x)
x = torch.mm(x, self.ent_emb.weight.data.t())
x = torch.sigmoid(x)
return x
def forward(self, triples, mode="single"):
"""The functions used in the training phase, calculate hr_score and tr_score simultaneously
"""
head_emb = self.ent_emb(triples[:, 0])
tail_emb = self.ent_emb(triples[:, 2])
rel_emb = self.rel_emb(triples[:, 1])
rel_reverse_emb = self.rel_reverse_emb(triples[:, 1])
h_weighted_vector = self.h_weighted_vector(triples[:, 1])
t_weighted_vector = self.t_weighted_vector(triples[:, 1])
hr_score = self.score_func(head_emb, rel_emb, h_weighted_vector, "tail_predict")
tr_score = self.score_func(tail_emb, rel_reverse_emb, t_weighted_vector, "head_predict")
# bias = self.bias(triples_id)
return hr_score, tr_score
def get_score(self, batch, mode):
"""The functions used in the testing phase, predict triple score
"""
triples = batch["positive_sample"]
if mode == "tail_predict":
head_emb = self.ent_emb(triples[:, 0])
rel_emb = self.rel_emb(triples[:, 1])
h_weighted_vector = self.h_weighted_vector(triples[:, 1])
return self.score_func(head_emb, rel_emb, h_weighted_vector, "tail_predict")
else:
tail_emb = self.ent_emb(triples[:, 2])
rel_reverse_emb = self.rel_reverse_emb(triples[:, 1])
t_weighted_vector = self.t_weighted_vector(triples[:, 1])
return self.score_func(tail_emb, rel_reverse_emb, t_weighted_vector, "head_predict")
def regularize_loss(self, norm=2):
"""Add regularization to loss
"""
return (self.ent_emb.weight.norm(p = norm) ** norm + \
self.rel_emb.weight.norm(p = norm) ** norm + \
self.rel_reverse_emb.weight.norm(p = norm) ** norm + \
self.h_weighted_vector.weight.norm(p = norm) ** norm + \
self.t_weighted_vector.weight.norm(p = norm) ** norm + \
self.hr_bias.norm(p = norm) ** norm + \
self.tr_bias.norm(p=norm) ** norm)
| 5,460 | 44.890756 | 187 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/TransR.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from .model import Model
from IPython import embed
class TransR(Model):
"""Learning Entity and Relation Embeddings for Knowledge Graph Completion`_ (TransR), which building entity and relation embeddings in separate entity space and relation spaces
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation embedding, shape:[num_rel, emb_dim].
transfer_matrix: Transfer entity and relation embedding, shape:[num_rel, emb_dim*emb_dim]
.. _Translating Embeddings for Modeling Multi-relational Data: http://www.aaai.org/ocs/index.php/AAAI/AAAI15/paper/download/9571/9523/
"""
def __init__(self, args):
super(TransR, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.norm_flag = args.norm_flag
self.init_emb()
def init_emb(self):
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]), requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False,
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
self.transfer_matrix = nn.Embedding(
self.args.num_rel, self.args.emb_dim * self.args.emb_dim
)
nn.init.uniform_(
tensor=self.ent_emb.weight.data,
a=-self.embedding_range.item(),
b=self.embedding_range.item(),
)
nn.init.uniform_(
tensor=self.rel_emb.weight.data,
a=-self.embedding_range.item(),
b=self.embedding_range.item(),
)
diag_matrix = torch.eye(self.args.emb_dim)
diag_matrix = diag_matrix.flatten().repeat(self.args.num_rel, 1)
self.transfer_matrix.weight.data = diag_matrix
# nn.init.uniform_(tensor=self.transfer_matrix.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\gamma - \| M_{r} {e}_h + r_r - M_{r}e_t \|_{p}^2`
"""
if self.norm_flag:
head_emb = F.normalize(head_emb, 2, -1)
relation_emb = F.normalize(relation_emb, 2, -1)
tail_emb = F.normalize(tail_emb, 2, -1)
if mode == "head-batch" or mode == "head_predict":
score = head_emb + (relation_emb - tail_emb)
else:
score = (head_emb + relation_emb) - tail_emb
score = self.margin.item() - torch.norm(score, p=1, dim=-1)
return score
def forward(self, triples, negs=None, mode="single"):
"""The functions used in the training phase, calculate triple score."""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
rel_transfer = self.transfer_matrix(triples[:, 1]) # shape:[bs, dim]
head_emb = self._transfer(head_emb, rel_transfer, mode)
tail_emb = self._transfer(tail_emb, rel_transfer, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase, predict triple score."""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
rel_transfer = self.transfer_matrix(triples[:, 1]) # shape:[bs, dim]
head_emb = self._transfer(head_emb, rel_transfer, mode)
tail_emb = self._transfer(tail_emb, rel_transfer, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def _transfer(self, emb, rel_transfer, mode):
"""Transfer entity embedding with relation-specific matrix.
Args:
emb: Entity embeddings, shape:[batch_size, emb_dim]
rel_transfer: Relation-specific projection matrix, shape:[batch_size, emb_dim]
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
transfered entity emb: Shape:[batch_size, emb_dim]
"""
rel_transfer = rel_transfer.view(-1, self.args.emb_dim, self.args.emb_dim)
rel_transfer = rel_transfer.unsqueeze(dim=1)
emb = emb.unsqueeze(dim=-2)
emb = torch.matmul(emb, rel_transfer)
return emb.squeeze(dim=-2)
| 4,844 | 40.410256 | 180 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/DualE.py | import torch.nn as nn
import torch
from .model import Model
from numpy.random import RandomState
import numpy as np
class DualE(Model):
"""`Dual Quaternion Knowledge Graph Embeddings`_ (DualE), which introduces dual quaternions into knowledge graph embeddings.
Attributes:
args: Model configuration parameters.
ent_emb: Entity embedding, shape:[num_ent, emb_dim * 8].
rel_emb: Relation embedding, shape:[num_rel, emb_dim * 8].
.. Dual Quaternion Knowledge Graph Embeddings: https://ojs.aaai.org/index.php/AAAI/article/view/16850
"""
def __init__(self, args):
super(DualE, self).__init__(args)
self.args = args
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim*8)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim*8)
self.criterion = nn.Softplus()
self.fc = nn.Linear(100, 50, bias=False)
self.ent_dropout = torch.nn.Dropout(0)
self.rel_dropout = torch.nn.Dropout(0)
self.bn = torch.nn.BatchNorm1d(self.args.emb_dim)
self.init_weights()
def init_weights(self):
r, i, j, k,r_1,i_1,j_1,k_1 = self.quaternion_init(self.args.num_ent, self.args.emb_dim)
r, i, j, k,r_1,i_1,j_1,k_1 = torch.from_numpy(r), torch.from_numpy(i), torch.from_numpy(j), torch.from_numpy(k),\
torch.from_numpy(r_1), torch.from_numpy(i_1), torch.from_numpy(j_1), torch.from_numpy(k_1)
tmp_ent_emb = torch.cat((r, i, j, k,r_1,i_1,j_1,k_1),1)
self.ent_emb.weight.data = tmp_ent_emb.type_as(self.ent_emb.weight.data)
s, x, y, z,s_1,x_1,y_1,z_1 = self.quaternion_init(self.args.num_ent, self.args.emb_dim)
s, x, y, z,s_1,x_1,y_1,z_1 = torch.from_numpy(s), torch.from_numpy(x), torch.from_numpy(y), torch.from_numpy(z), \
torch.from_numpy(s_1), torch.from_numpy(x_1), torch.from_numpy(y_1), torch.from_numpy(z_1)
tmp_rel_emb = torch.cat((s, x, y, z,s_1,x_1,y_1,z_1),1)
self.rel_emb.weight.data = tmp_rel_emb.type_as(self.ent_emb.weight.data)
#Calculate the Dual Hamiltonian product
def _omult(self, a_0, a_1, a_2, a_3, b_0, b_1, b_2, b_3, c_0, c_1, c_2, c_3, d_0, d_1, d_2, d_3):
h_0=a_0*c_0-a_1*c_1-a_2*c_2-a_3*c_3
h1_0=a_0*d_0+b_0*c_0-a_1*d_1-b_1*c_1-a_2*d_2-b_2*c_2-a_3*d_3-b_3*c_3
h_1=a_0*c_1+a_1*c_0+a_2*c_3-a_3*c_2
h1_1=a_0*d_1+b_0*c_1+a_1*d_0+b_1*c_0+a_2*d_3+b_2*c_3-a_3*d_2-b_3*c_2
h_2=a_0*c_2-a_1*c_3+a_2*c_0+a_3*c_1
h1_2=a_0*d_2+b_0*c_2-a_1*d_3-b_1*c_3+a_2*d_0+b_2*c_0+a_3*d_1+b_3*c_1
h_3=a_0*c_3+a_1*c_2-a_2*c_1+a_3*c_0
h1_3=a_0*d_3+b_0*c_3+a_1*d_2+b_1*c_2-a_2*d_1-b_2*c_1+a_3*d_0+b_3*c_0
return (h_0,h_1,h_2,h_3,h1_0,h1_1,h1_2,h1_3)
#Normalization of relationship embedding
def _onorm(self,r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8):
denominator_0 = r_1 ** 2 + r_2 ** 2 + r_3 ** 2 + r_4 ** 2
denominator_1 = torch.sqrt(denominator_0)
deno_cross = r_5 * r_1 + r_6 * r_2 + r_7 * r_3 + r_8 * r_4
r_5 = r_5 - deno_cross / denominator_0 * r_1
r_6 = r_6 - deno_cross / denominator_0 * r_2
r_7 = r_7 - deno_cross / denominator_0 * r_3
r_8 = r_8 - deno_cross / denominator_0 * r_4
r_1 = r_1 / denominator_1
r_2 = r_2 / denominator_1
r_3 = r_3 / denominator_1
r_4 = r_4 / denominator_1
return r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8
#Calculate the inner product of the head entity and the relationship Hamiltonian product and the tail entity
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:` <\boldsymbol{Q}_h \otimes \boldsymbol{W}_r^{\diamond}, \boldsymbol{Q}_t> `
Args:
head_emb: The head entity embedding with 8 dimensionalities.
relation_emb: The relation embedding with 8 dimensionalities.
tail_emb: The tail entity embedding with 8 dimensionalities.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples with regul_1 and regul_2
"""
e_1_h,e_2_h,e_3_h,e_4_h,e_5_h,e_6_h,e_7_h,e_8_h = torch.chunk(head_emb, 8, dim=-1)
e_1_t,e_2_t,e_3_t,e_4_t,e_5_t,e_6_t,e_7_t,e_8_t = torch.chunk(tail_emb, 8, dim=-1)
r_1,r_2,r_3,r_4,r_5,r_6,r_7,r_8 = torch.chunk(relation_emb, 8, dim=-1)
r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8 = self._onorm(r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8 )
o_1, o_2, o_3, o_4, o_5, o_6, o_7, o_8 = self._omult(e_1_h, e_2_h, e_3_h, e_4_h, e_5_h, e_6_h, e_7_h, e_8_h,
r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8)
score_r = (o_1 * e_1_t + o_2 * e_2_t + o_3 * e_3_t + o_4 * e_4_t
+ o_5 * e_5_t + o_6 * e_6_t + o_7 * e_7_t + o_8 * e_8_t)
regul_1 = (torch.mean(torch.abs(e_1_h) ** 2)
+ torch.mean(torch.abs(e_2_h) ** 2)
+ torch.mean(torch.abs(e_3_h) ** 2)
+ torch.mean(torch.abs(e_4_h) ** 2)
+ torch.mean(torch.abs(e_5_h) ** 2)
+ torch.mean(torch.abs(e_6_h) ** 2)
+ torch.mean(torch.abs(e_7_h) ** 2)
+ torch.mean(torch.abs(e_8_h) ** 2)
+ torch.mean(torch.abs(e_1_t) ** 2)
+ torch.mean(torch.abs(e_2_t) ** 2)
+ torch.mean(torch.abs(e_3_t) ** 2)
+ torch.mean(torch.abs(e_4_t) ** 2)
+ torch.mean(torch.abs(e_5_t) ** 2)
+ torch.mean(torch.abs(e_6_t) ** 2)
+ torch.mean(torch.abs(e_7_t) ** 2)
+ torch.mean(torch.abs(e_8_t) ** 2)
)
regul_2 = (torch.mean(torch.abs(r_1) ** 2)
+ torch.mean(torch.abs(r_2) ** 2)
+ torch.mean(torch.abs(r_3) ** 2)
+ torch.mean(torch.abs(r_4) ** 2)
+ torch.mean(torch.abs(r_5) ** 2)
+ torch.mean(torch.abs(r_6) ** 2)
+ torch.mean(torch.abs(r_7) ** 2)
+ torch.mean(torch.abs(r_8) ** 2))
return (torch.sum(score_r, -1), regul_1, regul_2)
def forward(self, triples, negs=None, mode='single'):
if negs != None:
head_emb, relation_emb, tail_emb = self.tri2emb(negs)
else:
head_emb, relation_emb, tail_emb = self.tri2emb(triples)
score, regul_1, regul_2 = self.score_func(head_emb, relation_emb, tail_emb, mode)
return (score, regul_1, regul_2)
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
e_1_h,e_2_h,e_3_h,e_4_h,e_5_h,e_6_h,e_7_h,e_8_h = torch.chunk(head_emb, 8, dim=-1)
e_1_t,e_2_t,e_3_t,e_4_t,e_5_t,e_6_t,e_7_t,e_8_t = torch.chunk(tail_emb, 8, dim=-1)
r_1,r_2,r_3,r_4,r_5,r_6,r_7,r_8 = torch.chunk(relation_emb, 8, dim=-1)
r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8 = self._onorm(r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8 )
o_1, o_2, o_3, o_4, o_5, o_6, o_7, o_8 = self._omult(e_1_h, e_2_h, e_3_h, e_4_h, e_5_h, e_6_h, e_7_h, e_8_h,
r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8)
score_r = (o_1 * e_1_t + o_2 * e_2_t + o_3 * e_3_t + o_4 * e_4_t
+ o_5 * e_5_t + o_6 * e_6_t + o_7 * e_7_t + o_8 * e_8_t)
return torch.sum(score_r, -1)
def quaternion_init(self, in_features, out_features, criterion='he'):
"""
Quaternion-valued weight initialization
the initialization scheme is optional on these four datasets,
random initialization can get the same performance. This initialization
scheme might be useful for the case which needs fewer epochs.
"""
fan_in = in_features
fan_out = out_features
if criterion == 'glorot':
s = 1. / np.sqrt(2 * (fan_in + fan_out))
elif criterion == 'he':
s = 1. / np.sqrt(2 * fan_in)
else:
raise ValueError('Invalid criterion: ', criterion)
rng = RandomState(2020)
# Generating randoms and purely imaginary quaternions :
kernel_shape = (in_features, out_features)
number_of_weights = np.prod(kernel_shape) # in_features*out_features
v_i = np.random.uniform(0.0, 1.0, number_of_weights) #(low,high,size)
v_j = np.random.uniform(0.0, 1.0, number_of_weights)
v_k = np.random.uniform(0.0, 1.0, number_of_weights)
# Purely imaginary quaternions unitary
for i in range(0, number_of_weights):
norm = np.sqrt(v_i[i] ** 2 + v_j[i] ** 2 + v_k[i] ** 2) + 0.0001
v_i[i] /= norm
v_j[i] /= norm
v_k[i] /= norm
v_i = v_i.reshape(kernel_shape)
v_j = v_j.reshape(kernel_shape)
v_k = v_k.reshape(kernel_shape)
modulus = rng.uniform(low=-s, high=s, size=kernel_shape)
# Calculate the three parts about t
kernel_shape1 = (in_features, out_features)
number_of_weights1 = np.prod(kernel_shape1)
t_i = np.random.uniform(0.0, 1.0, number_of_weights1)
t_j = np.random.uniform(0.0, 1.0, number_of_weights1)
t_k = np.random.uniform(0.0, 1.0, number_of_weights1)
# Purely imaginary quaternions unitary
for i in range(0, number_of_weights1):
norm1 = np.sqrt(t_i[i] ** 2 + t_j[i] ** 2 + t_k[i] ** 2) + 0.0001
t_i[i] /= norm1
t_j[i] /= norm1
t_k[i] /= norm1
t_i = t_i.reshape(kernel_shape1)
t_j = t_j.reshape(kernel_shape1)
t_k = t_k.reshape(kernel_shape1)
tmp_t = rng.uniform(low=-s, high=s, size=kernel_shape1)
phase = rng.uniform(low=-np.pi, high=np.pi, size=kernel_shape)
phase1 = rng.uniform(low=-np.pi, high=np.pi, size=kernel_shape1)
weight_r = modulus * np.cos(phase)
weight_i = modulus * v_i * np.sin(phase)
weight_j = modulus * v_j * np.sin(phase)
weight_k = modulus * v_k * np.sin(phase)
wt_i = tmp_t * t_i * np.sin(phase1)
wt_j = tmp_t * t_j * np.sin(phase1)
wt_k = tmp_t * t_k * np.sin(phase1)
i_0=weight_r
i_1=weight_i
i_2=weight_j
i_3=weight_k
i_4=(-wt_i*weight_i-wt_j*weight_j-wt_k*weight_k)/2
i_5=(wt_i*weight_r+wt_j*weight_k-wt_k*weight_j)/2
i_6=(-wt_i*weight_k+wt_j*weight_r+wt_k*weight_i)/2
i_7=(wt_i*weight_j-wt_j*weight_i+wt_k*weight_r)/2
return (i_0,i_1,i_2,i_3,i_4,i_5,i_6,i_7)
| 11,028 | 43.471774 | 131 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/ConvE.py | import torch
import torch.nn as nn
from .model import Model
from IPython import embed
from torch.autograd import Variable
from inspect import stack
#TODO: ConvE and SEGNN
class ConvE(Model):
"""`Convolutional 2D Knowledge Graph Embeddings`_ (ConvE), which use a 2D convolution network for embedding representation.
Attributes:
args: Model configuration parameters.
.. _Convolutional 2D Knowledge Graph Embeddings: https://arxiv.org/pdf/1707.01476.pdf
"""
def __init__(self, args):
super(ConvE, self).__init__(args)
self.args = args
self.emb_ent = None
self.emb_rel = None
self.init_emb(args)
def init_emb(self,args):
"""Initialize the convolution layer and embeddings .
Args:
conv1: The convolution layer.
fc: The full connection layer.
bn0, bn1, bn2: The batch Normalization layer.
inp_drop, hid_drop, feg_drop: The dropout layer.
emb_ent: Entity embedding, shape:[num_ent, emb_dim].
emb_rel: Relation_embedding, shape:[num_rel, emb_dim].
"""
self.emb_dim1 = self.args.emb_shape
self.emb_dim2 = self.args.emb_dim // self.emb_dim1
self.emb_ent = torch.nn.Embedding(self.args.num_ent, self.args.emb_dim, padding_idx=0)
self.emb_rel = torch.nn.Embedding(self.args.num_rel, self.args.emb_dim, padding_idx=0)
torch.nn.init.xavier_normal_(self.emb_ent.weight.data)
torch.nn.init.xavier_normal_(self.emb_rel.weight.data)
# Setting dropout
self.inp_drop = torch.nn.Dropout(self.args.inp_drop)
self.hid_drop = torch.nn.Dropout(self.args.hid_drop)
self.feg_drop = torch.nn.Dropout2d(self.args.fet_drop)
self.ent_drop = torch.nn.Dropout(self.args.ent_drop_pred)
self.fc_drop = torch.nn.Dropout(self.args.fc_drop)
# Setting net model
self.conv1 = torch.nn.Conv2d(1, out_channels=self.args.out_channel, kernel_size=self.args.ker_sz, stride=1, padding=0, bias=False)
self.bn0 = torch.nn.BatchNorm2d(1)
self.bn1 = torch.nn.BatchNorm2d(self.args.out_channel)
self.bn2 = torch.nn.BatchNorm1d(self.args.emb_dim)
self.register_parameter('b', torch.nn.Parameter(torch.zeros(self.args.num_ent)))
self.fc = torch.nn.Linear(self.args.hid_size,self.args.emb_dim, bias=False)
def score_func(self, head_emb, relation_emb, choose_emb = None):
"""Calculate the score of the triple embedding.
This function calculate the score of the embedding.
First, the entity and relation embeddings are reshaped
and concatenated; the resulting matrix is then used as
input to a convolutional layer; the resulting feature
map tensor is vectorised and projected into a k-dimensional
space.
Args:
head_emb: The embedding of head entity.
relation_emb:The embedding of relation.
Returns:
score: Final score of the embedding.
"""
if self.args.model_name == "SEGNN":
head_emb = head_emb.view(-1, 1, head_emb.shape[-1])
relation_emb = relation_emb.view(-1, 1, relation_emb.shape[-1])
stacked_inputs = torch.cat([head_emb, relation_emb], 1)
stacked_inputs = torch.transpose(stacked_inputs, 2, 1).reshape((-1, 1, 2 * self.args.k_h, self.args.k_w))
else:
stacked_inputs = torch.cat([head_emb, relation_emb], 2)
stacked_inputs = self.bn0(stacked_inputs)
x = self.inp_drop(stacked_inputs)
#print(x==stacked_inputs)
x = self.conv1(x)
x = self.bn1(x)
x = torch.nn.functional.relu(x)
if self.args.model_name == 'SEGNN':
x = self.fc_drop(x)
else:
x = self.feg_drop(x)
x = x.view(x.shape[0], -1)
x = self.fc(x)
if self.args.model_name == 'SEGNN':
x = self.bn2(x)
x = torch.nn.functional.relu(x)
x = self.hid_drop(x)
choose_emb = self.ent_drop(choose_emb)
x = torch.mm(x, choose_emb.transpose(1,0))
else:
x = self.hid_drop(x)
x = self.bn2(x)
x = torch.nn.functional.relu(x)
x = torch.mm(x, self.emb_ent.weight.transpose(1,0)) if choose_emb == None \
else torch.mm(x, choose_emb.transpose(1, 0))
x += self.b.expand_as(x)
x = torch.sigmoid(x)
return x
def forward(self, triples):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
Returns:
score: The score of triples.
"""
head_emb = self.emb_ent(triples[:, 0]).view(-1, 1, self.emb_dim1, self.emb_dim2)
rela_emb = self.emb_rel(triples[:, 1]).view(-1, 1, self.emb_dim1, self.emb_dim2)
score = self.score_func(head_emb, rela_emb)
return score
def get_score(self, batch, mode="tail_predict"):
"""The functions used in the testing phase
Args:
batch: A batch of data.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb = self.emb_ent(triples[:, 0]).view(-1, 1, self.emb_dim1, self.emb_dim2)
rela_emb = self.emb_rel(triples[:, 1]).view(-1, 1, self.emb_dim1, self.emb_dim2)
score = self.score_func(head_emb, rela_emb)
return score | 5,548 | 36.493243 | 138 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/TransE.py | import torch.nn as nn
import torch
from .model import Model
from IPython import embed
class TransE(Model):
"""`Translating Embeddings for Modeling Multi-relational Data`_ (TransE), which represents the relationships as translations in the embedding space.
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation embedding, shape:[num_rel, emb_dim].
.. _Translating Embeddings for Modeling Multi-relational Data: http://papers.nips.cc/paper/5071-translating-embeddings-for-modeling-multi-rela
"""
def __init__(self, args):
super(TransE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
"""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\gamma - ||h + r - t||_F`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
score = (head_emb + relation_emb) - tail_emb
score = self.margin.item() - torch.norm(score, p=1, dim=-1)
return score
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
| 3,488 | 34.969072 | 152 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/TransH.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from .model import Model
from IPython import embed
class TransH(Model):
"""`Knowledge Graph Embedding by Translating on Hyperplanes`_ (TransH), which apply the translation from head to tail entity in a
relational-specific hyperplane in order to address its inability to model one-to-many, many-to-one, and many-to-many relations.
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation embedding, shape:[num_rel, emb_dim].
norm_vector: Relation-specific projection matrix, shape:[num_rel, emb_dim]
.. _Knowledge Graph Embedding by Translating on Hyperplanes: https://ojs.aaai.org/index.php/AAAI/article/view/8870
"""
def __init__(self, args):
super(TransH, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.norm_flag = args.norm_flag
self.init_emb()
def init_emb(self):
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]), requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False,
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
self.norm_vector = nn.Embedding(self.args.num_rel, self.args.emb_dim)
nn.init.uniform_(
tensor=self.ent_emb.weight.data,
a=-self.embedding_range.item(),
b=self.embedding_range.item(),
)
nn.init.uniform_(
tensor=self.rel_emb.weight.data,
a=-self.embedding_range.item(),
b=self.embedding_range.item(),
)
nn.init.uniform_(
tensor=self.norm_vector.weight.data,
a=-self.embedding_range.item(),
b=self.embedding_range.item(),
)
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\gamma - \|e'_{h,r} + d_r - e'_{t,r}\|_{p}^2`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
if self.norm_flag:
head_emb = F.normalize(head_emb, 2, -1)
relation_emb = F.normalize(relation_emb, 2, -1)
tail_emb = F.normalize(tail_emb, 2, -1)
if mode == "head-batch" or mode == "head_predict":
score = head_emb + (relation_emb - tail_emb)
else:
score = (head_emb + relation_emb) - tail_emb
score = self.margin.item() - torch.norm(score, p=1, dim=-1)
return score
def forward(self, triples, negs=None, mode="single"):
"""The functions used in the training phase, same as TransE"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
norm_vector = self.norm_vector(triples[:, 1]).unsqueeze(
dim=1
) # shape:[bs, 1, dim]
head_emb = self._transfer(head_emb, norm_vector)
tail_emb = self._transfer(tail_emb, norm_vector)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase, same as TransE"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
norm_vector = self.norm_vector(triples[:, 1]).unsqueeze(
dim=1
) # shape:[bs, 1, dim]
head_emb = self._transfer(head_emb, norm_vector)
tail_emb = self._transfer(tail_emb, norm_vector)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def _transfer(self, emb, norm_vector):
"""Projecting entity embeddings onto the relation-specific hyperplane
The formula for Projecting entity embeddings is :math:`e'_{r} = e - w_r^\Top e w_r`
Args:
emb: Entity embeddings, shape:[batch_size, emb_dim]
norm_vector: Relation-specific projection matrix, shape:[num_rel, emb_dim]
Returns:
projected entity emb: Shape:[batch_size, emb_dim]
"""
if self.norm_flag:
norm_vector = F.normalize(norm_vector, p=2, dim=-1)
return emb - torch.sum(emb * norm_vector, -1, True) * norm_vector
| 4,937 | 37.578125 | 133 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/KGEModel/HAKE.py | import torch
import torch.nn as nn
from .model import Model
class HAKE(Model):
"""`Learning Hierarchy-Aware Knowledge Graph Embeddings for Link Prediction`_ (HAKE), which maps entities into the polar coordinate system.
Attributes:
args: Model configuration parameters.
epsilon: Calculate embedding_range.
margin: Calculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim * 2].
rel_emb: Relation embedding, shape:[num_rel, emb_dim * 3].
phase_weight: Calculate phase score.
modules_weight: Calculate modulus score.
.. _Learning Hierarchy-Aware Knowledge Graph Embeddings for Link Prediction: https://arxiv.org/pdf/1911.09419.pdf
"""
def __init__(self, args):
super(HAKE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
"""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False,
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False,
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim * 2)
nn.init.uniform_(
tensor = self.ent_emb.weight.data,
a = -self.embedding_range.item(),
b = self.embedding_range.item(),
)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim * 3)
nn.init.uniform_(
tensor = self.rel_emb.weight.data,
a = -self.embedding_range.item(),
b = self.embedding_range.item(),
)
nn.init.ones_(
tensor=self.rel_emb.weight[:, self.args.emb_dim: 2*self.args.emb_dim],
)
nn.init.zeros_(
tensor=self.rel_emb.weight[:, 2*self.args.emb_dim: 3*self.args.emb_dim]
)
self.phase_weight = nn.Parameter(
torch.Tensor([self.args.phase_weight * self.embedding_range.item()])
)
self.modules_weight = nn.Parameter(
torch.Tensor([self.args.modulus_weight])
)
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`\gamma - ||h_m \circ r_m- t_m||_2 - \lambda ||\sin((h_p + r_p - t_p)/2)||_1`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
phase_head, mod_head = torch.chunk(head_emb, 2, dim=-1)
phase_tail, mod_tail = torch.chunk(tail_emb, 2, dim=-1)
phase_rela, mod_rela, bias_rela = torch.chunk(relation_emb, 3, dim=-1)
pi = 3.141592653589793
phase_head = phase_head / (self.embedding_range.item() / pi)
phase_tail = phase_tail / (self.embedding_range.item() / pi)
phase_rela = phase_rela / (self.embedding_range.item() / pi)
if mode == 'head-batch':
phase_score = phase_head + (phase_rela - phase_tail)
else:
phase_score = (phase_head + phase_rela) - phase_tail
mod_rela = torch.abs(mod_rela)
bias_rela = torch.clamp(bias_rela, max=1)
indicator = (bias_rela < -mod_rela)
bias_rela[indicator] = -mod_rela[indicator]
r_score = mod_head * (mod_rela + bias_rela) - mod_tail * (1 - bias_rela)
phase_score = torch.sum(torch.abs(torch.sin(phase_score /2)), dim=2) * self.phase_weight
r_score = torch.norm(r_score, dim=2) * self.modules_weight
return self.margin.item() - (phase_score + r_score)
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch['positive_sample']
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
| 5,161 | 35.352113 | 143 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/RuleModel/ComplEx_NNE_AER.py | import torch.nn as nn
import torch
import os
from .model import Model
from IPython import embed
class ComplEx_NNE_AER(Model):
"""`Improving Knowledge Graph Embedding Using Simple Constraints`_ (/ComplEx-NNE_AER), which examines non-negativity constraints on entity representations and approximate entailment constraints on relation representations.
Attributes:
args: Model configuration parameters.
epsilon: Caculate embedding_range.
margin: Caculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
.. _Improving Knowledge Graph Embedding Using Simple Constraints: https://arxiv.org/pdf/1805.02408.pdf
"""
def __init__(self, args, rel2id):
super(ComplEx_NNE_AER, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
self.rule, self.conf = self.get_rule(rel2id)
def get_rule(self, rel2id):
"""Get rule for rule_base KGE models, such as ComplEx_NNE model.
Get rule and confidence from _cons.txt file.
Update:
(rule_p, rule_q): Rule.
confidence: The confidence of rule.
"""
rule_p, rule_q, confidence = [], [], []
with open(os.path.join(self.args.data_path, '_cons.txt')) as file:
lines = file.readlines()
for line in lines:
rule_str, trust = line.strip().split()
body, head = rule_str.split(',')
if '-' in body:
rule_p.append(rel2id[body[1:]])
rule_q.append(rel2id[head])
else:
rule_p.append(rel2id[body])
rule_q.append(rel2id[head])
confidence.append(float(trust))
rule_p = torch.tensor(rule_p).cuda()
rule_q = torch.tensor(rule_q).cuda()
confidence = torch.tensor(confidence).cuda()
return (rule_p, rule_q), confidence
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
"""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim * 2)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim * 2)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`Re(< wr, es, e¯o >)`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
re_head, im_head = torch.chunk(head_emb, 2, dim=-1)
re_relation, im_relation = torch.chunk(relation_emb, 2, dim=-1)
re_tail, im_tail = torch.chunk(tail_emb, 2, dim=-1)
return torch.sum(
re_head * re_tail * re_relation
+ im_head * im_tail * re_relation
+ re_head * im_tail * im_relation
- im_head * re_tail * im_relation,
-1
)
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score | 4,959 | 37.153846 | 226 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/RuleModel/IterE.py | import torch.nn as nn
import torch
import os
from .model import Model
from IPython import embed
from collections import defaultdict
import numpy as np
import pickle
import copy
class IterE(Model):
"""`Iteratively Learning Embeddings and Rules for Knowledge Graph Reasoning. (WWW'19)`_ (IterE).
Attributes:
args: Model configuration parameters.
epsilon: Caculate embedding_range.
margin: Caculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
.. _Iteratively Learning Embeddings and Rules for Knowledge Graph Reasoning. (WWW'19): https://dl.acm.org/doi/10.1145/3308558.3313612
"""
def __init__(self, args, train_sampler, test_sampler):
super(IterE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
#print(self.args)
#print(train_sampler)
#print('run get_axiom()')
self.train_sampler = train_sampler
self.train_triples_base = copy.deepcopy(train_sampler.train_triples)
self.select_probability = self.args.select_probability
self.max_entialments = self.args.max_entialments
self.axiom_types = self.args.axiom_types
self.axiom_weight = self.args.axiom_weight
self.inject_triple_percent = self.args.inject_triple_percent
self.sparsity = 0.995
self.num_entity = self.args.num_ent
self.relation2id=train_sampler.rel2id
self.train_ids=train_sampler.train_triples
self.valid_ids=train_sampler.valid_triples
self.test_ids=train_sampler.test_triples
#print(len(self.train_ids))
#print(len(self.valid_ids))
#print(len(self.test_ids))
self.train_ids_labels_inject = np.reshape([], [-1, 4])
# generate r_ht, hr_t
print('# generate r_ht, hr_t')
self.r_ht, self.hr_t, self.tr_h, self.hr_t_all, self.tr_h_all = self._generate(self.train_ids, self.valid_ids, self.test_ids)
# generate entity2frequency and entity2sparsity dict
print('# generate entity2frequency and entity2sparsity dict')
self.entity2frequency, self.entity2sparsity = self._entity2frequency()
print('# get_axiom')
self.get_axiom()
#self.rule, self.conf = self.get_rule(self.relation2id)
def _entity2frequency(self):
ent2freq = {ent:0 for ent in range(self.num_entity)}
ent2sparsity = {ent:-1 for ent in range(self.num_entity)}
for h,r,t in self.train_ids:
ent2freq[h] += 1
ent2freq[t] += 1
ent_freq_list = np.asarray([ent2freq[ent] for ent in range(self.num_entity)])
ent_freq_list_sort = np.argsort(ent_freq_list)
max_freq = max(list(ent2freq))
min_freq = min(list(ent2freq))
for ent, freq in ent2freq.items():
sparsity = 1 - (freq-min_freq)/(max_freq - min_freq)
ent2sparsity[ent] = sparsity
return ent2freq, ent2sparsity
def _generate(self, train, valid, test):
r_ht = defaultdict(set)
hr_t = defaultdict(set)
tr_h = defaultdict(set)
hr_t_all = defaultdict(list)
tr_h_all = defaultdict(list)
for (h,r,t) in train:
r_ht[r].add((h,t))
hr_t[(h,r)].add(t)
tr_h[(t,r)].add(h)
hr_t_all[(h,r)].append(t)
tr_h_all[(t,r)].append(h)
for (h,r,t) in test+valid:
hr_t_all[(h,r)].append(t)
tr_h_all[(t, r)].append(h)
return r_ht, hr_t, tr_h, hr_t_all, tr_h_all
def get_axiom(self, ):
self.axiom_dir = os.path.join(self.args.data_path, 'axiom_pool')
self.reflexive_dir, self.symmetric_dir, self.transitive_dir, self.inverse_dir, self.subproperty_dir, self.equivalent_dir, self.inferencechain1, self.inferencechain2, self.inferencechain3, self.inferencechain4 = map(lambda x: os.path.join(self.axiom_dir, x),
['axiom_reflexive.txt',
'axiom_symmetric.txt',
'axiom_transitive.txt',
'axiom_inverse.txt',
'axiom_subProperty.txt',
'axiom_equivalent.txt',
'axiom_inferenceChain1.txt',
'axiom_inferenceChain2.txt',
'axiom_inferenceChain3.txt',
'axiom_inferenceChain4.txt'])
# read and materialize axioms
print('# self._read_axioms()')
self._read_axioms()
print('# self._read_axioms()')
self._materialize_axioms()
print('# self._read_axioms()')
self._init_valid_axioms()
def _read_axioms(self):
# for each axiom, the first id is the basic relation
self.axiompool_reflexive = self._read_axiompool_file(self.reflexive_dir)
self.axiompool_symmetric = self._read_axiompool_file(self.symmetric_dir)
self.axiompool_transitive = self._read_axiompool_file(self.transitive_dir)
self.axiompool_inverse = self._read_axiompool_file(self.inverse_dir)
self.axiompool_equivalent = self._read_axiompool_file(self.equivalent_dir)
self.axiompool_subproperty = self._read_axiompool_file(self.subproperty_dir)
self.axiompool_inferencechain1 = self._read_axiompool_file(self.inferencechain1)
self.axiompool_inferencechain2 = self._read_axiompool_file(self.inferencechain2)
self.axiompool_inferencechain3 = self._read_axiompool_file(self.inferencechain3)
self.axiompool_inferencechain4 = self._read_axiompool_file(self.inferencechain4)
self.axiompool = [self.axiompool_reflexive, self.axiompool_symmetric, self.axiompool_transitive,
self.axiompool_inverse, self.axiompool_subproperty, self.axiompool_equivalent,
self.axiompool_inferencechain1,self.axiompool_inferencechain2,
self.axiompool_inferencechain3,self.axiompool_inferencechain4]
def _read_axiompool_file(self, file):
f = open(file, 'r')
axioms = []
for line in f.readlines():
line_list = line.strip().split('\t')
axiom_ids = list(map(lambda x: self.relation2id[x], line_list))
#axiom_ids = self.relation2id[line_list]
axioms.append(axiom_ids)
# for the case reflexive pool is empty
if len(axioms) == 0:
np.reshape(axioms, [-1, 3])
return axioms
# for each axioms in axiom pool
# generate a series of entailments for each axiom
def _materialize_axioms(self, generate=True, dump=True, load=False):
if generate:
self.reflexive2entailment = defaultdict(list)
self.symmetric2entailment = defaultdict(list)
self.transitive2entailment = defaultdict(list)
self.inverse2entailment = defaultdict(list)
self.equivalent2entailment = defaultdict(list)
self.subproperty2entailment = defaultdict(list)
self.inferencechain12entailment = defaultdict(list)
self.inferencechain22entailment = defaultdict(list)
self.inferencechain32entailment = defaultdict(list)
self.inferencechain42entailment = defaultdict(list)
self.reflexive_entailments, self.reflexive_entailments_num = self._materialize_sparse(self.axiompool_reflexive, type='reflexive')
self.symmetric_entailments, self.symmetric_entailments_num = self._materialize_sparse(self.axiompool_symmetric, type='symmetric')
self.transitive_entailments, self.transitive_entailments_num = self._materialize_sparse(self.axiompool_transitive, type='transitive')
self.inverse_entailments, self.inverse_entailments_num = self._materialize_sparse(self.axiompool_inverse, type='inverse')
self.subproperty_entailments, self.subproperty_entailments_num = self._materialize_sparse(self.axiompool_subproperty, type='subproperty')
self.equivalent_entailments, self.equivalent_entailments_num = self._materialize_sparse(self.axiompool_equivalent, type='equivalent')
self.inferencechain1_entailments, self.inferencechain1_entailments_num = self._materialize_sparse(self.axiompool_inferencechain1, type='inferencechain1')
self.inferencechain2_entailments, self.inferencechain2_entailments_num = self._materialize_sparse(self.axiompool_inferencechain2, type='inferencechain2')
self.inferencechain3_entailments, self.inferencechain3_entailments_num = self._materialize_sparse(self.axiompool_inferencechain3, type='inferencechain3')
self.inferencechain4_entailments, self.inferencechain4_entailments_num = self._materialize_sparse(self.axiompool_inferencechain4, type='inferencechain4')
print('reflexive entailments for sparse: ', self.reflexive_entailments_num)
print('symmetric entailments for sparse: ', self.symmetric_entailments_num)
print('transitive entailments for sparse: ', self.transitive_entailments_num)
print('inverse entailments for sparse: ', self.inverse_entailments_num)
print('subproperty entailments for sparse: ', self.subproperty_entailments_num)
print('equivalent entailments for sparse: ', self.equivalent_entailments_num)
print('inferencechain1 entailments for sparse: ', self.inferencechain1_entailments_num)
print('inferencechain2 entailments for sparse: ', self.inferencechain2_entailments_num)
print('inferencechain3 entailments for sparse: ', self.inferencechain3_entailments_num)
print('inferencechain4 entailments for sparse: ', self.inferencechain4_entailments_num)
print("finish generate axioms entailments for sparse")
if dump:
pickle.dump(self.reflexive_entailments, open(os.path.join(self.axiom_dir, 'reflexive_entailments'), 'wb'))
pickle.dump(self.symmetric_entailments, open(os.path.join(self.axiom_dir, 'symmetric_entailments'), 'wb'))
pickle.dump(self.transitive_entailments, open(os.path.join(self.axiom_dir, 'transitive_entailments'), 'wb'))
pickle.dump(self.inverse_entailments, open(os.path.join(self.axiom_dir, 'inverse_entailments'), 'wb'))
pickle.dump(self.subproperty_entailments, open(os.path.join(self.axiom_dir, 'subproperty_entailments'), 'wb'))
#pickle.dump(self.inferencechain_entailments, open(os.path.join(self.axiom_dir, 'inferencechain_entailments'), 'wb'))
pickle.dump(self.equivalent_entailments, open(os.path.join(self.axiom_dir, 'equivalent_entailments'), 'wb'))
pickle.dump(self.inferencechain1_entailments,
open(os.path.join(self.axiom_dir, 'inferencechain1_entailments'), 'wb'))
pickle.dump(self.inferencechain2_entailments,
open(os.path.join(self.axiom_dir, 'inferencechain2_entailments'), 'wb'))
pickle.dump(self.inferencechain3_entailments,
open(os.path.join(self.axiom_dir, 'inferencechain3_entailments'), 'wb'))
pickle.dump(self.inferencechain4_entailments,
open(os.path.join(self.axiom_dir, 'inferencechain4_entailments'), 'wb'))
print("finish dump axioms entialments")
if load:
print("load refexive entailments...")
self.reflexive_entailments = pickle.load(open(os.path.join(self.axiom_dir, 'reflexive_entailments'), 'rb'))
print(self.reflexive_entailments)
print('load symmetric entailments...')
self.symmetric_entailments = pickle.load(open(os.path.join(self.axiom_dir, 'symmetric_entailments'), 'rb'))
print("load transitive entialments... ")
self.transitive_entailments = pickle.load(open(os.path.join(self.axiom_dir, 'transitive_entailments'), 'rb'))
print("load inverse entailments...")
self.inverse_entailments = pickle.load(open(os.path.join(self.axiom_dir, 'inverse_entailments'), 'rb'))
print("load subproperty entailments...")
self.subproperty_entailments = pickle.load(open(os.path.join(self.axiom_dir, 'subproperty_entailments'), 'rb'))
#print("load inferencechain entailments...")
#self.inferencechain_entailments = pickle.load(open(os.path.join(self.axiom_dir, 'inferencechain_entailments'), 'rb'))
print("load equivalent entialments...")
self.equivalent_entailments = pickle.load(open(os.path.join(self.axiom_dir, 'equivalent_entailments'), 'rb'))
print("load inferencechain1 entailments...")
self.inferencechain1_entailments = pickle.load(
open(os.path.join(self.axiom_dir, 'inferencechain1_entailments'), 'rb'))
print("load inferencechain2 entailments...")
self.inferencechain2_entailments = pickle.load(
open(os.path.join(self.axiom_dir, 'inferencechain2_entailments'), 'rb'))
print("load inferencechain3 entailments...")
self.inferencechain3_entailments = pickle.load(
open(os.path.join(self.axiom_dir, 'inferencechain3_entailments'), 'rb'))
print("load inferencechain4 entailments...")
self.inferencechain4_entailments = pickle.load(
open(os.path.join(self.axiom_dir, 'inferencechain4_entailments'), 'rb'))
print("finish load axioms entailments")
def _materialize_sparse(self, axioms, type=None, sparse = False):
inference = []
# axiom2entailment is a dict
# with the all axioms in the axiom pool as keys
# and all the entailments for each axiom as values
axiom_list = axioms
length = len(axioms)
max_entailments = self.max_entialments
num = 0
if length == 0:
if type == 'reflexive':
np.reshape(inference, [-1, 3])
elif type == 'symmetric' or type =='inverse' or type =='equivalent' or type =='subproperty':
np.reshape(inference, [-1, 6])
elif type=='transitive' or type=='inferencechain':
np.reshape(inference, [-1, 9])
else:
raise NotImplementedError
return inference, num
if type == 'reflexive':
for axiom in axiom_list:
axiom_key =tuple(axiom)
r = axiom[0]
inference_tmp = []
for (h,t) in self.r_ht[r]:
# filter the axiom with too much entailments
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 2])
break
if h != t and self.entity2sparsity[h]>self.sparsity:
num += 1
inference_tmp.append([h,r,h])
for entailment in inference_tmp:
self.reflexive2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'symmetric':
#self.symmetric2entailment = defaultdict(list)
for axiom in axiom_list:
axiom_key = tuple(axiom)
r = axiom[0]
inference_tmp = []
for (h,t) in self.r_ht[r]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 2])
break
if (t,h) not in self.r_ht[r] and (self.entity2sparsity[h]>self.sparsity or self.entity2sparsity[t]>self.sparsity):
num += 1
inference_tmp.append([h,r,t,t,r,h])
for entailment in inference_tmp:
self.symmetric2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'transitive':
#self.transitive2entailment = defaultdict(list)
for axiom in axiom_list:
axiom_key = tuple(axiom)
r = axiom[0]
inference_tmp = []
for (h,t) in self.r_ht[r]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
# (t,r,e) exist but (h,r,e) not exist and e!=h
for e in self.hr_t[(t,r)]- self.hr_t[(h,r)]:
if e != h and (self.entity2sparsity[h]>self.sparsity or self.entity2sparsity[e]>self.sparsity):
num += 1
inference_tmp.append([h,r,t,t,r,e,h,r,e])
for entailment in inference_tmp:
self.transitive2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inverse':
for axiom in axiom_list:
axiom_key = tuple(axiom)
r1,r2 = axiom
inference_tmp = []
for (h,t) in self.r_ht[r1]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 6])
break
if (t,h) not in self.r_ht[r2] and (self.entity2sparsity[h]>self.sparsity or self.entity2sparsity[t]>self.sparsity):
num += 1
inference_tmp.append([h,r1,t, t,r2,h])
#self.inverse2entailment[axiom_key].append([h,r1,t, t,r2,h])
for entailment in inference_tmp:
self.inverse2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'equivalent' or type =='subproperty':
for axiom in axiom_list:
axiom_key = tuple(axiom)
r1,r2 = axiom
inference_tmp = []
for (h,t) in self.r_ht[r1]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 6])
break
if (h,t) not in self.r_ht[r2] and (self.entity2sparsity[h]>self.sparsity or self.entity2sparsity[t]>self.sparsity):
num += 1
inference_tmp.append([h,r1,t, h,r2,t])
for entailment in inference_tmp:
self.equivalent2entailment[axiom_key].append(entailment)
self.subproperty2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain1':
self.inferencechain12entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
# print('%d/%d' % (i, length))
r1, r2, r3 = axiom
inference_tmp = []
for (e, h) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.hr_t[(e, r3)]:
if (h, t) not in self.r_ht[r1] and (
self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[e] > self.sparsity):
num += 1
inference_tmp.append([e, r2, h, e, r3, t, h, r1, t])
#self.inferencechain12entailment[axiom_key].append([[e, r2, h, e, r3, t, h, r1, t]])
for entailment in inference_tmp:
self.inferencechain12entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain2':
self.inferencechain22entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
# print('%d/%d' % (i, length))
r1, r2, r3 = axiom
inference_tmp = []
for (e, h) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.tr_h[(e, r3)]:
if (h, t) not in self.r_ht[r1] and (
self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[e] > self.sparsity):
num += 1
inference_tmp.append([e, r2, h, t, r3, e, h, r1, t])
#self.inferencechain22entailment[axiom_key].append([[e, r2, h, t, r3, e, h, r1, t]])
for entailment in inference_tmp:
self.inferencechain22entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain3':
self.inferencechain32entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
# print('%d/%d' % (i, length))
r1, r2, r3 = axiom
inference_tmp = []
for (h, e) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.hr_t[(e, r3)]:
if (h, t) not in self.r_ht[r1] and (
self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[e] > self.sparsity):
num += 1
inference_tmp.append([h, r2, e, e, r3, t, h, r1, t])
for entailment in inference_tmp:
self.inferencechain32entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain4':
self.inferencechain42entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
# print('%d/%d' % (i, length))
r1, r2, r3 = axiom
inference_tmp = []
for (h, e) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.tr_h[(e, r3)]:
if (h, t) not in self.r_ht[r1] and (
self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[e] > self.sparsity):
num += 1
inference_tmp.append([h, r2, e, t, r3, e, h, r1, t])
for entailment in inference_tmp:
self.inferencechain42entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
return inference, num
def _materialize(self, axioms, type=None, sparse=False):
inference = []
# axiom2entailment is a dict
# with the all axioms in the axiom pool as keys
# and all the entailments for each axiom as values
axiom_list = axioms
# print('axiom_list', axiom_list)
length = len(axioms)
max_entailments = 5000
num = 0
if length == 0:
if type == 'reflexive':
np.reshape(inference, [-1, 3])
elif type == 'symmetric' or type == 'inverse' or type == 'equivalent' or type == 'subproperty':
np.reshape(inference, [-1, 6])
elif type == 'transitive' or type == 'inferencechain':
np.reshape(inference, [-1, 9])
else:
raise NotImplementedError
return inference, num
if type == 'reflexive':
for axiom in axiom_list:
axiom_key = tuple(axiom)
r = axiom[0]
inference_tmp = []
for (h, t) in self.r_ht[r]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 2])
break
if h != t: #and self.entity2sparsity[h] > self.sparsity:
num += 1
inference_tmp.append([h, r, h])
for entailment in inference_tmp:
self.reflexive2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'symmetric':
for axiom in axiom_list:
axiom_key = tuple(axiom)
r = axiom[0]
inference_tmp = []
for (h, t) in self.r_ht[r]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 2])
break
if (t, h) not in self.r_ht[r]: #and (self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[t] > self.sparsity):
num += 1
inference_tmp.append([h, r, t, t, r, h])
for entailment in inference_tmp:
self.symmetric2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'transitive':
for axiom in axiom_list:
axiom_key = tuple(axiom)
r = axiom[0]
inference_tmp = []
for (h, t) in self.r_ht[r]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
# (t,r,e) exist but (h,r,e) not exist and e!=h
for e in self.hr_t[(t, r)] - self.hr_t[(h, r)]:
if e != h: #and (self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[e] > self.sparsity):
num += 1
inference_tmp.append([h, r, t, t, r, e, h, r, e])
for entailment in inference_tmp:
self.transitive2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inverse':
# self.inverse2entailment = defaultdict(list)
for axiom in axiom_list:
axiom_key = tuple(axiom)
r1, r2 = axiom
inference_tmp = []
for (h, t) in self.r_ht[r1]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 6])
break
if (t, h) not in self.r_ht[r2]: #and (self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[t] > self.sparsity):
num += 1
inference_tmp.append([h, r1, t, t, r2, h])
for entailment in inference_tmp:
self.inverse2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'equivalent' or type == 'subproperty':
for axiom in axiom_list:
axiom_key = tuple(axiom)
r1, r2 = axiom
inference_tmp = []
for (h, t) in self.r_ht[r1]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 6])
break
if (h, t) not in self.r_ht[r2]: #and (self.entity2sparsity[h] > self.sparsity or self.entity2sparsity[t] > self.sparsity):
num += 1
inference_tmp.append([h, r1, t, h, r2, t])
for entailment in inference_tmp:
self.equivalent2entailment[axiom_key].append(entailment)
self.subproperty2entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain1':
self.inferencechain12entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
# print('%d/%d' % (i, length))
r1, r2, r3 = axiom
inference_tmp = []
for (e, h) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.hr_t[(e, r3)]:
if (h, t) not in self.r_ht[r1]:
num += 1
inference_tmp.append([e, r2, h, e, r3, t, h, r1, t])
for entailment in inference_tmp:
self.inferencechain12entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain2':
self.inferencechain22entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
# print('%d/%d' % (i, length))
r1, r2, r3 = axiom
inference_tmp = []
for (e, h) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.tr_h[(e, r3)]:
if (h, t) not in self.r_ht[r1]:
num += 1
inference_tmp.append([e, r2, h, t, r3, e, h, r1, t])
for entailment in inference_tmp:
self.inferencechain22entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain3':
self.inferencechain32entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
# print('%d/%d' % (i, length))
r1, r2, r3 = axiom
inference_tmp = []
for (h, e) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.hr_t[(e, r3)]:
if (h, t) not in self.r_ht[r1]:
num += 1
inference_tmp.append([h, r2, e, e, r3, t, h, r1, t])
for entailment in inference_tmp:
self.inferencechain32entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
if type == 'inferencechain4':
self.inferencechain42entailment = defaultdict(list)
i = 0
for axiom in axiom_list:
axiom_key = tuple(axiom)
i += 1
r1, r2, r3 = axiom
inference_tmp = []
for (h, e) in self.r_ht[r2]:
if len(inference_tmp) > max_entailments:
inference_tmp = np.reshape([], [-1, 9])
break
for t in self.tr_h[(e, r3)]:
if (h, t) not in self.r_ht[r1]:
num += 1
inference_tmp.append([h, r2, e, t, r3, e, h, r1, t])
for entailment in inference_tmp:
self.inferencechain42entailment[axiom_key].append(entailment)
inference.append(inference_tmp)
return inference, num
def _init_valid_axioms(self):
# init valid axioms
self.valid_reflexive, self.valid_symmetric, self.valid_transitive,\
self.valid_inverse, self.valid_subproperty, self.valid_equivalent,\
self.valid_inferencechain1, self.valid_inferencechain2, \
self.valid_inferencechain3, self.valid_inferencechain4 = [[] for x in range(self.axiom_types)]
# init valid axiom entailments
self.valid_reflexive2entailment, self.valid_symmetric2entailment, self.valid_transitive2entailment, \
self.valid_inverse2entailment, self.valid_subproperty2entailment, self.valid_equivalent2entailment, \
self.valid_inferencechain12entailment, self.valid_inferencechain22entailment, \
self.valid_inferencechain32entailment, self.valid_inferencechain42entailment = [[] for x in range(self.axiom_types)]
# init valid axiom entailments probability
self.valid_reflexive_p, self.valid_symmetric_p, self.valid_transitive_p, \
self.valid_inverse_p, self.valid_subproperty_p, self.valid_equivalent_p, \
self.valid_inferencechain1_p, self.valid_inferencechain2_p,\
self.valid_inferencechain3_p, self.valid_inferencechain4_p= [[] for x in range(self.axiom_types)]
# init valid axiom batchsize
self.reflexive_batchsize = 1
self.symmetric_batchsize = 1
self.transitive_batchsize = 1
self.inverse_batchsize = 1
self.subproperty_batchsize = 1
self.equivalent_batchsize = 1
#self.inferencechain_batchsize = 1
self.inferencechain1_batchsize = 1
self.inferencechain2_batchsize = 1
self.inferencechain3_batchsize = 1
self.inferencechain4_batchsize = 1
# add the new triples from axioms to training triple
def update_train_triples(self, epoch=0, update_per = 10):
"""add the new triples from axioms to training triple
Args:
epoch (int, optional): epoch in training process. Defaults to 0.
update_per (int, optional): Defaults to 10.
Returns:
updated_train_data: training triple after adding the new triples from axioms
"""
reflexive_triples, symmetric_triples, transitive_triples, inverse_triples,\
equivalent_triples, subproperty_triples, inferencechain1_triples, \
inferencechain2_triples, inferencechain3_triples, inferencechain4_triples = [ np.reshape(np.asarray([]), [-1, 3]) for i in range(self.axiom_types)]
reflexive_p, symmetric_p, transitive_p, inverse_p, \
equivalent_p, subproperty_p, inferencechain1_p, \
inferencechain2_p, inferencechain3_p, inferencechain4_p = [np.reshape(np.asarray([]), [-1, 1]) for i in
range(self.axiom_types)]
updated_train_data=None
if epoch >= 5:
print("len(self.valid_reflexive2entailment):", len(self.valid_reflexive2entailment))
print("len(self.valid_symmetric2entailment):", len(self.valid_symmetric2entailment))
print("len(self.valid_transitive2entailment)", len(self.valid_transitive2entailment))
print("len(self.valid_inverse2entailment)", len(self.valid_inverse2entailment))
print("len(self.valid_equivalent2entailment)", len(self.valid_equivalent2entailment))
print("len(self.valid_subproperty2entailment)", len(self.valid_subproperty2entailment))
valid_reflexive2entailment, valid_symmetric2entailment, valid_transitive2entailment,\
valid_inverse2entailment, valid_equivalent2entailment, valid_subproperty2entailment, \
valid_inferencechain12entailment, valid_inferencechain22entailment,\
valid_inferencechain32entailment, valid_inferencechain42entailment = [[] for i in range(10)]
if len(self.valid_reflexive2entailment)>0:
valid_reflexive2entailment = np.reshape(np.asarray(self.valid_reflexive2entailment), [-1, 3])
reflexive_triples = np.asarray(valid_reflexive2entailment)[:, -3:]
reflexive_p = np.reshape(np.asarray(self.valid_reflexive_p),[-1,1])
if len(self.valid_symmetric2entailment) > 0:
valid_symmetric2entailment = np.reshape(np.asarray(self.valid_symmetric2entailment), [-1, 6])
symmetric_triples = np.asarray(valid_symmetric2entailment)[:, -3:]
symmetric_p = np.reshape(np.asarray(self.valid_symmetric_p),[-1,1])
if len(self.valid_transitive2entailment) > 0:
valid_transitive2entailment = np.reshape(np.asarray(self.valid_transitive2entailment), [-1, 9])
transitive_triples = np.asarray(valid_transitive2entailment)[:, -3:]
transitive_p = np.reshape(np.asarray(self.valid_transitive_p), [-1, 1])
if len(self.valid_inverse2entailment) > 0:
valid_inverse2entailment = np.reshape(np.asarray(self.valid_inverse2entailment), [-1, 6])
inverse_triples = np.asarray(valid_inverse2entailment)[:, -3:]
inverse_p = np.reshape(np.asarray(self.valid_inverse_p), [-1, 1])
if len(self.valid_equivalent2entailment) > 0:
valid_equivalent2entailment = np.reshape(np.asarray(self.valid_equivalent2entailment), [-1, 6])
equivalent_triples = np.asarray(valid_equivalent2entailment)[:, -3:]
equivalent_p = np.reshape(np.asarray(self.valid_equivalent_p), [-1, 1])
if len(self.valid_subproperty2entailment) > 0:
valid_subproperty2entailment = np.reshape(np.asarray(self.valid_subproperty2entailment), [-1, 6])
subproperty_triples = np.asarray(valid_subproperty2entailment)[:, -3:]
subproperty_p = np.reshape(np.asarray(self.valid_subproperty_p),[-1,1])
if len(self.valid_inferencechain12entailment) > 0:
valid_inferencechain12entailment = np.reshape(np.asarray(self.valid_inferencechain12entailment), [-1, 9])
inferencechain1_triples = np.asarray(valid_inferencechain12entailment)[:, -3:]
inferencechain1_p = np.reshape(np.asarray(self.valid_inferencechain1_p), [-1, 1])
if len(self.valid_inferencechain22entailment) > 0:
valid_inferencechain22entailment = np.reshape(np.asarray(self.valid_inferencechain22entailment), [-1, 9])
inferencechain2_triples = np.asarray(valid_inferencechain22entailment)[:, -3:]
inferencechain2_p = np.reshape(np.asarray(self.valid_inferencechain2_p), [-1, 1])
if len(self.valid_inferencechain32entailment) > 0:
valid_inferencechain32entailment = np.reshape(np.asarray(self.valid_inferencechain32entailment), [-1, 9])
inferencechain3_triples = np.asarray(valid_inferencechain32entailment)[:, -3:]
inferencechain3_p = np.reshape(np.asarray(self.valid_inferencechain3_p), [-1, 1])
if len(self.valid_inferencechain42entailment) > 0:
valid_inferencechain42entailment = np.reshape(np.asarray(self.valid_inferencechain42entailment), [-1, 9])
inferencechain4_triples = np.asarray(valid_inferencechain42entailment)[:, -3:]
inferencechain4_p = np.reshape(np.asarray(self.valid_inferencechain4_p), [-1, 1])
# pickle.dump(self.reflexive_entailments, open(os.path.join(self.axiom_dir, 'reflexive_entailments'), 'wb'))
# store all the injected triples
entailment_all = (valid_reflexive2entailment, valid_symmetric2entailment, valid_transitive2entailment,
valid_inverse2entailment, valid_equivalent2entailment, valid_subproperty2entailment,
valid_inferencechain12entailment,valid_inferencechain22entailment,
valid_inferencechain32entailment,valid_inferencechain42entailment)
pickle.dump(entailment_all, open(os.path.join(self.axiom_dir, 'valid_entailments.pickle'), 'wb'))
train_inject_triples = np.concatenate([reflexive_triples, symmetric_triples, transitive_triples, inverse_triples,
equivalent_triples, subproperty_triples, inferencechain1_triples,
inferencechain2_triples,inferencechain3_triples,inferencechain4_triples],
axis=0)
train_inject_triples_p = np.concatenate([reflexive_p,symmetric_p, transitive_p, inverse_p,
equivalent_p, subproperty_p, inferencechain1_p,
inferencechain2_p,inferencechain3_p,inferencechain4_p],
axis=0)
self.train_inject_triples = train_inject_triples
inject_labels = np.reshape(np.ones(len(train_inject_triples)), [-1, 1]) * self.axiom_weight * train_inject_triples_p
train_inject_ids_labels = np.concatenate([train_inject_triples, inject_labels],
axis=1)
self.train_ids_labels_inject = train_inject_triples#train_inject_ids_labels
print('num reflexive triples', len(reflexive_triples))
print('num symmetric triples', len(symmetric_triples))
print('num transitive triples', len(transitive_triples))
print('num inverse triples', len(inverse_triples))
print('num equivalent triples', len(equivalent_triples))
print('num subproperty triples', len(subproperty_triples))
print('num inferencechain1 triples', len(inferencechain1_triples))
print('num inferencechain2 triples', len(inferencechain2_triples))
print('num inferencechain3 triples', len(inferencechain3_triples))
print('num inferencechain4 triples', len(inferencechain4_triples))
#print(self.train_ids_labels_inject)
updated_train_data=self.generate_new_train_triples()
return updated_train_data
def split_embedding(self, embedding):
"""split embedding
Args:
embedding: embeddings need to be splited, shape:[None, dim].
Returns:
probability: The similrity between two matrices.
"""
# embedding: [None, dim]
assert self.args.emb_dim % 4 == 0
num_scalar = self.args.emb_dim // 2
num_block = self.args.emb_dim // 4
if len(embedding.size()) ==2:
embedding_scalar = embedding[:, 0:num_scalar]
embedding_x = embedding[:, num_scalar:-num_block]
embedding_y = embedding[:, -num_block:]
elif len(embedding.size()) ==3:
embedding_scalar = embedding[:, :, 0:num_scalar]
embedding_x = embedding[:, :, num_scalar:-num_block]
embedding_y = embedding[:, :, -num_block:]
else:
raise NotImplementedError
return embedding_scalar, embedding_x, embedding_y
# calculate the similrity between two matrices
# head: [?, dim]
# tail: [?, dim] or [1,dim]
def sim(self, head=None, tail=None, arity=None):
"""calculate the similrity between two matrices
Args:
head: embeddings of head, shape:[batch_size, dim].
tail: embeddings of tail, shape:[batch_size, dim] or [1, dim].
arity: 1,2 or 3
Returns:
probability: The similrity between two matrices.
"""
if arity == 1:
A_scalar, A_x, A_y = self.split_embedding(head)
elif arity == 2:
M1_scalar, M1_x, M1_y = self.split_embedding(head[0])
M2_scalar, M2_x, M2_y = self.split_embedding(head[1])
A_scalar= M1_scalar * M2_scalar
A_x = M1_x*M2_x - M1_y*M2_y
A_y = M1_x*M2_y + M1_y*M2_x
elif arity==3:
M1_scalar, M1_x, M1_y = self.split_embedding(head[0])
M2_scalar, M2_x, M2_y = self.split_embedding(head[1])
M3_scalar, M3_x, M3_y = self.split_embedding(head[2])
M1M2_scalar = M1_scalar * M2_scalar
M1M2_x = M1_x * M2_x - M1_y * M2_y
M1M2_y = M1_x * M2_y + M1_y * M2_x
A_scalar = M1M2_scalar * M3_scalar
A_x = M1M2_x * M3_x - M1M2_y * M3_y
A_y = M1M2_x * M3_y + M1M2_y * M3_x
else:
raise NotImplemented
B_scala, B_x, B_y = self.split_embedding(tail)
similarity = torch.cat([(A_scalar - B_scala)**2, (A_x - B_x)**2, (A_x - B_x)**2, (A_y - B_y)**2, (A_y - B_y)**2 ], dim=1)
similarity = torch.sqrt(torch.sum(similarity, dim=1))
#recale the probability
probability = (torch.max(similarity)-similarity)/(torch.max(similarity)-torch.min(similarity))
return probability
# generate a probality for each axiom in axiom pool
def run_axiom_probability(self):
"""this function is used to generate a probality for each axiom in axiom pool
"""
self.identity = torch.cat((torch.ones(int(self.args.emb_dim-self.args.emb_dim/4)),torch.zeros(int(self.args.emb_dim/4))),0).unsqueeze(0).cuda()
if len(self.axiompool_reflexive) != 0:
index = torch.LongTensor(self.axiompool_reflexive).cuda()
reflexive_embed = self.rel_emb(index)
reflexive_prob = self.sim(head=reflexive_embed[:, 0, :], tail=self.identity, arity=1)
else:
reflexive_prob = []
if len(self.axiompool_symmetric) != 0:
index = torch.LongTensor(self.axiompool_symmetric).cuda()
symmetric_embed = self.rel_emb(index)
symmetric_prob = self.sim(head=[symmetric_embed[:, 0, :], symmetric_embed[:, 0, :]], tail=self.identity, arity=2)
#symmetric_prob = sess.run(self.symmetric_probability, {self.symmetric_pool: self.axiompool_symmetric})
else:
symmetric_prob = []
if len(self.axiompool_transitive) != 0:
index = torch.LongTensor(self.axiompool_transitive).cuda()
transitive_embed = self.rel_emb(index)
transitive_prob = self.sim(head=[transitive_embed[:, 0, :], transitive_embed[:, 0, :]], tail=transitive_embed[:, 0, :], arity=2)
#transitive_prob = sess.run(self.transitive_probability, {self.transitive_pool: self.axiompool_transitive})
else:
transitive_prob = []
if len(self.axiompool_inverse) != 0:
index = torch.LongTensor(self.axiompool_inverse).cuda()
#inverse_prob = sess.run(self.inverse_probability, {self.inverse_pool: self.axiompool_inverse})
inverse_embed = self.rel_emb(index)
inverse_probability1 = self.sim(head=[inverse_embed[:, 0,:],inverse_embed[:, 1,:]], tail = self.identity, arity=2)
inverse_probability2 = self.sim(head=[inverse_embed[:,1,:],inverse_embed[:, 0,:]], tail=self.identity, arity=2)
inverse_prob = (inverse_probability1 + inverse_probability2)/2
else:
inverse_prob = []
if len(self.axiompool_subproperty) != 0:
index = torch.LongTensor(self.axiompool_subproperty).cuda()
#subproperty_prob = sess.run(self.subproperty_probability, {self.subproperty_pool: self.axiompool_subproperty})
subproperty_embed = self.rel_emb(index)
subproperty_prob = self.sim(head=subproperty_embed[:, 0,:], tail=subproperty_embed[:, 1, :], arity=1)
else:
subproperty_prob = []
if len(self.axiompool_equivalent) != 0:
index = torch.LongTensor(self.axiompool_equivalent).cuda()
#equivalent_prob = sess.run(self.equivalent_probability, {self.equivalent_pool: self.axiompool_equivalent})
equivalent_embed = self.rel_emb(index)
equivalent_prob = self.sim(head=equivalent_embed[:, 0,:], tail=equivalent_embed[:, 1,:], arity=1)
else:
equivalent_prob = []
if len(self.axiompool_inferencechain1) != 0:
index = torch.LongTensor(self.axiompool_inferencechain1).cuda()
inferencechain_embed = self.rel_emb(index)
inferencechain1_prob = self.sim(head=[inferencechain_embed[:, 1, :], inferencechain_embed[:, 0, :]], tail=inferencechain_embed[:, 2, :], arity=2)
else:
inferencechain1_prob = []
if len(self.axiompool_inferencechain2) != 0:
index = torch.LongTensor(self.axiompool_inferencechain2).cuda()
inferencechain_embed = self.rel_emb(index)
inferencechain2_prob = self.sim(head=[inferencechain_embed[:, 2, :], inferencechain_embed[:, 1, :], inferencechain_embed[:, 0, :]], tail=self.identity, arity=3)
else:
inferencechain2_prob = []
if len(self.axiompool_inferencechain3) != 0:
index = torch.LongTensor(self.axiompool_inferencechain3).cuda()
inferencechain_embed = self.rel_emb(index)
inferencechain3_prob = self.sim(head=[inferencechain_embed[:, 1, :], inferencechain_embed[:, 2, :]], tail=inferencechain_embed[:, 0, :], arity=2)
else:
inferencechain3_prob = []
if len(self.axiompool_inferencechain4) != 0:
index = torch.LongTensor(self.axiompool_inferencechain4).cuda()
inferencechain_embed = self.rel_emb(index)
inferencechain4_prob = self.sim(head=[inferencechain_embed[:, 0, :], inferencechain_embed[:, 2, :]],tail=inferencechain_embed[:, 1, :], arity=2)
else:
inferencechain4_prob = []
output = [reflexive_prob, symmetric_prob, transitive_prob, inverse_prob,
subproperty_prob,equivalent_prob,inferencechain1_prob, inferencechain2_prob,
inferencechain3_prob, inferencechain4_prob]
return output
def update_valid_axioms(self, input):
"""this function is used to select high probability axioms as valid axioms and record their scores
"""
#
#
valid_axioms = [self._select_high_probability(list(prob), axiom) for prob,axiom in zip(input, self.axiompool)]
self.valid_reflexive, self.valid_symmetric, self.valid_transitive, \
self.valid_inverse, self.valid_subproperty, self.valid_equivalent, \
self.valid_inferencechain1, self.valid_inferencechain2, \
self.valid_inferencechain3, self.valid_inferencechain4 = valid_axioms
# update the batchsize of axioms and entailments
self._reset_valid_axiom_entailment()
def _select_high_probability(self, prob, axiom):
# select the high probability axioms and recore their probabilities
valid_axiom = [[axiom[prob.index(p)],[p]] for p in prob if p>self.select_probability]
return valid_axiom
def _reset_valid_axiom_entailment(self):
self.infered_hr_t = defaultdict(set)
self.infered_tr_h = defaultdict(set)
self.valid_reflexive2entailment, self.valid_reflexive_p = \
self._valid_axiom2entailment(self.valid_reflexive, self.reflexive2entailment)
self.valid_symmetric2entailment, self.valid_symmetric_p = \
self._valid_axiom2entailment(self.valid_symmetric, self.symmetric2entailment)
self.valid_transitive2entailment, self.valid_transitive_p = \
self._valid_axiom2entailment(self.valid_transitive, self.transitive2entailment)
self.valid_inverse2entailment, self.valid_inverse_p = \
self._valid_axiom2entailment(self.valid_inverse, self.inverse2entailment)
self.valid_subproperty2entailment, self.valid_subproperty_p = \
self._valid_axiom2entailment(self.valid_subproperty, self.subproperty2entailment)
self.valid_equivalent2entailment, self.valid_equivalent_p = \
self._valid_axiom2entailment(self.valid_equivalent, self.equivalent2entailment)
self.valid_inferencechain12entailment, self.valid_inferencechain1_p = \
self._valid_axiom2entailment(self.valid_inferencechain1, self.inferencechain12entailment)
self.valid_inferencechain22entailment, self.valid_inferencechain2_p = \
self._valid_axiom2entailment(self.valid_inferencechain2, self.inferencechain22entailment)
self.valid_inferencechain32entailment, self.valid_inferencechain3_p = \
self._valid_axiom2entailment(self.valid_inferencechain3, self.inferencechain32entailment)
self.valid_inferencechain42entailment, self.valid_inferencechain4_p = \
self._valid_axiom2entailment(self.valid_inferencechain4, self.inferencechain42entailment)
def _valid_axiom2entailment(self, valid_axiom, axiom2entailment):
valid_axiom2entailment = []
valid_axiom_p = []
for axiom_p in valid_axiom:
axiom = tuple(axiom_p[0])
p = axiom_p[1]
for entailment in axiom2entailment[axiom]:
valid_axiom2entailment.append(entailment)
valid_axiom_p.append(p)
h,r,t = entailment[-3:]
self.infered_hr_t[(h,r)].add(t)
self.infered_tr_h[(t,r)].add(h)
return valid_axiom2entailment, valid_axiom_p
# updata new train triples:
def generate_new_train_triples(self):
"""The function is to updata new train triples and used after each training epoch end
Returns:
self.train_sampler.train_triples: The new training dataset (triples).
"""
self.train_sampler.train_triples = copy.deepcopy(self.train_triples_base)
print('generate_new_train_triples...')
#origin_triples = train_sampler.train_triples
inject_triples = self.train_ids_labels_inject
inject_num = int(self.inject_triple_percent*len(self.train_sampler.train_triples))
if len(inject_triples)> inject_num and inject_num >0:
np.random.shuffle(inject_triples)
inject_triples = inject_triples[:inject_num]
#train_triples = np.concatenate([origin_triples, inject_triples], axis=0)
print('当前train_sampler.train_triples数目',len(self.train_sampler.train_triples))
for h,r,t in inject_triples:
self.train_sampler.train_triples.append((int(h),int(r),int(t)))
print('添加后train_sampler.train_triples数目',len(self.train_sampler.train_triples))
return self.train_sampler.train_triples
def get_rule(self, rel2id):
"""Get rule for rule_base KGE models, such as ComplEx_NNE model.
Get rule and confidence from _cons.txt file.
Update:
(rule_p, rule_q): Rule.
confidence: The confidence of rule.
"""
rule_p, rule_q, confidence = [], [], []
with open(os.path.join(self.args.data_path, '_cons.txt')) as file:
lines = file.readlines()
for line in lines:
rule_str, trust = line.strip().split()
body, head = rule_str.split(',')
if '-' in body:
rule_p.append(rel2id[body[1:]])
rule_q.append(rel2id[head])
else:
rule_p.append(rel2id[body])
rule_q.append(rel2id[head])
confidence.append(float(trust))
rule_p = torch.tensor(rule_p).cuda()
rule_q = torch.tensor(rule_q).cuda()
confidence = torch.tensor(confidence).cuda()
return (rule_p, rule_q), confidence
"""def init_emb(self):
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim * 2)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim * 2)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())"""
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
"""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is DistMult.
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
h_scalar, h_x ,h_y = self.split_embedding(head_emb)
r_scalar, r_x, r_y = self.split_embedding(relation_emb)
t_scalar, t_x, t_y = self.split_embedding(tail_emb)
score_scalar = torch.sum(h_scalar * r_scalar * t_scalar, axis=-1)
score_block = torch.sum(h_x * r_x * t_x
+ h_x * r_y * t_y
+ h_y * r_x * t_y
- h_y * r_y * t_x, axis=-1)
score = score_scalar + score_block
return score
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
| 59,788 | 49.242857 | 265 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/RuleModel/model.py | import torch.nn as nn
import torch
class Model(nn.Module):
def __init__(self, args):
super(Model, self).__init__()
def init_emb(self):
raise NotImplementedError
def score_func(self, head_emb, relation_emb, tail_emb):
raise NotImplementedError
def forward(self, triples, negs, mode):
raise NotImplementedError
def tri2emb(self, triples, negs=None, mode="single"):
"""Get embedding of triples.
This function get the embeddings of head, relation, and tail
respectively. each embedding has three dimensions.
Args:
triples (tensor): This tensor save triples id, which dimension is
[triples number, 3].
negs (tensor, optional): This tenosr store the id of the entity to
be replaced, which has one dimension. when negs is None, it is
in the test/eval phase. Defaults to None.
mode (str, optional): This arg indicates that the negative entity
will replace the head or tail entity. when it is 'single', it
means that entity will not be replaced. Defaults to 'single'.
Returns:
head_emb: Head entity embedding.
relation_emb: Relation embedding.
tail_emb: Tail entity embedding.
"""
if mode == "single":
head_emb = self.ent_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
relation_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
tail_emb = self.ent_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
elif mode == "head-batch" or mode == "head_predict":
if negs is None: # 说明这个时候是在evluation,所以需要直接用所有的entity embedding
head_emb = self.ent_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
else:
head_emb = self.ent_emb(negs) # [bs, num_neg, dim]
relation_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
tail_emb = self.ent_emb(triples[:, 2]).unsqueeze(1) # [bs, 1, dim]
elif mode == "tail-batch" or mode == "tail_predict":
head_emb = self.ent_emb(triples[:, 0]).unsqueeze(1) # [bs, 1, dim]
relation_emb = self.rel_emb(triples[:, 1]).unsqueeze(1) # [bs, 1, dim]
if negs is None:
tail_emb = self.ent_emb.weight.data.unsqueeze(0) # [1, num_ent, dim]
else:
tail_emb = self.ent_emb(negs) # [bs, num_neg, dim]
return head_emb, relation_emb, tail_emb
| 2,572 | 40.5 | 85 | py |
NeuralKG | NeuralKG-main/src/neuralkg/model/RuleModel/RugE.py | import torch.nn as nn
import torch
from .model import Model
from IPython import embed
import pdb
class RugE(Model):
"""`Knowledge Graph Embedding with Iterative Guidance from Soft Rules`_ (RugE), which is a novel paradigm of KG embedding with iterative guidance from soft rules.
Attributes:
args: Model configuration parameters.
epsilon: Caculate embedding_range.
margin: Caculate embedding_range and loss.
embedding_range: Uniform distribution range.
ent_emb: Entity embedding, shape:[num_ent, emb_dim].
rel_emb: Relation_embedding, shape:[num_rel, emb_dim].
.. _Knowledge Graph Embedding with Iterative Guidance from Soft Rules: https://ojs.aaai.org/index.php/AAAI/article/view/11918
"""
def __init__(self, args):
super(RugE, self).__init__(args)
self.args = args
self.ent_emb = None
self.rel_emb = None
self.init_emb()
def init_emb(self):
"""Initialize the entity and relation embeddings in the form of a uniform distribution.
"""
self.epsilon = 2.0
self.margin = nn.Parameter(
torch.Tensor([self.args.margin]),
requires_grad=False
)
self.embedding_range = nn.Parameter(
torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
requires_grad=False
)
self.ent_emb = nn.Embedding(self.args.num_ent, self.args.emb_dim * 2)
self.rel_emb = nn.Embedding(self.args.num_rel, self.args.emb_dim * 2)
nn.init.uniform_(tensor=self.ent_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
nn.init.uniform_(tensor=self.rel_emb.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
def score_func(self, head_emb, relation_emb, tail_emb, mode):
"""Calculating the score of triples.
The formula for calculating the score is :math:`Re(< wr, es, e¯o >)`
Args:
head_emb: The head entity embedding.
relation_emb: The relation embedding.
tail_emb: The tail entity embedding.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
re_head, im_head = torch.chunk(head_emb, 2, dim=-1)
re_relation, im_relation = torch.chunk(relation_emb, 2, dim=-1)
re_tail, im_tail = torch.chunk(tail_emb, 2, dim=-1)
return torch.sum(
re_head * re_tail * re_relation
+ im_head * im_tail * re_relation
+ re_head * im_tail * im_relation
- im_head * re_tail * im_relation,
-1
)
def forward(self, triples, negs=None, mode='single'):
"""The functions used in the training phase
Args:
triples: The triples ids, as (h, r, t), shape:[batch_size, 3].
negs: Negative samples, defaults to None.
mode: Choose head-predict or tail-predict, Defaults to 'single'.
Returns:
score: The score of triples.
"""
head_emb, relation_emb, tail_emb = self.tri2emb(triples, negs, mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score
def get_score(self, batch, mode):
"""The functions used in the testing phase
Args:
batch: A batch of data.
mode: Choose head-predict or tail-predict.
Returns:
score: The score of triples.
"""
triples = batch["positive_sample"]
head_emb, relation_emb, tail_emb = self.tri2emb(triples, mode=mode)
score = self.score_func(head_emb, relation_emb, tail_emb, mode)
return score | 3,796 | 35.161905 | 166 | py |
NeuralKG | NeuralKG-main/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
import sphinx_rtd_theme
import doctest
import neuralkg
# -- Project information -----------------------------------------------------
project = 'NeuralKG'
copyright = '2022, zjukg'
author = 'chenxn'
# The full version, including alpha/beta/rc tags
release = '1.0.0'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinx.ext.todo',
'sphinx.ext.coverage',
# 'sphinx_copybutton',
'recommonmark',
'sphinx_markdown_tables',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
doctest_default_flags = doctest.NORMALIZE_WHITESPACE
autodoc_member_order = 'bysource'
intersphinx_mapping = {'python': ('https://docs.python.org/', None)}
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_css_files = ['css/custom.css']
# html_logo = './_static/logo.png'
html_context = {
"display_github": True, # Integrate GitHub
"github_user": "chenxn2020", # Username
"github_repo": "test_doc", # Repo name
"github_version": "main", # Version
"conf_py_path": "/docs/source/", # Path in the checkout to the docs root
} | 2,913 | 32.113636 | 79 | py |
cmm_ts | cmm_ts-main/main.py | from models.utils import *
from models.AdjLR import AdjLR
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.optimizers import Adam
from Data import Data
from keras.layers import *
from keras.models import *
from constants import *
# IAED import
from models.IAED.mIAED import mIAED
from models.IAED.sIAED import sIAED
from models.IAED.config import config as cIAED
from MyParser import *
if __name__ == "__main__":
parser = create_parser()
args = parser.parse_args()
MODEL = args.model
MODEL_FOLDER = args.model_dir
DATA = args.data
N_PAST = args.npast
N_FUTURE = args.nfuture
N_DELAY = args.ndelay
INITDEC = args.noinit_dec
BATCH_SIZE = args.batch_size
TRAIN_PERC, VAL_PERC, TEST_PERC = args.percs
TRAIN_PERC, VAL_PERC, TEST_PERC = float(TRAIN_PERC), float(VAL_PERC), float(TEST_PERC)
PATIENCE = args.patience
EPOCHS = args.epochs
LR = args.learning_rate
ADJLR = args.adjLR
TARGETVAR = args.target_var
df, features = get_df(DATA)
use_att, use_cm, cm, cm_trainable, use_constraint, constraint = cmd_attention_map(args.att, args.catt)
if MODEL == Models.sIAED.value:
if TARGETVAR == None: raise ValueError('for models sIAED, target_var needs to be specified')
# Single-output data initialization
d = Data(df, N_PAST, N_DELAY, N_FUTURE, TRAIN_PERC, VAL_PERC, TEST_PERC, target = TARGETVAR)
d.downsample(step = 10)
d.smooth(window_size = 50)
X_train, y_train, X_val, y_val, X_test, y_test = d.get_timeseries()
# IAED Model definition
config = init_config(cIAED, folder = MODEL_FOLDER, npast = N_PAST, nfuture = N_FUTURE,
ndelay = N_DELAY, nfeatures = N_FEATURES, features = features, initDEC = INITDEC,
use_att = use_att, use_cm = use_cm, cm = cm, cm_trainable = cm_trainable, use_constraint = use_constraint, constraint = constraint)
model = sIAED(df = df, config = config)
model.create_model(target_var = TARGETVAR, loss = 'mse', optimizer = Adam(LR), metrics = ['mse', 'mae', 'mape'])
elif MODEL == Models.mIAED.value:
# Multi-output data initialization
d = Data(df, N_PAST, N_DELAY, N_FUTURE, TRAIN_PERC, VAL_PERC, TEST_PERC)
d.downsample(step = 10)
d.smooth(window_size = 50)
X_train, y_train, X_val, y_val, X_test, y_test = d.get_timeseries()
# IAED Model definition
config = init_config(cIAED, folder = MODEL_FOLDER, npast = N_PAST, nfuture = N_FUTURE,
ndelay = N_DELAY, nfeatures = N_FEATURES, features = features, initDEC = INITDEC,
use_att = use_att, use_cm = use_cm, cm = cm, cm_trainable = cm_trainable, use_constraint = use_constraint, constraint = constraint)
model = mIAED(df = df, config = config)
model.create_model(loss = 'mse', optimizer = Adam(LR), metrics = ['mse', 'mae', 'mape'])
# Create .txt file with model parameters
print_init(MODEL, TARGETVAR, MODEL_FOLDER, N_PAST, N_FUTURE, N_DELAY, INITDEC, TRAIN_PERC, VAL_PERC, TEST_PERC,
use_att, use_cm, cm, cm_trainable, use_constraint, constraint , BATCH_SIZE, PATIENCE, EPOCHS, LR, ADJLR)
# Model fit
cbs = list()
cbs.append(EarlyStopping(patience = PATIENCE))
cbs.append(ModelCheckpoint(RESULT_DIR + '/' + MODEL_FOLDER + '/', save_best_only = True))
if ADJLR is not None: cbs.append(AdjLR(model, int(ADJLR[0]), float(ADJLR[1]), bool(ADJLR[2]), 1))
model.fit(X = X_train, y = y_train, validation_data = (X_val, y_val), batch_size = BATCH_SIZE,
epochs = EPOCHS, callbacks = cbs)
# Save causal matrix
model.save_cmatrix()
# Model evaluation
model.MAE(X_test, y_test, d.scaler)
# Model predictions
model.predict(X_test, y_test, d.scaler) | 3,876 | 41.604396 | 160 | py |
cmm_ts | cmm_ts-main/main_bestparams.py | import pickle
from models.utils import *
from keras.optimizers import Adam
from Data import Data
from keras.layers import *
from keras.models import *
from constants import *
import pandas as pd
from kerashypetune import KerasGridSearch
from models.utils import Words as W
# IAED import
from models.IAED.mIAED import mIAED
from models.IAED.sIAED import sIAED
from models.IAED.config import config as cIAED
from MyParser import *
df, features = get_df(11)
parser = create_parser()
args = parser.parse_args()
# Parameters definition
MODEL = args.model
N_FUTURE = args.nfuture
N_PAST = args.npast
N_DELAY = 0
TRAIN_PERC, VAL_PERC, TEST_PERC = args.percs
MODEL_FOLDER = args.model_dir
TRAIN_AGENT = args.train_agent
df, features = get_df(TRAIN_AGENT)
if MODEL == Models.sIAED.value:
# Single-output data initialization
TARGETVAR = 'd_g'
d = Data(df, N_PAST, N_DELAY, N_FUTURE, TRAIN_PERC, VAL_PERC, TEST_PERC, target = TARGETVAR)
d.downsample(step = 10)
d.smooth(window_size = 50)
X_train, y_train, X_val, y_val, x_test, y_test = d.get_timeseries()
# IAED Model definition
config_grid = init_config(cIAED, folder = MODEL_FOLDER, npast = N_PAST, nfuture = N_FUTURE,
ndelay = N_DELAY, nfeatures = N_FEATURES, features = None, initDEC = False,
use_att = True, use_cm = True, cm = None, cm_trainable = True, use_constraint = True, constraint = [0.1, 0.2])
config_grid[W.ATTUNITS] = [128, 256, 512]
config_grid[W.ENCDECUNITS] = [64, 128, 256, 512]
config_grid[W.DECINIT] = True
config_grid["epochs"] = 25
config_grid["batch_size"] = 32
hypermodel = lambda x: sIAED(config = x).create_model(target_var = TARGETVAR, loss = 'mse', optimizer = Adam(0.0001),
metrics = ['mse', 'mae', 'mape'], searchBest = True)
elif MODEL == Models.mIAED.value:
# Multi-output data initialization
d = Data(df, N_PAST, N_DELAY, N_FUTURE, TRAIN_PERC, VAL_PERC, TEST_PERC)
d.downsample(step = 10)
d.smooth(window_size = 50)
X_train, y_train, X_val, y_val, x_test, y_test = d.get_timeseries()
# IAED Model definition
config_grid = init_config(cIAED, folder = MODEL_FOLDER, npast = N_PAST, nfuture = N_FUTURE,
ndelay = N_DELAY, nfeatures = N_FEATURES, features = None, initDEC = False,
use_att = True, use_cm = True, cm = None, cm_trainable = True, use_constraint = True, constraint = [0.1, 0.2])
config_grid[W.ATTUNITS] = [256, 300, 512]
config_grid[W.ENCDECUNITS] = [128, 256]
config_grid[W.DECINIT] = [False, True]
config_grid["epochs"] = 25
config_grid["batch_size"] = [64, 128, 256, 512]
hypermodel = lambda x: mIAED(config = x).create_model(loss = 'mse', optimizer = Adam(0.0001),
metrics = ['mse', 'mae', 'mape'], searchBest = True)
kgs = KerasGridSearch(hypermodel, config_grid, monitor = 'val_loss', greater_is_better = False, tuner_verbose = 1)
kgs.search(X_train, y_train, validation_data = (X_val, y_val), shuffle = False)
with open(RESULT_DIR + '/' + MODEL_FOLDER + '/best_param.pkl', 'rb') as pickle_file:
pickle.dump(kgs.best_params, pickle_file)
| 3,299 | 37.372093 | 140 | py |
cmm_ts | cmm_ts-main/models/MyModel.py | from abc import ABC, abstractmethod
import os
from constants import RESULT_DIR
import models.utils as utils
import models.Words as W
from keras.models import *
from matplotlib import pyplot as plt
import pickle
import numpy as np
from tqdm import tqdm
class MyModel(ABC):
def __init__(self, name, df, config : dict = None, folder : str = None):
"""
Constructur, specify config if you want to create a new model, while, set folder if you want to load a pre-existing model
Args:
name (str): model name
df (dataframe): dataset
config (dict): configuration file. Default None.
folder (str): model's name to load. Default None.
"""
self.name = name
self.df = df
self.predY = None
if config:
self.dir = config[W.FOLDER]
with open(self.model_dir + '/config.pkl', 'wb') as file_pi:
pickle.dump(config, file_pi)
utils.no_warning()
self.config = config
self.model : Model = None
if folder:
self.dir = folder
with open(self.model_dir + '/config.pkl', 'rb') as pickle_file:
self.config = pickle.load(pickle_file)
self.model : Model = load_model(self.model_dir)
@property
def model_dir(self):
model_dir = RESULT_DIR + "/" + self.dir
if not os.path.exists(model_dir):
os.makedirs(model_dir)
return model_dir
@property
def plot_dir(self):
plot_dir = self.model_dir + "/plots"
if not os.path.exists(plot_dir):
os.makedirs(plot_dir)
return plot_dir
@property
def pred_dir(self):
pred_dir = self.model_dir + "/predictions"
if not os.path.exists(pred_dir):
os.makedirs(pred_dir)
return pred_dir
@abstractmethod
def create_model(self) -> Model:
pass
def fit(self, X, y, validation_data, batch_size, epochs, callbacks = None):
"""
Fit wrapper
Args:
X (array): X training set
y (array): Y training set
validation_data (tuple): (x_val, y_val)
batch_size (int): batch size
epochs (int): # epochs
callbacks (list, optional): List of callbacks. Defaults to None.
"""
history = self.model.fit(x = X, y = y, batch_size = batch_size, epochs = epochs,
callbacks = callbacks, validation_data = validation_data, shuffle = False)
with open(self.model_dir + '/history.pkl', 'wb') as file_pi:
pickle.dump(history.history, file_pi)
self.plot_history(history)
def MAE(self, X, y, scaler, folder = None, show = False):
"""
Prediction evaluation through MAE
Args:
X (np.array): network input
y (np.array): actual output
scaler (scaler): scaler used for the scaling
folder (str, optional): saving folder. Defaults to None.
show (bool, optional): bit to show the plots. Defaults to False.
Returns:
np.array: mean absolute error
"""
print('\n##')
print('## Prediction evaluation through MAE')
print('##')
if folder is None:
folder = self.plot_dir
else:
if not os.path.exists(folder): os.makedirs(folder)
if self.predY is None: self.predY = self.model.predict(X)
if self.name is utils.Models.mIAED or self.name == utils.Models.mCNN or self.name == utils.Models.mT2V:
ae_shape = (y.shape[1], self.config[W.NFEATURES])
elif self.name is utils.Models.sIAED or self.name is utils.Models.sT2V or self.name is utils.Models.sCNN:
ae_shape = (y.shape[1], 1)
ae = np.zeros(shape = ae_shape)
if self.name is utils.Models.sIAED or self.name is utils.Models.sT2V or self.name is utils.Models.sCNN:
t_idx = self.config[W.FEATURES].index(self.target_var)
dummy_y = np.zeros(shape = (y.shape[1], 8))
for t in tqdm(range(len(y)), desc = 'Abs error'):
# Invert scaling actual
actualY_t = np.squeeze(y[t,:,:])
if self.name is utils.Models.mIAED or self.name == utils.Models.mCNN or self.name == utils.Models.mT2V:
actualY_t = scaler.inverse_transform(actualY_t)
elif self.name is utils.Models.sIAED or self.name is utils.Models.sT2V or self.name is utils.Models.sCNN:
dummy_y[:, t_idx] = actualY_t
actualY_t = scaler.inverse_transform(dummy_y)[:, t_idx]
actualY_t = np.reshape(actualY_t, (actualY_t.shape[0], 1))
# Invert scaling pred
predY_t = np.squeeze(self.predY[t,:,:])
if self.name is utils.Models.mIAED or self.name == utils.Models.mCNN or self.name == utils.Models.mT2V:
predY_t = scaler.inverse_transform(predY_t)
elif self.name is utils.Models.sIAED or self.name is utils.Models.sT2V or self.name is utils.Models.sCNN:
dummy_y[:, t_idx] = predY_t
predY_t = scaler.inverse_transform(dummy_y)[:, t_idx]
predY_t = np.reshape(predY_t, (predY_t.shape[0], 1))
ae = ae + abs(actualY_t - predY_t)
ae_mean = ae/len(y)
with open(self.model_dir + '/ae.npy', 'wb') as file:
np.save(file, ae_mean)
self.plot_MAE(ae_mean, folder = folder, show = show)
return ae_mean
def predict(self, X, y, scaler, folder = None, plot = False):
"""
Predict output
Args:
X (np.array): network input
y (np.array): actual output
scaler (scaler): scaler used for the scaling
folder (str, optional): saving folder. Defaults to None.
plot (bool, optional): bit to plot the prediction. Defaults to False.
"""
print('\n##')
print('## Predictions')
print('##')
if folder is None:
folder = self.pred_dir
else:
if not os.path.exists(folder): os.makedirs(folder)
x_npy = list()
ya_npy = list()
yp_npy = list()
# Generate and save predictions
if self.predY is None: self.predY = self.model.predict(X)
if self.name is utils.Models.sIAED or self.name is utils.Models.sT2V or self.name is utils.Models.sCNN:
t_idx = self.config[W.FEATURES].index(self.target_var)
dummy_y = np.zeros(shape = (y.shape[1], 8))
for t in range(len(self.predY)):
# test X
X_t = np.squeeze(X[t,:,:])
X_t = scaler.inverse_transform(X_t)
x_npy.append(X_t)
# test y
Y_t = np.squeeze(y[t,:,:])
if self.name is utils.Models.mIAED or self.name == utils.Models.mCNN or self.name == utils.Models.mT2V:
Y_t = scaler.inverse_transform(Y_t)
elif self.name is utils.Models.sIAED or self.name == utils.Models.sCNN or self.name is utils.Models.sT2V:
dummy_y[:, t_idx] = Y_t
Y_t = scaler.inverse_transform(dummy_y)[:, t_idx]
ya_npy.append(Y_t)
# pred y
predY_t = np.squeeze(self.predY[t,:,:])
if self.name is utils.Models.mIAED or self.name == utils.Models.mCNN or self.name == utils.Models.mT2V:
predY_t = scaler.inverse_transform(predY_t)
elif self.name is utils.Models.sIAED or self.name == utils.Models.sCNN or self.name is utils.Models.sT2V:
dummy_y[:, t_idx] = predY_t
predY_t = scaler.inverse_transform(dummy_y)[:, t_idx]
yp_npy.append(predY_t)
with open(self.pred_dir + '/x_npy.npy', 'wb') as file:
np.save(file, x_npy)
with open(self.pred_dir + '/ya_npy.npy', 'wb') as file:
np.save(file, ya_npy)
with open(self.pred_dir + '/yp_npy.npy', 'wb') as file:
np.save(file, yp_npy)
target = self.target_var if self.name is utils.Models.sIAED or self.name == utils.Models.sCNN or self.name is utils.Models.sT2V else None
if plot: self.plot_prediction(x_npy, ya_npy, yp_npy, target_var = target)
def save_cmatrix(self):
"""
Save causal matrix after training
"""
if self.config[W.USECAUSAL]:
layers = self.model.layers
if self.name == utils.Models.mIAED or self.name == utils.Models.mCNN or self.name == utils.Models.mT2V:
ca_matrix = [layers[l].selfatt.Dalpha.bias.numpy() for l in range(1, len(layers) - 1)]
else:
ca_matrix = [layers[l].selfatt.Dalpha.bias.numpy() for l in range(1, len(layers))]
print(ca_matrix)
print(self.config[W.CMATRIX])
with open(self.model_dir + '/cmatrix.npy', 'wb') as file_pi:
np.save(file_pi, ca_matrix)
def plot_history(self, history):
"""
Plot history information
"""
if "loss" in history.history.keys():
plt.figure()
plt.plot(history.history["loss"], label = "Training loss")
plt.plot(history.history["val_loss"], label = "Validation loss")
plt.legend()
plt.grid()
plt.savefig(self.plot_dir + "/loss.png", dpi = 300)
plt.savefig(self.plot_dir + "/loss.eps", dpi = 300)
plt.close()
if "mae" in history.history.keys():
plt.figure()
plt.plot(history.history["mae"], label = "Training mae")
plt.plot(history.history["val_mae"], label = "Validation mae")
plt.legend()
plt.grid()
plt.savefig(self.plot_dir + "/mae.png", dpi = 300)
plt.savefig(self.plot_dir + "/mae.eps", dpi = 300)
plt.close()
if "mape" in history.history.keys():
plt.figure()
plt.plot(history.history["mape"], label = "Training mape")
plt.plot(history.history["val_mape"], label = "Validation mape")
plt.legend()
plt.grid()
plt.savefig(self.plot_dir + "/mape.png", dpi = 300)
plt.savefig(self.plot_dir + "/mape.eps", dpi = 300)
plt.close()
if "accuracy" in history.history.keys():
plt.figure()
plt.plot(history.history["accuracy"], label = "Training accuracy")
plt.plot(history.history["val_accuracy"], label = "Validation accuracy")
plt.legend()
plt.grid()
plt.savefig(self.plot_dir + "/accuracy.png", dpi = 300)
plt.savefig(self.plot_dir + "/accuracy.eps", dpi = 300)
plt.close()
def plot_MAE(self, ae, folder = None, show = False):
"""
Plot Mean Absolute Error for each variable involved in the prediction
Args:
ae (np.array): absolute error along horizon predition
folder (str, optional): saving folder. Defaults to None.
show (bool, optional): bit to show the plots. Defaults to False.
"""
if self.name is utils.Models.sIAED or self.name == utils.Models.sCNN or self.name is utils.Models.sT2V:
f = self.target_var
plt.figure()
plt.title(f + " NMAE " + str(round(ae.mean()/self.df[self.target_var].std(), 3)))
plt.plot(range(self.config[W.NFUTURE]), ae)
plt.ylabel("Abs error")
plt.xlabel("Time steps")
plt.grid()
if show:
plt.show()
else:
if folder is None: folder = self.plot_dir
plt.savefig(folder + "/" + f + "_nmae.png", dpi = 300)
plt.savefig(folder + "/" + f + "_nmae.eps", dpi = 300)
plt.close()
elif self.name is utils.Models.mIAED or self.name == utils.Models.mCNN or self.name == utils.Models.mT2V:
for f in range(self.config[W.NFEATURES]):
plt.figure()
plt.title(self.config[W.FEATURES][f] + " NMAE " + str(round(ae[:, f].mean()/self.df[self.config[W.FEATURES][f]].std(), 3)))
plt.plot(range(self.config[W.NFUTURE]), ae[:, f])
plt.ylabel("Abs error")
plt.xlabel("Time steps")
plt.grid()
if show:
plt.show()
else:
if folder is None: folder = self.plot_dir
plt.savefig(folder + "/" + str(self.config[W.FEATURES][f]) + "_nmae.png", dpi = 300)
plt.savefig(folder + "/" + str(self.config[W.FEATURES][f]) + "_nmae.eps", dpi = 300)
plt.close()
def plot_prediction(self, x, ya, yp, folder = None, target_var = None):
"""
Plot predicted output with observed input and actual output
Args:
x (np.array): observation timeseries
ya (np.array): actual output
yp (np.array): predicted output
folder (str, optional): saving folder. Defaults to None.
target_var (str, optional): target var to plot. Defaults to None.
"""
if folder is None: folder = self.pred_dir
plt.figure()
if target_var is None:
for f in self.config[W.FEATURES]:
# Create var folder
if not os.path.exists(folder + "/" + str(f) + "/"):
os.makedirs(folder + "/" + str(f) + "/")
f_idx = list(self.config[W.FEATURES]).index(f)
for t in tqdm(range(len(yp)), desc = f):
plt.plot(range(t, t + len(x[t][:, f_idx])), x[t][:, f_idx], color = 'green', label = "past")
plt.plot(range(t - 1 + len(x[t][:, f_idx]), t - 1 + len(x[t][:, f_idx]) + len(ya[t][:, f_idx])), ya[t][:, f_idx], color = 'blue', label = "actual")
plt.plot(range(t - 1 + len(x[t][:, f_idx]), t - 1 + len(x[t][:, f_idx]) + len(yp[t][:, f_idx])), yp[t][:, f_idx], color = 'red', label = "pred")
plt.title("Multi-step prediction - " + f)
plt.xlabel("step = 0.1s")
plt.ylabel(f)
plt.grid()
plt.legend()
plt.savefig(folder + "/" + str(f) + "/" + str(t) + ".png")
plt.clf()
else:
# Create var folder
if not os.path.exists(folder + "/" + str(target_var) + "/"):
os.makedirs(folder + "/" + str(target_var) + "/")
f_idx = list(self.config[W.FEATURES]).index(target_var)
for t in tqdm(range(len(yp)), desc = target_var):
plt.plot(range(t, t + len(x[t][:, f_idx])), x[t][:, f_idx], color = 'green', label = "past")
plt.plot(range(t - 1 + len(x[t][:, f_idx]), t - 1 + len(x[t][:, f_idx]) + len(ya[t])), ya[t], color = 'blue', label = "actual")
plt.plot(range(t - 1 + len(x[t][:, f_idx]), t - 1 + len(x[t][:, f_idx]) + len(yp[t])), yp[t], color = 'red', label = "pred")
plt.title("Multi-step prediction - " + target_var)
plt.xlabel("step = 0.1s")
plt.ylabel(target_var)
plt.grid()
plt.legend()
plt.savefig(folder + "/" + str(target_var) + "/" + str(t) + ".png")
plt.clf()
plt.close() | 15,549 | 40.246684 | 167 | py |
cmm_ts | cmm_ts-main/models/AdjLR.py | import keras
import tensorflow as tf
class AdjLR(keras.callbacks.Callback):
def __init__ (self, model, freq, factor, justOnce, verbose):
self.model = model
self.freq = freq
self.factor = factor
self.justOnce = justOnce
self.verbose = verbose
self.adj_epoch = freq
def on_epoch_end(self, epoch, logs=None):
if epoch + 1 == self.adj_epoch: # adjust the learning rate
lr=float(tf.keras.backend.get_value(self.model.optimizer.lr)) # get the current learning rate
new_lr=lr * self.factor
if not self.justOnce: self.adj_epoch += self.freq
if self.verbose == 1:
print('\n#')
print('# Learning rate updated :', new_lr)
print('#')
tf.keras.backend.set_value(self.model.optimizer.lr, new_lr) # set the learning rate in the optimizer | 905 | 38.391304 | 112 | py |
cmm_ts | cmm_ts-main/models/DenseDropout.py | from keras.layers import *
from keras.models import *
class DenseDropout(Layer):
def __init__(self, units, activation, dropout):
super(DenseDropout, self).__init__()
self.dbit = dropout != 0
self.dense = Dense(units, activation = activation)
if self.dbit: self.dropout = Dropout(dropout)
def call(self, x):
y = self.dense(x)
if self.dbit: y = self.dropout(y)
return y | 437 | 23.333333 | 58 | py |
cmm_ts | cmm_ts-main/models/Constraints.py | from keras.constraints import Constraint
import keras.backend as K
import numpy as np
class Between(Constraint):
def __init__(self, init_value, adj_thres):
self.adj_thres = adj_thres
# self.min_value = init_value - self.adj_thres
self.max_value = init_value + self.adj_thres
self.min_value = np.clip(init_value - self.adj_thres, 0, init_value)
# self.max_value = np.clip(init_value + self.adj_thres, init_value, 1)
def __call__(self, w):
return K.clip(w, self.min_value, self.max_value)
# class ConstantTensorInitializer(tf.keras.initializers.Initializer):
# """Initializes tensors to `t`."""
# def __init__(self, t):
# self.t = t
# def __call__(self, shape, dtype=None):
# return self.t
# def get_config(self):
# return {'t': self.t}
class Constant(Constraint):
"""Constrains tensors to `t`."""
def __init__(self, t):
self.t = t
def __call__(self, w):
return self.t
def get_config(self):
return {'t': self.t} | 1,019 | 24.5 | 79 | py |
cmm_ts | cmm_ts-main/models/IAED/IAED2.py | import numpy as np
from constants import CM_FPCMCI
from models.attention.SelfAttention import SelfAttention
from models.attention.InputAttention import InputAttention
from keras.layers import *
from keras.models import *
import tensorflow as tf
import models.Words as W
from models.DenseDropout import DenseDropout
class IAED(Layer):
def __init__(self, config, target_var, name = "IAED", searchBest = False):
super(IAED, self).__init__(name = name)
self.config = config
self.target_var = target_var
self.searchBest = searchBest
if self.config[W.USEATT]:
# Causal vector definition
if searchBest:
causal_vec = CM_FPCMCI[0, :] if self.config[W.USECAUSAL] else None
else:
causal_vec = np.array(self.config[W.CMATRIX][self.config[W.FEATURES].index(self.target_var), :]) if self.config[W.USECAUSAL] else None
# Self attention
self.selfatt = SelfAttention(self.config, causal_vec, name = self.target_var + '_selfatt')
# Input attention
self.inatt = InputAttention(self.config, name = self.target_var + '_inatt')
# Encoders
self.selfenc1 = LSTM(int(self.config[W.ENCDECUNITS]/2),
name = target_var + '_selfENC1',
return_sequences = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
self.selfenc2 = LSTM(int(self.config[W.ENCDECUNITS]/2),
name = target_var + '_selfENC2',
return_state = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
self.inenc1 = LSTM(int(self.config[W.ENCDECUNITS]/2),
name = target_var + '_inENC1',
return_sequences = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
self.inenc2 = LSTM(int(self.config[W.ENCDECUNITS]/2),
name = target_var + '_inENC2',
return_state = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
# Initialization
self.past_h = tf.Variable(tf.zeros([int(self.config[W.ENCDECUNITS]/2), 1]),
trainable = False,
shape = (int(self.config[W.ENCDECUNITS]/2), 1),
name = self.target_var + '_pastH')
self.past_c = tf.Variable(tf.zeros([int(self.config[W.ENCDECUNITS]/2), 1]),
trainable = False,
shape = (int(self.config[W.ENCDECUNITS]/2), 1),
name = self.target_var + '_pastC')
else:
self.enc1 = LSTM(self.config[W.ENCDECUNITS],
name = target_var + '_ENC1',
return_sequences = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
self.enc2 = LSTM(self.config[W.ENCDECUNITS],
name = target_var + '_ENC2',
return_state = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
self.repeat = RepeatVector(self.config[W.NFUTURE], name = self.target_var + '_REPEAT')
# Decoder
self.dec1 = LSTM(self.config[W.ENCDECUNITS], return_sequences = True, name = self.target_var + '_DEC1')
self.dec2 = LSTM(self.config[W.ENCDECUNITS], name = self.target_var + '_DEC2')
# Dense
# self.outdense1 = DenseDropout(self.config[W.NFUTURE] * 3, self.config[W.D1ACT], self.config[W.DRATE])
self.outdense = DenseDropout(self.config[W.NFUTURE] * 2, self.config[W.DACT], self.config[W.DRATE])
self.out = DenseDropout(self.config[W.NFUTURE], 'linear', 0)
def call(self, x):
if self.config[W.USEATT]:
# Attention
x_selfatt = self.selfatt(x)
# if not self.searchBest: x_selfatt = Dropout(self.config[W.DRATE])(x_selfatt)
x_inatt = self.inatt([x, self.past_h, self.past_c])
# if not self.searchBest: x_inatt = Dropout(self.config[W.DRATE])(x_inatt)
# Encoders
enc1_1 = self.selfenc1(x_selfatt)
enc2_1 = self.inenc1(x_inatt)
enc1_2, h1, c1 = self.selfenc2(enc1_1)
enc2_2, h2, c2 = self.inenc2(enc2_1)
self.past_h.assign(tf.expand_dims(h2[-1], -1))
self.past_c.assign(tf.expand_dims(c2[-1], -1))
x = concatenate([enc1_2, enc2_2])
if self.config[W.DECINIT]:
h = concatenate([h1, h2])
c = concatenate([c1, c2])
else:
x = self.enc1(x)
x, h, c = self.enc2(x)
repeat = self.repeat(x)
# Decoder
if self.config[W.DECINIT]:
y = self.dec1(repeat, initial_state = [h, c])
else:
y = self.dec1(repeat)
y = self.dec2(y)
if not self.searchBest: y = Dropout(self.config[W.DRATE])(y)
# y = self.outdense1(y)
y = self.outdense(y)
y = self.out(y)
y = tf.expand_dims(y, axis = -1)
return y | 5,627 | 44.756098 | 150 | py |
cmm_ts | cmm_ts-main/models/IAED/IAED.py | from matplotlib.pyplot import yscale
import numpy as np
from constants import CM_FPCMCI
from models.attention.SelfAttention import SelfAttention
from models.attention.InputAttention import InputAttention
from keras.layers import *
from keras.models import *
import tensorflow as tf
import models.Words as W
from models.DenseDropout import DenseDropout
class IAED(Layer):
def __init__(self, config, target_var, name = "IAED", searchBest = False):
super(IAED, self).__init__(name = name)
self.config = config
self.target_var = target_var
if self.config[W.USEATT]:
# Causal vector definition
if searchBest:
causal_vec = CM_FPCMCI[0, :] if self.config[W.USECAUSAL] else None
else:
causal_vec = np.array(self.config[W.CMATRIX][self.config[W.FEATURES].index(self.target_var), :]) if self.config[W.USECAUSAL] else None
# Self attention
self.selfatt = SelfAttention(self.config, causal_vec, name = self.target_var + '_selfatt')
# Input attention
self.inatt = InputAttention(self.config, name = self.target_var + '_inatt')
# Encoders
self.selfenc = LSTM(int(self.config[W.ENCDECUNITS]/2),
name = target_var + '_selfENC',
return_state = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
self.inenc = LSTM(int(self.config[W.ENCDECUNITS]/2),
name = target_var + '_inENC',
return_state = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
# Initialization
self.past_h = tf.Variable(tf.zeros([int(self.config[W.ENCDECUNITS]/2), 1]),
trainable = False,
shape = (int(self.config[W.ENCDECUNITS]/2), 1),
name = self.target_var + '_pastH')
self.past_c = tf.Variable(tf.zeros([int(self.config[W.ENCDECUNITS]/2), 1]),
trainable = False,
shape = (int(self.config[W.ENCDECUNITS]/2), 1),
name = self.target_var + '_pastC')
else:
self.enc = LSTM(self.config[W.ENCDECUNITS],
name = target_var + '_ENC',
return_state = True,
input_shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
self.repeat = RepeatVector(self.config[W.NFUTURE], name = self.target_var + '_REPEAT')
# Decoder
self.dec = LSTM(self.config[W.ENCDECUNITS], name = self.target_var + '_DEC')
# Dense
# self.outdense1 = DenseDropout(self.config[W.NFUTURE] * 3, self.config[W.D1ACT], self.config[W.DRATE])
self.outdense = DenseDropout(self.config[W.NFUTURE] * 2, self.config[W.DACT], self.config[W.DRATE])
self.out = DenseDropout(self.config[W.NFUTURE], 'linear', 0)
def call(self, x):
if self.config[W.USEATT]:
# Attention
x_selfatt = self.selfatt(x)
# x_selfatt = Dropout(self.config[W.DRATE])(x_selfatt)
x_inatt = self.inatt([x, self.past_h, self.past_c])
# x_inatt = Dropout(self.config[W.DRATE])(x_inatt)
# Encoders
enc1, h1, c1 = self.selfenc(x_selfatt)
enc2, h2, c2 = self.inenc(x_inatt)
self.past_h.assign(tf.expand_dims(h2[-1], -1))
self.past_c.assign(tf.expand_dims(c2[-1], -1))
x = concatenate([enc1, enc2])
if self.config[W.DECINIT]:
h = concatenate([h1, h2])
c = concatenate([c1, c2])
else:
x, h, c = self.enc(x)
repeat = self.repeat(x)
# Decoder
if self.config[W.DECINIT]:
y = self.dec(repeat, initial_state = [h, c])
else:
y = self.dec(repeat)
y = Dropout(self.config[W.DRATE])(y)
# y = self.outdense1(y)
y = self.outdense(y)
y = self.out(y)
y = tf.expand_dims(y, axis = -1)
return y | 4,444 | 40.542056 | 150 | py |
cmm_ts | cmm_ts-main/models/IAED/mIAED.py | from keras.layers import *
from keras.models import *
from keras.utils.vis_utils import plot_model
from constants import LIST_FEATURES
from models.MyModel import MyModel
from .IAED import IAED
from models.utils import Models
import models.Words as W
class mIAED(MyModel):
def __init__(self, df, config : dict = None, folder : str = None):
super().__init__(name = Models.mIAED, df = df, config = config, folder = folder)
def create_model(self, loss, optimizer, metrics, searchBest = False) -> Model:
inp = Input(shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
# Multihead
channels = list()
list_f = LIST_FEATURES if searchBest else self.config[W.FEATURES]
for var in list_f:
channels.append(IAED(self.config, var, name = var + "_IAED", searchBest = searchBest)(inp))
# Concatenation
y = concatenate(channels, axis = 2)
self.model = Model(inp, y)
self.model.compile(loss = loss, optimizer = optimizer, metrics = metrics)
self.model.summary()
# plot_model(self.model, to_file = self.model_dir + '/model_plot.png', show_shapes = True, show_layer_names = True, expand_nested = True)
return self.model | 1,267 | 36.294118 | 145 | py |
cmm_ts | cmm_ts-main/models/IAED/sIAED.py | from keras.layers import *
from keras.models import *
from keras.utils.vis_utils import plot_model
from models.utils import Models
from models.MyModel import MyModel
from .IAED2 import IAED
import models.Words as W
class sIAED(MyModel):
def __init__(self, df, config : dict = None, folder : str = None):
super().__init__(name = Models.sIAED, df = df, config = config, folder = folder)
def create_model(self, target_var, loss, optimizer, metrics, searchBest = False) -> Model:
self.target_var = target_var
inp = Input(shape = (self.config[W.NPAST], self.config[W.NFEATURES]))
x = IAED(self.config, target_var, name = target_var + "_IAED", searchBest = searchBest)(inp)
self.model = Model(inp, x)
self.model.compile(loss = loss, optimizer = optimizer, metrics = metrics)
self.model.summary()
# plot_model(self.model, to_file = self.model_dir + '/model_plot.png', show_shapes = True, show_layer_names = True, expand_nested = True)
return self.model | 1,051 | 39.461538 | 145 | py |
cmm_ts | cmm_ts-main/models/attention/InputAttention.py | import tensorflow as tf
import keras.backend as K
from keras.layers import *
class InputAttention(Layer):
def __init__(self, config, name = 'Attention'):
super(InputAttention, self).__init__(name = name)
self.config = config
def build(self, inputs):
# input_shape = batch x n_past x n_features
# T = window size : n_past
# n = number of driving series : n_features
# m = size of hidden state + cell state
input_shape = inputs[0]
T = input_shape[1]
n = input_shape[-1]
m = inputs[1][0] + inputs[2][0]
# Ve = T x 1
self.Ve = self.add_weight(name='Ve', shape=(T, 1),
initializer='random_normal',
trainable = True)
# We = T x 2m
self.We = self.add_weight(name = 'We', shape = (T, m),
initializer='random_normal',
trainable = True)
# Ue = T x T
self.Ue = self.add_weight(name = 'Ue', shape = (T, T),
initializer = 'random_normal',
trainable = True)
super(InputAttention, self).build(input_shape)
def call(self, inputs):
x, past_h, past_c = inputs
# Hidden and cell states concatenation
conc = K.concatenate([past_h, past_c], axis = 0)
conc = K.concatenate([conc for _ in range(x.shape[-1])], axis = 1)
# print("[ht-1, ct-1] shape", conc.shape)
# Attention weights pre softmax
e = tf.matmul(tf.transpose(self.Ve), K.tanh(tf.matmul(self.We, conc) + tf.matmul(self.Ue, x)))
# print("e shape", e.shape)
# Attention weights
alpha = tf.nn.softmax(e, axis = 2)
# print("alpha shape", alpha.shape)
# New state
x_tilde = tf.math.multiply(x, alpha)
# print("x_tilde shape", x_tilde.shape)
return x_tilde
| 1,990 | 31.639344 | 102 | py |
cmm_ts | cmm_ts-main/models/attention/SelfAttention.py | import tensorflow as tf
import numpy as np
from keras.layers import *
from models.Constraints import *
import models.Words as W
import keras.backend as K
class SelfAttention(Layer):
def __init__(self, config, causal_vec : np.array, name = 'Attention'):
super(SelfAttention, self).__init__(name = name)
self.config = config
self.causal_vec = causal_vec
self.Dg = Dense(self.config[W.ATTUNITS], activation = 'tanh', use_bias = True)
if self.config[W.USECAUSAL]:
if not self.config[W.CTRAINABLE]:
constraint = Constant(self.causal_vec)
elif self.config[W.CTRAINABLE] and not self.config[W.USECONSTRAINT]:
constraint = None
elif self.config[W.CTRAINABLE] and self.config[W.USECONSTRAINT]:
constraint = Between(self.causal_vec, self.config[W.TRAINTHRESH])
self.Dalpha = Dense(self.config[W.NFEATURES], activation = 'sigmoid',
use_bias = True,
bias_initializer = tf.initializers.Constant(self.causal_vec),
bias_constraint = constraint)
else:
self.Dalpha = Dense(self.config[W.NFEATURES], activation = 'sigmoid',
use_bias = True)
def call(self, x):
# Attention weights
g = self.Dg(x)
alpha = self.Dalpha(g)
# New state
x_tilde = tf.math.multiply(x, alpha)
return x_tilde | 1,508 | 38.710526 | 93 | py |
TreEnhance | TreEnhance-master/ptcolor.py | """Pytorch routines for color conversions and management.
All color arguments are given as 4-dimensional tensors representing
batch of images (Bx3xHxW). RGB values are supposed to be in the
range 0-1 (but values outside the range are tolerated).
Some examples:
>>> rgb = torch.tensor([0.8, 0.4, 0.2]).view(1, 3, 1, 1)
>>> lab = rgb2lab(rgb)
>>> print(lab.view(-1))
tensor([54.6400, 36.9148, 46.1227])
>>> rgb2 = lab2rgb(lab)
>>> print(rgb2.view(-1))
tensor([0.8000, 0.4000, 0.2000])
>>> rgb3 = torch.tensor([0.1333,0.0549,0.0392]).view(1, 3, 1, 1)
>>> lab3 = rgb2lab(rgb3)
>>> print(lab3.view(-1))
tensor([6.1062, 9.3593, 5.2129])
"""
import torch
def _t(data):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
return torch.tensor(data, requires_grad=False, dtype=torch.float32, device=device)
def _mul(coeffs, image):
coeffs = coeffs.to(image.device).view(3, 3, 1, 1)
return torch.nn.functional.conv2d(image, coeffs)
_RGB_TO_XYZ = {
"srgb": _t([[0.4124564, 0.3575761, 0.1804375],
[0.2126729, 0.7151522, 0.0721750],
[0.0193339, 0.1191920, 0.9503041]]),
"prophoto": _t([[0.7976749, 0.1351917, 0.0313534],
[0.2880402, 0.7118741, 0.0000857],
[0.0000000, 0.0000000, 0.8252100]])
}
_XYZ_TO_RGB = {
"srgb": _t([[3.2404542, -1.5371385, -0.4985314],
[-0.9692660, 1.8760108, 0.0415560],
[0.0556434, -0.2040259, 1.0572252]]),
"prophoto": _t([[1.3459433, -0.2556075, -0.0511118],
[-0.5445989, 1.5081673, 0.0205351],
[0.0000000, 0.0000000, 1.2118128]])
}
WHITE_POINTS = {item[0]: _t(item[1:]).view(1, 3, 1, 1) for item in [
("a", 1.0985, 1.0000, 0.3558),
("b", 0.9807, 1.0000, 1.1822),
("e", 1.0000, 1.0000, 1.0000),
("d50", 0.9642, 1.0000, 0.8251),
("d55", 0.9568, 1.0000, 0.9214),
("d65", 0.9504, 1.0000, 1.0888),
("icc", 0.9642, 1.0000, 0.8249)
]}
_EPSILON = 0.008856
_KAPPA = 903.3
_XYZ_TO_LAB = _t([[0.0, 116.0, 0.], [500.0, -500.0, 0.], [0.0, 200.0, -200.0]])
_LAB_TO_XYZ = _t([[1.0 / 116.0, 1.0 / 500.0, 0], [1.0 / 116.0, 0, 0], [1.0 / 116.0, 0, -1.0 / 200.0]])
_LAB_OFF = _t([16.0, 0.0, 0.0]).view(1, 3, 1, 1)
def apply_gamma(rgb, gamma="srgb"):
"""Linear to gamma rgb.
Assume that rgb values are in the [0, 1] range (but values outside are tolerated).
gamma can be "srgb", a real-valued exponent, or None.
>>> apply_gamma(torch.tensor([0.5, 0.4, 0.1]).view([1, 3, 1, 1]), 0.5).view(-1)
tensor([0.2500, 0.1600, 0.0100])
"""
if gamma == "srgb":
T = 0.0031308
rgb1 = torch.max(rgb, rgb.new_tensor(T))
return torch.where(rgb < T, 12.92 * rgb, (1.055 * torch.pow(torch.abs(rgb1), 1 / 2.4) - 0.055))
elif gamma is None:
return rgb
else:
return torch.pow(torch.max(rgb, rgb.new_tensor(0.0)), 1.0 / gamma)
def remove_gamma(rgb, gamma="srgb"):
"""Gamma to linear rgb.
Assume that rgb values are in the [0, 1] range (but values outside are tolerated).
gamma can be "srgb", a real-valued exponent, or None.
>>> remove_gamma(apply_gamma(torch.tensor([0.001, 0.3, 0.4])))
tensor([0.0010, 0.3000, 0.4000])
>>> remove_gamma(torch.tensor([0.5, 0.4, 0.1]).view([1, 3, 1, 1]), 2.0).view(-1)
tensor([0.2500, 0.1600, 0.0100])
"""
if gamma == "srgb":
T = 0.04045
rgb1 = torch.max(rgb, rgb.new_tensor(T))
return torch.where(rgb < T, rgb / 12.92, torch.pow(torch.abs(rgb1 + 0.055) / 1.055, 2.4))
elif gamma is None:
return rgb
else:
res = torch.pow(torch.max(rgb, rgb.new_tensor(0.0)), gamma) + \
torch.min(rgb, rgb.new_tensor(0.0))
return res
def rgb2xyz(rgb, gamma_correction="srgb", clip_rgb=False, space="srgb"):
"""sRGB to XYZ conversion.
rgb: Bx3xHxW
return: Bx3xHxW
>>> rgb2xyz(torch.tensor([0., 0., 0.]).view(1, 3, 1, 1)).view(-1)
tensor([0., 0., 0.])
>>> rgb2xyz(torch.tensor([0., 0.75, 0.]).view(1, 3, 1, 1)).view(-1)
tensor([0.1868, 0.3737, 0.0623])
>>> rgb2xyz(torch.tensor([0.4, 0.8, 0.2]).view(1, 3, 1, 1), gamma_correction=None).view(-1)
tensor([0.4871, 0.6716, 0.2931])
>>> rgb2xyz(torch.ones(2, 3, 4, 5)).size()
torch.Size([2, 3, 4, 5])
>>> xyz2rgb(torch.tensor([-1, 2., 0.]).view(1, 3, 1, 1), clip_rgb=True).view(-1)
tensor([0.0000, 1.0000, 0.0000])
>>> rgb2xyz(torch.tensor([0.4, 0.8, 0.2]).view(1, 3, 1, 1), gamma_correction=None, space='prophoto').view(-1)
tensor([0.4335, 0.6847, 0.1650])
"""
if clip_rgb:
rgb = torch.clamp(rgb, 0, 1)
rgb = remove_gamma(rgb, gamma_correction)
return _mul(_RGB_TO_XYZ[space], rgb)
def xyz2rgb(xyz, gamma_correction="srgb", clip_rgb=False, space="srgb"):
"""XYZ to sRGB conversion.
rgb: Bx3xHxW
return: Bx3xHxW
>>> xyz2rgb(torch.tensor([0., 0., 0.]).view(1, 3, 1, 1)).view(-1)
tensor([0., 0., 0.])
>>> xyz2rgb(torch.tensor([0.04, 0.02, 0.05]).view(1, 3, 1, 1)).view(-1)
tensor([0.3014, 0.0107, 0.2503])
>>> xyz2rgb(torch.ones(2, 3, 4, 5)).size()
torch.Size([2, 3, 4, 5])
>>> xyz2rgb(torch.tensor([-1, 2., 0.]).view(1, 3, 1, 1), clip_rgb=True).view(-1)
tensor([0.0000, 1.0000, 0.0000])
"""
rgb = _mul(_XYZ_TO_RGB[space], xyz)
if clip_rgb:
rgb = torch.clamp(rgb, 0, 1)
rgb = apply_gamma(rgb, gamma_correction)
return rgb
def _lab_f(x):
x1 = torch.max(x, x.new_tensor(_EPSILON))
return torch.where(x > _EPSILON, torch.pow(x1, 1.0 / 3), (_KAPPA * x + 16.0) / 116.0)
def xyz2lab(xyz, white_point="d65"):
"""XYZ to Lab conversion.
xyz: Bx3xHxW
return: Bx3xHxW
>>> xyz2lab(torch.tensor([0., 0., 0.]).view(1, 3, 1, 1)).view(-1)
tensor([0., 0., 0.])
>>> xyz2lab(torch.tensor([0.4, 0.2, 0.1]).view(1, 3, 1, 1)).view(-1)
tensor([51.8372, 82.3018, 26.7245])
>>> xyz2lab(torch.tensor([1., 1., 1.]).view(1, 3, 1, 1), white_point="e").view(-1)
tensor([100., 0., 0.])
"""
xyz = xyz / WHITE_POINTS[white_point].to(xyz.device)
f_xyz = _lab_f(xyz)
return _mul(_XYZ_TO_LAB, f_xyz) - _LAB_OFF.to(xyz.device)
def _inv_lab_f(x):
x3 = torch.max(x, x.new_tensor(_EPSILON)) ** 3
return torch.where(x3 > _EPSILON, x3, (116.0 * x - 16.0) / _KAPPA)
def lab2xyz(lab, white_point="d65"):
"""lab to XYZ conversion.
lab: Bx3xHxW
return: Bx3xHxW
>>> lab2xyz(torch.tensor([0., 0., 0.]).view(1, 3, 1, 1)).view(-1)
tensor([0., 0., 0.])
>>> lab2xyz(torch.tensor([100., 0., 0.]).view(1, 3, 1, 1), white_point="e").view(-1)
tensor([1., 1., 1.])
>>> lab2xyz(torch.tensor([50., 25., -30.]).view(1, 3, 1, 1)).view(-1)
tensor([0.2254, 0.1842, 0.4046])
"""
f_xyz = _mul(_LAB_TO_XYZ, lab + _LAB_OFF.to(lab.device))
xyz = _inv_lab_f(f_xyz)
return xyz * WHITE_POINTS[white_point].to(lab.device)
def rgb2lab(rgb, white_point="d65", gamma_correction="srgb", clip_rgb=False, space="srgb"):
"""sRGB to Lab conversion."""
lab = xyz2lab(rgb2xyz(rgb, gamma_correction, clip_rgb, space), white_point)
return lab
def lab2rgb(rgb, white_point="d65", gamma_correction="srgb", clip_rgb=False, space="srgb"):
"""Lab to sRGB conversion."""
return xyz2rgb(lab2xyz(rgb, white_point), gamma_correction, clip_rgb, space)
def lab2lch(lab):
"""Lab to LCH conversion."""
l = lab[:, 0, :, :]
c = torch.norm(lab[:, 1:, :, :], 2, 1)
h = torch.atan2(lab[:, 2, :, :], lab[:, 1, :, :])
h = h * (180 / 3.141592653589793)
h = torch.where(h >= 0, h, 360 + h)
return torch.stack([l, c, h], 1)
def rgb2lch(rgb, white_point="d65", gamma_correction="srgb", clip_rgb=False, space="srgb"):
"""sRGB to LCH conversion."""
lab = rgb2lab(rgb, white_point, gamma_correction, clip_rgb, space)
return lab2lch(lab)
def squared_deltaE(lab1, lab2):
"""Squared Delta E (CIE 1976).
lab1: Bx3xHxW
lab2: Bx3xHxW
return: Bx1xHxW
"""
return torch.sum((lab1 - lab2) ** 2, 1, keepdim=True)
def deltaE(lab1, lab2):
"""Delta E (CIE 1976).
lab1: Bx3xHxW
lab2: Bx3xHxW
return: Bx1xHxW
>>> lab1 = torch.tensor([100., 75., 50.]).view(1, 3, 1, 1)
>>> lab2 = torch.tensor([50., 50., 100.]).view(1, 3, 1, 1)
>>> deltaE(lab1, lab2).item()
75.0
"""
return torch.norm(lab1 - lab2, 2, 1, keepdim=True)
def squared_deltaE94(lab1, lab2):
"""Squared Delta E (CIE 1994).
Default parameters for the 'Graphic Art' version.
lab1: Bx3xHxW (reference color)
lab2: Bx3xHxW (other color)
return: Bx1xHxW
"""
diff_2 = (lab1 - lab2) ** 2
dl_2 = diff_2[:, 0:1, :, :]
c1 = torch.norm(lab1[:, 1:3, :, :], 2, 1, keepdim=True)
c2 = torch.norm(lab2[:, 1:3, :, :], 2, 1, keepdim=True)
dc_2 = (c1 - c2) ** 2
dab_2 = torch.sum(diff_2[:, 1:3, :, :], 1, keepdim=True)
dh_2 = torch.abs(dab_2 - dc_2)
de_2 = (dl_2 +
dc_2 / ((1 + 0.045 * c1) ** 2) +
dh_2 / ((1 + 0.015 * c1) ** 2))
return de_2
def deltaE94(lab1, lab2):
"""Delta E (CIE 1994).
Default parameters for the 'Graphic Art' version.
lab1: Bx3xHxW (reference color)
lab2: Bx3xHxW (other color)
return: Bx1xHxW
>>> lab1 = torch.tensor([100., 0., 0.]).view(1, 3, 1, 1)
>>> lab2 = torch.tensor([80., 0., 0.]).view(1, 3, 1, 1)
>>> deltaE94(lab1, lab2).item()
20.0
>>> lab1 = torch.tensor([100., 0., 0.]).view(1, 3, 1, 1)
>>> lab2 = torch.tensor([100., 20., 0.]).view(1, 3, 1, 1)
>>> deltaE94(lab1, lab2).item()
20.0
>>> lab1 = torch.tensor([100., 0., 10.]).view(1, 3, 1, 1)
>>> lab2 = torch.tensor([100., 0., 0.]).view(1, 3, 1, 1)
>>> round(deltaE94(lab1, lab2).item(), 4)
6.8966
>>> lab1 = torch.tensor([100., 75., 50.]).view(1, 3, 1, 1)
>>> lab2 = torch.tensor([50., 50., 100.]).view(1, 3, 1, 1)
>>> round(deltaE94(lab1, lab2).item(), 4)
54.7575
"""
sq = torch.nn.functional.relu(squared_deltaE94(lab1, lab2))
return torch.sqrt(sq)
def _check_conversion(**opts):
"""Verify the conversions on the RGB cube.
>>> _check_conversion(white_point='d65', gamma_correction='srgb', clip_rgb=False, space='srgb')
True
>>> _check_conversion(white_point='d50', gamma_correction=1.8, clip_rgb=False, space='prophoto')
True
"""
for r in range(0, 256, 15):
for g in range(0, 256, 15):
for b in range(0, 256, 15):
rgb = torch.tensor([r / 255.0, g / 255.0, b / 255.0]).view(1, 3, 1, 1)
lab = rgb2lab(rgb, **opts)
rgb2 = lab2rgb(lab, **opts)
de = deltaE(rgb, rgb2).item()
if de > 2e-4:
print("Conversion failed for RGB:", r, g, b, " deltaE", de)
return False
return True
def _check_gradients():
"""Verify some borderline gradient computation
>>> a = torch.zeros(1, 3, 1, 1, requires_grad=True)
>>> b = torch.zeros(1, 3, 1, 1, requires_grad=True)
>>> deltaE(a, b).backward()
>>> torch.any(torch.isnan(a.grad)).item()
0
>>> torch.any(torch.isnan(b.grad)).item()
0
>>> deltaE94(a, b).backward()
>>> torch.any(torch.isnan(a.grad)).item()
0
>>> torch.any(torch.isnan(b.grad)).item()
0
"""
return True
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
print("Test completed")
| 11,528 | 28.561538 | 113 | py |
TreEnhance | TreEnhance-master/data_Prep.py | import torch
import torch.utils
import torch.utils.data
import os
from torchvision import transforms
from random import random, sample
from PIL import Image
class Dataset_LOL(torch.utils.data.Dataset):
def __init__(self, raw_dir, exp_dir, subset_img=None, size=None, training=True):
self.raw_dir = raw_dir
self.exp_dir = exp_dir
self.subset_img = subset_img
self.size = size
if subset_img is not None:
self.listfile = sample(os.listdir(raw_dir), self.subset_img)
else:
self.listfile = os.listdir(raw_dir)
transformation = []
if training:
transformation.append(transforms.RandomHorizontalFlip(0.5))
if size is not None:
if random() > 0.5:
transformation.append(transforms.RandomResizedCrop((size, size)))
if size is not None:
transformation.append(transforms.Resize((size, size)))
self.transforms = transforms.Compose(transformation)
def __len__(self):
return len(self.listfile)
def __getitem__(self, index):
raw = transforms.ToTensor()(Image.open(self.raw_dir + self.listfile[index]))
expert = transforms.ToTensor()(Image.open(self.exp_dir + self.listfile[index]))
if raw.shape != expert.shape:
raw = transforms.Resize((self.size, self.size))(raw)
expert = transforms.Resize((self.size, self.size))(expert)
raw_exp = self.transforms(torch.stack([raw, expert]))
return raw_exp[0], raw_exp[1]
class LoadDataset(torch.utils.data.Dataset):
def __init__(self, raw_list, prob_list, win):
self.raw_list = raw_list
self.prob_list = prob_list
self.win = win
self.indices = []
def __len__(self):
return len(self.raw_list)
def __getitem__(self, index):
return self.raw_list[index], self.prob_list[index], torch.tensor(self.win[index])
| 1,956 | 32.169492 | 89 | py |
TreEnhance | TreEnhance-master/training.py | #!/usr/bin/env python3
import torch
import torch.utils
import torch.utils.data
from torch.utils.tensorboard import SummaryWriter
import collections
import numpy as np
import random
from data_Prep import LoadDataset, Dataset_LOL
import Actions as Actions
import warnings
import Network
import os
from matplotlib import pyplot as plt
from metrics import PSNR
import tqdm
import mcts
import argparse
import ptcolor
# !!! Constants to command-line arguments
MAX_DEPTH = 10
STOP_ACTION = 36
def parse_args():
parser = argparse.ArgumentParser("TreEnhance Hyperparams")
a = parser.add_argument
a("basedir", help="BASE DIRECTORY")
a("expname",help="Name of the run")
a("dropout", type=float, default=0.6, help="Dropout")
a("num_images", type=int, default=100, help="number of Images")
a("num_steps", type=int, default=1000, help="number of steps")
a("val_images", type=int, default=100, help="number of val images")
a("lr", type=float, default=0.001, help="learning rate")
a("size", type=int, default=256, help="image size")
a("num_gen", type=float, default=256, help="number of generation")
a("bs", type=int, default=256, help="batch size")
a("lambd", type=int, default=20, help="lambda in the loss function")
a("loops", type=int, default=5, help="number of optimization loops")
return parser.parse_args()
def init_weights(m):
if isinstance(m, torch.nn.Linear):
torch.nn.init.zeros_(m.weight)
torch.nn.init.zeros_(m.bias)
def add_plot(x, y, writer, step):
plt.scatter(x, y, edgecolors='b')
plt.xticks(np.arange(0, 1, 0.1))
plt.yticks(np.arange(0, 1, 0.1))
plt.xlabel('z')
plt.ylabel('y')
plt.title('outcome plot')
plt.grid(True)
writer.add_figure('Fig1', plt.gcf(), step)
TrainingSample = collections.namedtuple("TrainingSample", ["image", "return_", "probabilities"])
def compute_error(x, y):
labx = ptcolor.rgb2lab(x.unsqueeze(0))
laby = ptcolor.rgb2lab(y.unsqueeze(0))
de = ptcolor.deltaE94(labx, laby)
return de
def train(samples, res, optimizer, step, device, writer,
train_loss_history, train_L1_history, train_L2_history, args, lambd=10):
img = [s.image.unsqueeze(0) for s in samples]
prob = [s.probabilities for s in samples]
win = [s.return_ for s in samples]
DS = LoadDataset(img, torch.tensor(prob), win)
L = torch.utils.data.DataLoader(DS, batch_size=64, drop_last=False,
shuffle=True, num_workers=0)
res.train()
loops = args.loops
for loop in tqdm.tqdm(range(loops)):
z_x, v_y = [], []
for img_prob in L:
outcome = img_prob[2].to(device)
optimizer.zero_grad()
pred, v = res(img_prob[0][:, 0, :, :, :].to(device))
z_x += outcome.unsqueeze(1)
v_y += v
l1 = lambd * ((outcome.unsqueeze(1) - v) ** 2)
l2 = -(((torch.tensor(img_prob[1]).to(device) *
torch.log(torch.clamp(pred, min=1e-8))).sum(1)))
loss = ((l1 + l2.unsqueeze(1)).mean())
train_loss_history.append(loss.item())
train_L1_history.append(l1.mean().item())
train_L2_history.append(l2.mean().item())
loss.backward()
optimizer.step()
step += 1
if step % 10 == 0:
mean_loss = (sum(train_loss_history) /
max(1, len(train_loss_history)))
mean_L1 = sum(train_L1_history) / max(1, len(train_L1_history))
mean_L2 = sum(train_L2_history) / max(1, len(train_L2_history))
writer.add_scalar('Loss', mean_loss, step)
writer.add_scalar('L1', mean_L1, step)
writer.add_scalar('L2', mean_L2, step)
tqdm.tqdm.write(f"{step} {mean_L1} + {mean_L2} = {mean_loss}")
z_x = torch.cat(z_x, dim=0)
v_y = torch.cat(v_y, dim=0)
add_plot(z_x.cpu().detach().numpy(), v_y.cpu().detach().numpy(),
writer, step)
writer.add_scalar('Average return', z_x.mean().item(), step)
return res, step
class TrainingState:
def __init__(self, image, target, depth=0):
self.image = image
self.target = target
self.depth = depth
self.stopped = False
def transition(self, action):
new_image = Actions.select(self.image[None], action)[0]
new_state = type(self)(new_image, self.target, self.depth + 1)
new_state.stopped = (action == STOP_ACTION)
return new_state
def terminal(self):
return self.depth >= MAX_DEPTH or self.stopped
def compute_return(self):
if self.depth >= MAX_DEPTH:
return 0.0
elif self.stopped:
d = torch.dist(self.image, self.target, 2)
return torch.exp(-0.05 * d).item()
else:
raise ValueError("This state has not return!")
def play_tree(net, images, targets, device, steps):
actions = STOP_ACTION + 1
samples = []
def transition(states, actions):
return [s.transition(a) for s, a in zip(states, actions)]
def evaluation(states):
t = [s.terminal() for s in states]
batch = torch.stack([s.image for s in states], 0)
batch = batch.to(device)
with torch.no_grad():
pi, values = net(batch)
pi = pi.cpu().numpy()
if np.all([v.depth == 0 for v in states]):
eps = 0.25
pi = (1 - eps) * pi + eps * np.random.dirichlet([0.03 for i in range(STOP_ACTION + 1)],
pi.shape[0])
r = [(s.compute_return() if s.terminal() else v.item())
for (v, s) in zip(values, states)]
return t, r, pi
root_states = [TrainingState(im, tgt) for im, tgt in zip(images, targets)]
trees = mcts.MCTS(root_states, actions, transition, evaluation, exploration=8, initial_q=1.0)
states = []
probs = []
samples = []
while not np.all(trees.T[:trees.roots]):
trees.grow(steps)
states.append(trees.x[:trees.roots])
tau = 1.0
numerator = trees.N[:trees.roots, :] ** (1 / tau)
denominator = np.maximum(1, numerator.sum(1, keepdims=True))
probs.append(numerator / denominator)
actions = trees.sample_path()[1]
trees.descend_tree(actions[:, 0])
errors = []
psnrs = []
for r in range(trees.roots):
z = trees.R[r]
for s, p in zip(states, probs):
if s[r].terminal():
errors.append(torch.dist(s[r].image, s[r].target, 2).item())
psnrs.append(PSNR(s[r].image, s[r].target).item())
break
samples.append(TrainingSample(s[r].image, z, p[r, :]))
return samples, errors, psnrs
def generation(res, loader, steps, device):
samples = []
errors = []
psnrs = []
res.eval()
for images, targets in tqdm.tqdm(loader):
s, e, p = play_tree(res, images, targets, device, steps)
samples.extend(s)
errors.extend(e)
psnrs.extend(p)
return samples, np.mean(errors), np.mean(psnrs)
def validation(val_loader, res, device, writer, step):
res.eval()
loss = []
Psnr_list = []
val_grid = torch.empty((16, 3, 64, 64))
with torch.no_grad():
for img, exp in tqdm.tqdm(val_loader):
img = img.to(device)
exp = exp.to(device).unsqueeze(0)
for it in range(MAX_DEPTH):
with torch.no_grad():
prob, z = res(img)
action = torch.argmax(torch.tensor(prob))
if action == STOP_ACTION:
break
img = Actions.select(img, action).to('cuda')
loss.append(torch.dist(img, exp, 2))
Psnr_list.append(PSNR(img, exp))
if len(loss) % 1 == 0:
val_grid[int(len(loss) / 1) - 1] = img.squeeze()
vpsnr = sum(Psnr_list) / len(Psnr_list)
if writer is not None:
writer.add_images('VAL IMAGE', val_grid, step)
writer.add_scalar('L2 Validation Loss', sum(loss) / len(loss), step)
writer.add_scalar('PSNR Validation Loss', vpsnr, step)
print('L2 Validation Loss', (sum(loss) / len(loss)).item())
res.train()
return vpsnr
def main():
args = parse_args()
BASEDIR = args.basedir
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("Using device:", device)
warnings.filterwarnings("ignore")
raw_dir = BASEDIR+'/TRAIN/low/'
exp_dir = BASEDIR+'/TRAIN/high/'
val_dirR = BASEDIR+'/VAL/low/'
val_dirE = BASEDIR+'/VAL/high/'
expname = args.expname
weightfile = os.path.join("./", expname + ".pt")
tblocation = os.path.join("./tensor/", expname)
res = Network.ModifiedResnet(STOP_ACTION + 1, Dropout=args.dropout)
res.to(device)
images = args.num_images
steps = args.num_steps
val_images = args.val_images
param = res.parameters()
optimizer = torch.optim.AdamW(param, lr=args.lr)
dataset = Dataset_LOL(raw_dir, exp_dir, size=args.size, training=True)
val_set = Dataset_LOL(val_dirR, val_dirE, size=args.size, training=False)
indices = random.sample(list(range(len(val_set))), val_images)
val_set = torch.utils.data.Subset(val_set, indices)
val_loader = torch.utils.data.DataLoader(val_set, batch_size=1,
drop_last=False,
shuffle=True, num_workers=0)
writer = SummaryWriter(tblocation)
train_loss_history = collections.deque(maxlen=100)
train_L1_history = collections.deque(maxlen=100)
train_L2_history = collections.deque(maxlen=100)
numGeneration = args.num_gen
step = 0
max_psnr = 0.0
for gen_count in range(0, numGeneration + 1):
samples = []
indices = random.sample(list(range(len(dataset))), images)
subset = torch.utils.data.Subset(dataset, indices)
loader = torch.utils.data.DataLoader(subset, batch_size=args.bs, drop_last=False, shuffle=True, num_workers=0)
print('GENERATION', gen_count)
s, mean_error, psnr = generation(res, loader, steps, device)
writer.add_scalar('L2 train Loss', mean_error, gen_count)
writer.add_scalar('PSNR train Loss', psnr, gen_count)
print('TRAIN')
res, step = train(samples, res, optimizer, step, device,
writer, train_loss_history, train_L1_history,
train_L2_history,args, lambd=args.lambd)
torch.save(res.state_dict(), weightfile)
print('VALIDATION')
if gen_count % 1 == 0:
act_psnr = validation(val_loader, res, device, writer, gen_count)
if act_psnr >= max_psnr:
max_psnr = act_psnr
best_model = res.state_dict()
print('Best model updated', max_psnr)
torch.save(best_model, './' + expname + '_best_model.pt')
| 11,048 | 36.327703 | 118 | py |
TreEnhance | TreEnhance-master/Actions.py | import torch
import torch.utils
import torch.utils.data
from ColorAlgorithms import Gray_World, MaxRGB, saturation, hue
from torchvision import transforms
from PIL import ImageFilter
def select(img, act):
if act == 0:
return gamma_corr(img, 0.6, 0)
elif act == 1:
return gamma_corr(img, 0.6, 1)
elif act == 2:
return gamma_corr(img, 0.6, 2)
elif act == 3:
return gamma_corr(img, 1.1, 0)
elif act == 4:
return gamma_corr(img, 1.1, 1)
elif act == 5:
return gamma_corr(img, 1.1, 2)
elif act == 6:
return gamma_corr(img, 0.6)
elif act == 7:
return gamma_corr(img, 1.1)
elif act == 8:
return brightness(img, 0.1, 0)
elif act == 9:
return brightness(img, 0.1, 1)
elif act == 10:
return brightness(img, 0.1, 2)
elif act == 11:
return brightness(img, -0.1, 0)
elif act == 12:
return brightness(img, -0.1, 1)
elif act == 13:
return brightness(img, -0.1, 2)
elif act == 14:
return brightness(img, 0.1)
elif act == 15:
return brightness(img, -0.1)
elif act == 16:
return contrast(img, 0.8, 0)
elif act == 17:
return contrast(img, 0.8, 1)
elif act == 18:
return contrast(img, 0.8, 2)
elif act == 19:
return contrast(img, 2, 0)
elif act == 20:
return contrast(img, 2, 1)
elif act == 21:
return contrast(img, 2, 2)
elif act == 22:
return contrast(img, 0.8)
elif act == 23:
return contrast(img, 2)
elif act == 24:
return saturation(img, 0.5)
elif act == 25:
return saturation(img, 2)
elif act == 26:
return hue(img, 0.05)
elif act == 27:
return hue(img, -0.05)
elif act == 28:
return Gray_World(img)
elif act == 29:
return MaxRGB(img)
elif act == 30:
return apply_filter(img, ImageFilter.MedianFilter)
elif act == 31:
return apply_filter(img, ImageFilter.SHARPEN)
elif act == 32:
return apply_filter(img, ImageFilter.GaussianBlur)
elif act == 33:
return apply_filter(img, ImageFilter.EDGE_ENHANCE)
elif act == 34:
return apply_filter(img, ImageFilter.DETAIL)
elif act == 35:
return apply_filter(img, ImageFilter.SMOOTH)
elif act == 36:
return img
def gamma_corr(image, gamma, channel=None):
mod = image.clone()
if channel is not None:
mod[:, channel, :, :] = mod[:, channel, :, :] ** gamma
else:
mod = mod ** gamma
return mod
def brightness(image, bright, channel=None):
mod = image.clone()
if channel is not None:
mod[:, channel, :, :] = torch.clamp(mod[:, channel, :, :] + bright, 0, 1)
else:
mod = torch.clamp(mod + bright, 0, 1)
return mod
def apply_filter(image, filter):
mod = image.clone()
mod = (transforms.ToPILImage()(mod.squeeze(0)))
mod = transforms.ToTensor()(mod.filter(filter))
return mod.unsqueeze(0)
def contrast(image, alpha, channel=None):
mod = image.clone()
if channel is not None:
mod[:, channel, :, :] = torch.clamp(
torch.mean(mod[:, channel, :, :]) + alpha * (mod[:, channel, :, :] - torch.mean(mod[:, channel, :, :])), 0,
1)
else:
mod = torch.clamp(torch.mean(mod) + alpha * (mod - torch.mean(mod)), 0, 1)
return mod
| 3,418 | 27.491667 | 119 | py |
TreEnhance | TreEnhance-master/Network.py | import torch
from torchvision.models import resnet18
import torch.nn as nn
class ModifiedResnet(nn.Module):
def __init__(self, n_actions, Dropout=None):
super(ModifiedResnet, self).__init__()
self.model = resnet18(pretrained=False)
num_ftrs = self.model.fc.in_features
self.model.fc = nn.Identity()
self.fc1 = nn.Sequential(nn.Linear(num_ftrs, n_actions), nn.Softmax(dim=1))
if Dropout is not None:
self.fc2 = nn.Sequential(nn.Linear(num_ftrs, 256), nn.ReLU(), torch.nn.Dropout(Dropout), nn.Linear(256, 1),
nn.Sigmoid())
else:
self.fc2 = nn.Sequential(nn.Linear(num_ftrs, 256), nn.ReLU(), nn.Linear(256, 1), nn.Sigmoid())
def forward(self, x):
x = self.model(x)
out1 = self.fc1(x)
out2 = self.fc2(x)
return out1, out2
| 879 | 34.2 | 119 | py |
TreEnhance | TreEnhance-master/metrics.py | import torch
def PSNR(img, gt):
mseL = torch.nn.MSELoss()
mse = mseL(img, gt)
if mse != 0:
print(20 * torch.log10(1 / torch.sqrt(mse)))
return 20 * torch.log10(1 / torch.sqrt(mse))
return 20 * torch.log10(1 / torch.sqrt(torch.tensor(1e-9)))
| 275 | 24.090909 | 63 | py |
TreEnhance | TreEnhance-master/evaluation.py | #!/usr/bin/env python3
import warnings
import torch
import torch.utils
import torch.utils.data
import numpy as np
from data_Prep import Dataset_LOL
import Actions as Actions
import Network
import tqdm
import mcts
import argparse
from ptcolor import deltaE94, rgb2lab
warnings.filterwarnings("ignore")
NUM_ACTIONS = 37
MAX_DEPTH = 10
STOP_ACTION = NUM_ACTIONS - 1
IMAGE_SIZE = 256
def parse_args():
parser = argparse.ArgumentParser("Compute performace statistics.")
a = parser.add_argument
a("base_dir", help="dataset BASE Directory")
a("weight_file", help="File storing the weights of the CNN")
a("-s", "--steps", type=int, default=1000, help="Number of MCTS steps")
a("-e", "--exploration", type=float, default=10, help="Exploration coefficient")
a("-q", "--initial-q", type=float, default=0.5, help="Value for non-visited nodes")
a("-b", "--batch-size", type=int, default=30, help="Size of the mini batches")
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
a("-d", "--device", default=device, help="Computing device")
return parser.parse_args()
class EvalState:
def __init__(self, image, depth=0):
self.image = image
self.depth = depth
self.stopped = False
def transition(self, action):
new_image = Actions.select(self.image[None], action)[0]
new_state = type(self)(new_image, self.depth + 1)
new_state.stopped = (action == STOP_ACTION)
return new_state
def terminal(self):
return self.depth >= MAX_DEPTH or self.stopped
def play_tree(net, images, device, steps, initial_q, exploration):
actions = STOP_ACTION + 1
samples = []
def transition(states, actions):
return [s.transition(a) for s, a in zip(states, actions)]
def evaluation(states):
t = [s.terminal() for s in states]
batch = torch.stack([s.image for s in states], 0)
batch = batch.to(device)
with torch.no_grad():
pi, values = net(batch)
pi = pi.cpu().numpy()
values = values.squeeze(1).cpu().numpy()
return t, values, pi
root_states = [EvalState(im) for im in images]
trees = mcts.MCTS(root_states, actions, transition, evaluation,
exploration=exploration, initial_q=initial_q)
trees.grow(steps)
return trees
def mse_error(x, y):
diff = (x - y).reshape(x.size(0), -1)
return (diff ** 2).mean(1)
def average_psnr(mses):
mses = np.maximum(np.array(mses), 1e-6)
return (-10 * np.log10(mses)).mean()
def eval_closest_node(trees, targets):
mses = []
for n in range(trees.roots):
sub = trees.subtree(n)
images = torch.stack([s.image for s in trees.x[sub]], 0)
mse = mse_error(images, targets[n:n + 1]).min()
mses.append(mse)
return mses
def eval_most_valuable_node(trees, targets):
mses = []
def key(i):
return trees.R[i] if trees.T[i] else -1
for n in range(trees.roots):
sub = trees.subtree(n)
best = max(sub, key=key)
image = trees.x[best].image[None]
mse = mse_error(image, targets[n:n + 1])
mses.append(mse.item())
return mses
def evaluation(val_loader, res, args):
res.eval()
mses = []
closest_mses = []
valuable_mses = []
l2s = []
diz = {k: 0 for k in range(NUM_ACTIONS)}
diz[-1] = 0
for img, target, name in tqdm.tqdm(val_loader):
trees = play_tree(res, img, args.device, args.steps, args.initial_q, args.exploration)
paths, actions, depths = trees.most_visited()
leaves = paths[np.arange(depths.size), depths - 1]
enhanced = torch.stack([s.image for s in trees.x[leaves]], 0)
for i in range(enhanced.shape[0]):
act = actions[i]
for ac in act:
diz[ac] += 1
if ac == STOP_ACTION:
break
l2s.append(torch.dist(enhanced[i], target[i], 2))
mse = mse_error(enhanced, target)
mses.extend(mse.tolist())
deltae = deltaE94(rgb2lab(enhanced), rgb2lab(target))
l2s = (torch.stack(l2s, 0)).mean()
closest_mses.extend(eval_closest_node(trees, target))
valuable_mses.extend(eval_most_valuable_node(trees, target))
print(diz)
print(f"PSNR {average_psnr(mses):.3f}")
def main():
args = parse_args()
print('STEPS:', args.steps)
BASEDIR = args.basedir
raw_dir = BASEDIR+'TEST/low/'
exp_dir = BASEDIR+'TEST/high/'
res = Network.ModifiedResnet(NUM_ACTIONS, 0.0)
res.to(args.device)
print("Loading", args.weight_file)
weights = torch.load(args.weight_file, map_location=args.device)
res.load_state_dict(weights)
val_set = Dataset_LOL(raw_dir, exp_dir, size=IMAGE_SIZE, training=False)
val_loader = torch.utils.data.DataLoader(val_set,
batch_size=args.batch_size,
drop_last=False,
shuffle=False,
num_workers=1)
import time
start = time.time()
evaluation(val_loader, res, args)
print('ELAPSED:', time.time() - start)
if __name__ == '__main__':
import resource
GB = (2 ** 30)
mem = 30 * GB
resource.setrlimit(resource.RLIMIT_DATA, (mem, resource.RLIM_INFINITY))
main()
| 5,424 | 30.358382 | 94 | py |
TreEnhance | TreEnhance-master/ColorAlgorithms.py | import torch
from torchvision.transforms.functional import adjust_saturation, adjust_hue
def Gray_World(img):
m = img.mean(-2, True).mean(-1, True)
img = img / torch.clamp(m, min=1e-3)
ma = img.max(-1, True).values.max(-2, True).values.max(-3, True).values
return img / torch.clamp(ma, min=1e-3)
def MaxRGB(img):
maxs = img.max(-1, True).values.max(-2, True).values.max(-3, True).values
return img / torch.clamp(maxs, min=1e-3)
def saturation(img, param):
return adjust_saturation(img, param)
def hue(img, param):
return adjust_hue(img, param)
| 584 | 24.434783 | 77 | py |
deep-viz-keras | deep-viz-keras-master/saliency.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities to compute SaliencyMasks."""
import numpy as np
import keras.backend as K
class SaliencyMask(object):
"""Base class for saliency masks. Alone, this class doesn't do anything."""
def __init__(self, model, output_index=0):
"""Constructs a SaliencyMask.
Args:
model: the keras model used to make prediction
output_index: the index of the node in the last layer to take derivative on
"""
pass
def get_mask(self, input_image):
"""Returns an unsmoothed mask.
Args:
input_image: input image with shape (H, W, 3).
"""
pass
def get_smoothed_mask(self, input_image, stdev_spread=.2, nsamples=50):
"""Returns a mask that is smoothed with the SmoothGrad method.
Args:
input_image: input image with shape (H, W, 3).
"""
stdev = stdev_spread * (np.max(input_image) - np.min(input_image))
total_gradients = np.zeros_like(input_image)
for i in range(nsamples):
noise = np.random.normal(0, stdev, input_image.shape)
x_value_plus_noise = input_image + noise
total_gradients += self.get_mask(x_value_plus_noise)
return total_gradients / nsamples
class GradientSaliency(SaliencyMask):
r"""A SaliencyMask class that computes saliency masks with a gradient."""
def __init__(self, model, output_index=0):
# Define the function to compute the gradient
input_tensors = [model.input, # placeholder for input image tensor
K.learning_phase(), # placeholder for mode (train or test) tense
]
gradients = model.optimizer.get_gradients(model.output[0][output_index], model.input)
self.compute_gradients = K.function(inputs=input_tensors, outputs=gradients)
def get_mask(self, input_image):
"""Returns a vanilla gradient mask.
Args:
input_image: input image with shape (H, W, 3).
"""
# Execute the function to compute the gradient
x_value = np.expand_dims(input_image, axis=0)
gradients = self.compute_gradients([x_value, 0])[0][0]
return gradients
| 2,836 | 35.371795 | 93 | py |
deep-viz-keras | deep-viz-keras-master/guided_backprop.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilites to computed GuidedBackprop SaliencyMasks"""
from saliency import SaliencyMask
import numpy as np
import tensorflow as tf
import keras.backend as K
from keras.models import load_model
class GuidedBackprop(SaliencyMask):
"""A SaliencyMask class that computes saliency masks with GuidedBackProp.
This implementation copies the TensorFlow graph to a new graph with the ReLU
gradient overwritten as in the paper:
https://arxiv.org/abs/1412.6806
"""
GuidedReluRegistered = False
def __init__(self, model, output_index=0, custom_loss=None):
"""Constructs a GuidedBackprop SaliencyMask."""
if GuidedBackprop.GuidedReluRegistered is False:
@tf.RegisterGradient("GuidedRelu")
def _GuidedReluGrad(op, grad):
gate_g = tf.cast(grad > 0, "float32")
gate_y = tf.cast(op.outputs[0] > 0, "float32")
return gate_y * gate_g * grad
GuidedBackprop.GuidedReluRegistered = True
"""
Create a dummy session to set the learning phase to 0 (test mode in keras) without
inteferring with the session in the original keras model. This is a workaround
for the problem that tf.gradients returns error with keras models that contains
Dropout or BatchNormalization.
Basic Idea: save keras model => create new keras model with learning phase set to 0 => save
the tensorflow graph => create new tensorflow graph with ReLU replaced by GuiededReLU.
"""
model.save('/tmp/gb_keras.h5')
with tf.Graph().as_default():
with tf.Session().as_default():
K.set_learning_phase(0)
load_model('/tmp/gb_keras.h5', custom_objects={"custom_loss":custom_loss})
session = K.get_session()
tf.train.export_meta_graph()
saver = tf.train.Saver()
saver.save(session, '/tmp/guided_backprop_ckpt')
self.guided_graph = tf.Graph()
with self.guided_graph.as_default():
self.guided_sess = tf.Session(graph = self.guided_graph)
with self.guided_graph.gradient_override_map({'Relu': 'GuidedRelu'}):
saver = tf.train.import_meta_graph('/tmp/guided_backprop_ckpt.meta')
saver.restore(self.guided_sess, '/tmp/guided_backprop_ckpt')
self.imported_y = self.guided_graph.get_tensor_by_name(model.output.name)[0][output_index]
self.imported_x = self.guided_graph.get_tensor_by_name(model.input.name)
self.guided_grads_node = tf.gradients(self.imported_y, self.imported_x)
def get_mask(self, input_image):
"""Returns a GuidedBackprop mask."""
x_value = np.expand_dims(input_image, axis=0)
guided_feed_dict = {}
guided_feed_dict[self.imported_x] = x_value
gradients = self.guided_sess.run(self.guided_grads_node, feed_dict = guided_feed_dict)[0][0]
return gradients | 3,669 | 42.176471 | 106 | py |
deep-viz-keras | deep-viz-keras-master/visual_backprop.py | from saliency import SaliencyMask
import numpy as np
import keras.backend as K
from keras.layers import Input, Conv2DTranspose
from keras.models import Model
from keras.initializers import Ones, Zeros
class VisualBackprop(SaliencyMask):
"""A SaliencyMask class that computes saliency masks with VisualBackprop (https://arxiv.org/abs/1611.05418).
"""
def __init__(self, model, output_index=0):
"""Constructs a VisualProp SaliencyMask."""
inps = [model.input, K.learning_phase()] # input placeholder
outs = [layer.output for layer in model.layers] # all layer outputs
self.forward_pass = K.function(inps, outs) # evaluation function
self.model = model
def get_mask(self, input_image):
"""Returns a VisualBackprop mask."""
x_value = np.expand_dims(input_image, axis=0)
visual_bpr = None
layer_outs = self.forward_pass([x_value, 0])
for i in range(len(self.model.layers)-1, -1, -1):
if 'Conv2D' in str(type(self.model.layers[i])):
layer = np.mean(layer_outs[i], axis=3, keepdims=True)
layer = layer - np.min(layer)
layer = layer/(np.max(layer)-np.min(layer)+1e-6)
if visual_bpr is not None:
if visual_bpr.shape != layer.shape:
visual_bpr = self._deconv(visual_bpr)
visual_bpr = visual_bpr * layer
else:
visual_bpr = layer
return visual_bpr[0]
def _deconv(self, feature_map):
"""The deconvolution operation to upsample the average feature map downstream"""
x = Input(shape=(None, None, 1))
y = Conv2DTranspose(filters=1,
kernel_size=(3,3),
strides=(2,2),
padding='same',
kernel_initializer=Ones(),
bias_initializer=Zeros())(x)
deconv_model = Model(inputs=[x], outputs=[y])
inps = [deconv_model.input, K.learning_phase()] # input placeholder
outs = [deconv_model.layers[-1].output] # output placeholder
deconv_func = K.function(inps, outs) # evaluation function
return deconv_func([feature_map, 0])[0] | 2,406 | 40.5 | 112 | py |
lrec2020-coref | lrec2020-coref-master/scripts/bert_coref.py | import re
import os
from collections import Counter
import sys
import argparse
import pytorch_pretrained_bert
from pytorch_pretrained_bert.modeling import BertPreTrainedModel, BertModel, BertConfig
from pytorch_pretrained_bert import BertTokenizer
from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE
import torch
from torch import nn
import torch.optim as optim
import numpy as np
import random
import calc_coref_metrics
from torch.optim.lr_scheduler import ExponentialLR
random.seed(1)
np.random.seed(1)
torch.manual_seed(1)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
bert_dim=768
HIDDEN_DIM=200
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class LSTMTagger(BertPreTrainedModel):
def __init__(self, config, freeze_bert=False):
super(LSTMTagger, self).__init__(config)
hidden_dim=HIDDEN_DIM
self.hidden_dim=hidden_dim
self.tokenizer = BertTokenizer.from_pretrained('bert-base-cased', do_lower_case=False, do_basic_tokenize=False)
self.bert = BertModel.from_pretrained("bert-base-cased")
self.bert.eval()
if freeze_bert:
for param in self.bert.parameters():
param.requires_grad = False
self.distance_embeddings = nn.Embedding(11, 20)
self.sent_distance_embeddings = nn.Embedding(11, 20)
self.nested_embeddings = nn.Embedding(2, 20)
self.gender_embeddings = nn.Embedding(3, 20)
self.width_embeddings = nn.Embedding(12, 20)
self.quote_embeddings = nn.Embedding(3, 20)
self.lstm = nn.LSTM(4*bert_dim, hidden_dim, bidirectional=True, batch_first=True)
self.attention1 = nn.Linear(hidden_dim * 2, hidden_dim * 2)
self.attention2 = nn.Linear(hidden_dim * 2, 1)
self.mention_mention1 = nn.Linear( (3 * 2 * hidden_dim + 20 + 20) * 3 + 20 + 20 + 20 + 20, 150)
self.mention_mention2 = nn.Linear(150, 150)
self.mention_mention3 = nn.Linear(150, 1)
self.unary1 = nn.Linear(3 * 2 * hidden_dim + 20 + 20, 150)
self.unary2 = nn.Linear(150, 150)
self.unary3 = nn.Linear(150, 1)
self.drop_layer_020 = nn.Dropout(p=0.2)
self.tanh = nn.Tanh()
self.apply(self.init_bert_weights)
def get_mention_reps(self, input_ids=None, attention_mask=None, starts=None, ends=None, index=None, widths=None, quotes=None, matrix=None, transforms=None, doTrain=True):
starts=starts.to(device)
ends=ends.to(device)
widths=widths.to(device)
quotes=quotes.to(device)
input_ids = input_ids.to(device)
attention_mask = attention_mask.to(device)
transforms = transforms.to(device)
# matrix specifies which token positions (cols) are associated with which mention spans (row)
matrix=matrix.to(device) # num_sents x max_ents x max_words
# index specifies the location of the mentions in each sentence (which vary due to padding)
index=index.to(device)
sequence_outputs, pooled_outputs = self.bert(input_ids, token_type_ids=None, attention_mask=attention_mask)
all_layers = torch.cat((sequence_outputs[-1], sequence_outputs[-2], sequence_outputs[-3], sequence_outputs[-4]), 2)
embeds=torch.matmul(transforms,all_layers)
lstm_output, _ = self.lstm(embeds) # num_sents x max_words x 2 * hidden_dim
###########
# ATTENTION OVER MENTION
###########
attention_weights=self.attention2(self.tanh(self.attention1(lstm_output))) # num_sents x max_words x 1
attention_weights=torch.exp(attention_weights)
attx=attention_weights.squeeze(-1).unsqueeze(1).expand_as(matrix)
summer=attx*matrix
val=matrix*summer # num_sents x max_ents x max_words
val=val/torch.sum(1e-8+val,dim=2).unsqueeze(-1)
attended=torch.matmul(val, lstm_output) # num_sents x max_ents x 2 * hidden_dim
attended=attended.view(-1,2*self.hidden_dim)
lstm_output=lstm_output.contiguous()
position_output=lstm_output.view(-1, 2*self.hidden_dim)
# starts = token position of beginning of mention in flattened token list
start_output=torch.index_select(position_output, 0, starts)
# ends = token position of end of mention in flattened token list
end_output=torch.index_select(position_output, 0, ends)
# index = index of entity in flattened list of attended mention representations
mentions=torch.index_select(attended, 0, index)
width_embeds=self.width_embeddings(widths)
quote_embeds=self.quote_embeddings(quotes)
span_representation=torch.cat((start_output, end_output, mentions, width_embeds, quote_embeds), 1)
if doTrain:
return span_representation
else:
# detach tensor from computation graph at test time or memory will blow up
return span_representation.detach()
def forward(self, matrix, index, truth=None, names=None, token_positions=None, starts=None, ends=None, widths=None, input_ids=None, attention_mask=None, transforms=None, quotes=None):
doTrain=False
if truth is not None:
doTrain=True
zeroTensor=torch.FloatTensor([0]).to(device)
all_starts=None
all_ends=None
span_representation=None
all_all=[]
for b in range(len(matrix)):
span_reps=self.get_mention_reps(input_ids=input_ids[b], attention_mask=attention_mask[b], starts=starts[b], ends=ends[b], index=index[b], widths=widths[b], quotes=quotes[b], transforms=transforms[b], matrix=matrix[b], doTrain=doTrain)
if b == 0:
span_representation=span_reps
all_starts=starts[b]
all_ends=ends[b]
else:
span_representation=torch.cat((span_representation, span_reps), 0)
all_starts=torch.cat((all_starts, starts[b]), 0)
all_ends=torch.cat((all_ends, ends[b]), 0)
all_starts=all_starts.to(device)
all_ends=all_ends.to(device)
num_mentions,=all_starts.shape
running_loss=0
curid=-1
curid+=1
assignments=[]
seen={}
ch=0
token_positions=np.array(token_positions)
mention_index=np.arange(num_mentions)
unary_scores=self.unary3(self.tanh(self.drop_layer_020(self.unary2(self.tanh(self.drop_layer_020(self.unary1(span_representation)))))))
for i in range(num_mentions):
if i == 0:
# the first mention must start a new entity; this doesn't affect training (since the loss must be 0) so we can skip it.
if truth is None:
assignment=curid
curid+=1
assignments.append(assignment)
continue
MAX_PREVIOUS_MENTIONS=300
first=0
if truth is None:
if len(names[i]) == 1 and names[i][0].lower() in {"he", "his", "her", "she", "him", "they", "their", "them", "it", "himself", "its", "herself", "themselves"}:
MAX_PREVIOUS_MENTIONS=20
first=i-MAX_PREVIOUS_MENTIONS
if first < 0:
first=0
targets=span_representation[first:i]
cp=span_representation[i].expand_as(targets)
dists=[]
nesteds=[]
# get distance in mentions
distances=i-mention_index[first:i]
dists=vec_get_distance_bucket(distances)
dists=torch.LongTensor(dists).to(device)
distance_embeds=self.distance_embeddings(dists)
# get distance in sentences
sent_distances=token_positions[i]-token_positions[first:i]
sent_dists=vec_get_distance_bucket(sent_distances)
sent_dists=torch.LongTensor(sent_dists).to(device)
sent_distance_embeds=self.sent_distance_embeddings(sent_dists)
# is the current mention nested within a previous one?
res1=(all_starts[first:i] <= all_starts[i])
res2=(all_ends[i] <= all_ends[first:i])
nesteds=(res1*res2).long()
nesteds_embeds=self.nested_embeddings(nesteds)
res1=(all_starts[i] <= all_starts[first:i])
res2=(all_ends[first:i] <= all_ends[i])
nesteds=(res1*res2).long()
nesteds_embeds2=self.nested_embeddings(nesteds)
elementwise=cp*targets
concat=torch.cat((cp, targets, elementwise, distance_embeds, sent_distance_embeds, nesteds_embeds, nesteds_embeds2), 1)
preds=self.mention_mention3(self.tanh(self.drop_layer_020(self.mention_mention2(self.tanh(self.drop_layer_020(self.mention_mention1(concat)))))))
preds=preds + unary_scores[i] + unary_scores[first:i]
preds=preds.squeeze(-1)
if truth is not None:
# zero is the score for the dummy antecedent/new entity
preds=torch.cat((preds, zeroTensor))
golds_sum=0.
preds_sum=torch.logsumexp(preds, 0)
if len(truth[i]) == 1 and truth[i][-1] not in seen:
golds_sum=0.
seen[truth[i][-1]]=1
else:
golds=torch.index_select(preds, 0, torch.LongTensor(truth[i]).to(device))
golds_sum=torch.logsumexp(golds, 0)
# want to maximize (golds_sum-preds_sum), so minimize (preds_sum-golds_sum)
diff=preds_sum-golds_sum
running_loss+=diff
else:
assignment=None
if i == 0:
assignment=curid
curid+=1
else:
arg_sorts=torch.argsort(preds, descending=True)
k=0
while k < len(arg_sorts):
cand_idx=arg_sorts[k]
if preds[cand_idx] > 0:
cand_assignment=assignments[cand_idx+first]
assignment=cand_assignment
ch+=1
break
else:
assignment=curid
curid+=1
break
k+=1
assignments.append(assignment)
if truth is not None:
return running_loss
else:
return assignments
def get_mention_width_bucket(dist):
if dist < 10:
return dist + 1
return 11
def get_distance_bucket(dist):
if dist < 5:
return dist+1
elif dist >= 5 and dist <= 7:
return 6
elif dist >= 8 and dist <= 15:
return 7
elif dist >= 16 and dist <= 31:
return 8
elif dist >= 32 and dist <= 63:
return 9
return 10
vec_get_distance_bucket=np.vectorize(get_distance_bucket)
def get_inquote(start, end, sent):
inQuote=False
quotes=[]
for token in sent:
if token == "“" or token == "\"":
if inQuote == True:
inQuote=False
else:
inQuote=True
quotes.append(inQuote)
for i in range(start, end+1):
if quotes[i] == True:
return 1
return 0
def print_conll(name, sents, all_ents, assignments, out):
doc_id, part_id=name
mapper=[]
idd=0
for ent in all_ents:
mapper_e=[]
for e in ent:
mapper_e.append(idd)
idd+=1
mapper.append(mapper_e)
out.write("#begin document (%s); part %s\n" % (doc_id, part_id))
for s_idx, sent in enumerate(sents):
ents=all_ents[s_idx]
for w_idx, word in enumerate(sent):
if w_idx == 0 or w_idx == len(sent)-1:
continue
label=[]
for idx, (start, end) in enumerate(ents):
if start == w_idx and end == w_idx:
eid=assignments[mapper[s_idx][idx]]
label.append("(%s)" % eid)
elif start == w_idx:
eid=assignments[mapper[s_idx][idx]]
label.append("(%s" % eid)
elif end == w_idx:
eid=assignments[mapper[s_idx][idx]]
label.append("%s)" % eid)
out.write("%s\t%s\t%s\t%s\t_\t_\t_\t_\t_\t_\t_\t_\t%s\n" % (doc_id, part_id, w_idx-1, word, '|'.join(label)))
if len(sent) > 2:
out.write("\n")
out.write("#end document\n")
def test(model, test_all_docs, test_all_ents, test_all_named_ents, test_all_max_words, test_all_max_ents, test_doc_names, outfile, iterr, goldFile, path_to_scorer, doTest=False):
out=open(outfile, "w", encoding="utf-8")
# for each document
for idx in range(len(test_all_docs)):
d,p=test_doc_names[idx]
d=re.sub("/", "_", d)
test_doc=test_all_docs[idx]
test_ents=test_all_ents[idx]
max_words=test_all_max_words[idx]
max_ents=test_all_max_ents[idx]
names=[]
for n_idx, sent in enumerate(test_ents):
for ent in sent:
name=test_doc[n_idx][ent[0]:ent[1]+1]
names.append(name)
named_index={}
for sidx, sentence in enumerate(test_all_named_ents[idx]):
for start, end, _ in sentence:
named_index[(sidx, start, end)]=1
is_named=[]
for sidx, sentence in enumerate(test_all_ents[idx]):
for (start, end) in sentence:
if (sidx, start, end) in named_index:
is_named.append(1)
else:
is_named.append(0)
test_matrix, test_index, test_token_positions, test_ent_spans, test_starts, test_ends, test_widths, test_data, test_masks, test_transforms, test_quotes=get_data(model, test_doc, test_ents, max_ents, max_words)
assignments=model.forward(test_matrix, test_index, names=names, token_positions=test_token_positions, starts=test_starts, ends=test_ends, widths=test_widths, input_ids=test_data, attention_mask=test_masks, transforms=test_transforms, quotes=test_quotes)
print_conll(test_doc_names[idx], test_doc, test_ents, assignments, out)
out.close()
if doTest:
print("Goldfile: %s" % goldFile)
print("Predfile: %s" % outfile)
bcub_f, avg=calc_coref_metrics.get_conll(path_to_scorer, gold=goldFile, preds=outfile)
print("Iter %s, Average F1: %.3f, bcub F1: %s" % (iterr, avg, bcub_f))
sys.stdout.flush()
return avg
def get_matrix(list_of_entities, max_words, max_ents):
matrix=np.zeros((max_ents, max_words))
for idx, (start, end) in enumerate(list_of_entities):
for i in range(start, end+1):
matrix[idx,i]=1
return matrix
def get_data(model, doc, ents, max_ents, max_words):
batchsize=128
token_positions=[]
ent_spans=[]
persons=[]
inquotes=[]
batch_matrix=[]
matrix=[]
max_words_batch=[]
max_ents_batch=[]
max_w=1
max_e=1
sent_count=0
for idx, sent in enumerate(doc):
if len(sent) > max_w:
max_w=len(sent)
if len(ents[idx]) > max_e:
max_e = len(ents[idx])
sent_count+=1
if sent_count == batchsize:
max_words_batch.append(max_w)
max_ents_batch.append(max_e)
sent_count=0
max_w=0
max_e=0
if sent_count > 0:
max_words_batch.append(max_w)
max_ents_batch.append(max_e)
batch_count=0
for idx, sent in enumerate(doc):
matrix.append(get_matrix(ents[idx], max_words_batch[batch_count], max_ents_batch[batch_count]))
if len(matrix) == batchsize:
batch_matrix.append(torch.FloatTensor(matrix))
matrix=[]
batch_count+=1
if len(matrix) > 0:
batch_matrix.append(torch.FloatTensor(matrix))
batch_index=[]
batch_quotes=[]
batch_ent_spans=[]
index=[]
abs_pos=0
sent_count=0
b=0
for idx, sent in enumerate(ents):
for i in range(len(sent)):
index.append(sent_count*max_ents_batch[b] + i)
s,e=sent[i]
token_positions.append(idx)
ent_spans.append(e-s)
phrase=' '.join(doc[idx][s:e+1])
inquotes.append(get_inquote(s, e, doc[idx]))
abs_pos+=len(doc[idx])
sent_count+=1
if sent_count == batchsize:
batch_index.append(torch.LongTensor(index))
batch_quotes.append(torch.LongTensor(inquotes))
batch_ent_spans.append(ent_spans)
index=[]
inquotes=[]
ent_spans=[]
sent_count=0
b+=1
if sent_count > 0:
batch_index.append(torch.LongTensor(index))
batch_quotes.append(torch.LongTensor(inquotes))
batch_ent_spans.append(ent_spans)
all_masks=[]
all_transforms=[]
all_data=[]
batch_masks=[]
batch_transforms=[]
batch_data=[]
# get ids and pad sentence
for sent in doc:
tok_ids=[]
input_mask=[]
transform=[]
all_toks=[]
n=0
for idx, word in enumerate(sent):
toks=model.tokenizer.tokenize(word)
all_toks.append(toks)
n+=len(toks)
cur=0
for idx, word in enumerate(sent):
toks=all_toks[idx]
ind=list(np.zeros(n))
for j in range(cur,cur+len(toks)):
ind[j]=1./len(toks)
cur+=len(toks)
transform.append(ind)
tok_id=model.tokenizer.convert_tokens_to_ids(toks)
assert len(tok_id) == len(toks)
tok_ids.extend(tok_id)
input_mask.extend(np.ones(len(toks)))
token=word.lower()
all_masks.append(input_mask)
all_data.append(tok_ids)
all_transforms.append(transform)
if len(all_masks) == batchsize:
batch_masks.append(all_masks)
batch_data.append(all_data)
batch_transforms.append(all_transforms)
all_masks=[]
all_data=[]
all_transforms=[]
if len(all_masks) > 0:
batch_masks.append(all_masks)
batch_data.append(all_data)
batch_transforms.append(all_transforms)
for b in range(len(batch_data)):
max_len = max([len(sent) for sent in batch_data[b]])
for j in range(len(batch_data[b])):
blen=len(batch_data[b][j])
for k in range(blen, max_len):
batch_data[b][j].append(0)
batch_masks[b][j].append(0)
for z in range(len(batch_transforms[b][j])):
batch_transforms[b][j][z].append(0)
for k in range(len(batch_transforms[b][j]), max_words_batch[b]):
batch_transforms[b][j].append(np.zeros(max_len))
batch_data[b]=torch.LongTensor(batch_data[b])
batch_transforms[b]=torch.FloatTensor(batch_transforms[b])
batch_masks[b]=torch.FloatTensor(batch_masks[b])
tok_pos=0
starts=[]
ends=[]
widths=[]
batch_starts=[]
batch_ends=[]
batch_widths=[]
sent_count=0
b=0
for idx, sent in enumerate(ents):
for i in range(len(sent)):
s,e=sent[i]
starts.append(tok_pos+s)
ends.append(tok_pos+e)
widths.append(get_mention_width_bucket(e-s))
sent_count+=1
tok_pos+=max_words_batch[b]
if sent_count == batchsize:
batch_starts.append(torch.LongTensor(starts))
batch_ends.append(torch.LongTensor(ends))
batch_widths.append(torch.LongTensor(widths))
starts=[]
ends=[]
widths=[]
tok_pos=0
sent_count=0
b+=1
if sent_count > 0:
batch_starts.append(torch.LongTensor(starts))
batch_ends.append(torch.LongTensor(ends))
batch_widths.append(torch.LongTensor(widths))
return batch_matrix, batch_index, token_positions, ent_spans, batch_starts, batch_ends, batch_widths, batch_data, batch_masks, batch_transforms, batch_quotes
def get_ant_labels(all_doc_sents, all_doc_ents):
max_words=0
max_ents=0
mention_id=0
big_ents={}
doc_antecedent_labels=[]
big_doc_ents=[]
for idx, sent in enumerate(all_doc_sents):
if len(sent) > max_words:
max_words=len(sent)
this_sent_ents=[]
all_sent_ents=sorted(all_doc_ents[idx], key=lambda x: (x[0], x[1]))
if len(all_sent_ents) > max_ents:
max_ents=len(all_sent_ents)
for (w_idx_start, w_idx_end, eid) in all_sent_ents:
this_sent_ents.append((w_idx_start, w_idx_end))
coref={}
if eid in big_ents:
coref=big_ents[eid]
else:
coref={mention_id:1}
vals=sorted(coref.keys())
if eid not in big_ents:
big_ents[eid]={}
big_ents[eid][mention_id]=1
mention_id+=1
doc_antecedent_labels.append(vals)
big_doc_ents.append(this_sent_ents)
return doc_antecedent_labels, big_doc_ents, max_words, max_ents
def read_conll(filename, model=None):
docid=None
partID=None
# collection
all_sents=[]
all_ents=[]
all_antecedent_labels=[]
all_max_words=[]
all_max_ents=[]
all_doc_names=[]
all_named_ents=[]
# for one doc
all_doc_sents=[]
all_doc_ents=[]
all_doc_named_ents=[]
# for one sentence
sent=[]
ents=[]
sent.append("[SEP]")
sid=0
named_ents=[]
cur_tokens=0
max_allowable_tokens=400
cur_tid=0
open_count=0
with open(filename, encoding="utf-8") as file:
for line in file:
if line.startswith("#begin document"):
all_doc_ents=[]
all_doc_sents=[]
all_doc_named_ents=[]
open_ents={}
open_named_ents={}
sid=0
docid=None
matcher=re.match("#begin document \((.*)\); part (.*)$", line.rstrip())
if matcher != None:
docid=matcher.group(1)
partID=matcher.group(2)
print(docid)
elif line.startswith("#end document"):
all_sents.append(all_doc_sents)
doc_antecedent_labels, big_ents, max_words, max_ents=get_ant_labels(all_doc_sents, all_doc_ents)
all_ents.append(big_ents)
all_named_ents.append(all_doc_named_ents)
all_antecedent_labels.append(doc_antecedent_labels)
all_max_words.append(max_words+1)
all_max_ents.append(max_ents+1)
all_doc_names.append((docid,partID))
else:
parts=re.split("\s+", line.rstrip())
if len(parts) < 2 or (cur_tokens >= max_allowable_tokens and open_count == 0):
sent.append("[CLS]")
all_doc_sents.append(sent)
ents=sorted(ents, key=lambda x: (x[0], x[1]))
all_doc_ents.append(ents)
all_doc_named_ents.append(named_ents)
ents=[]
named_ents=[]
sent=[]
sent.append("[SEP]")
sid+=1
cur_tokens=0
cur_tid=0
if len(parts) < 2:
continue
# +1 to account for initial [SEP]
tid=cur_tid+1
token=parts[3]
coref=parts[-1].split("|")
b_toks=model.tokenizer.tokenize(token)
cur_tokens+=len(b_toks)
cur_tid+=1
for c in coref:
if c.startswith("(") and c.endswith(")"):
c=re.sub("\(", "", c)
c=int(re.sub("\)", "", c))
ents.append((tid, tid, c))
elif c.startswith("("):
c=int(re.sub("\(", "", c))
if c not in open_ents:
open_ents[c]=[]
open_ents[c].append(tid)
open_count+=1
elif c.endswith(")"):
c=int(re.sub("\)", "", c))
assert c in open_ents
start_tid=open_ents[c].pop()
open_count-=1
ents.append((start_tid, tid, c))
ner=parts[10].split("|")
for c in ner:
try:
if c.startswith("(") and c.endswith(")"):
c=re.sub("\(", "", c)
c=int(re.sub("\)", "", c))
named_ents.append((tid, tid, c))
elif c.startswith("("):
c=int(re.sub("\(", "", c))
if c not in open_named_ents:
open_named_ents[c]=[]
open_named_ents[c].append(tid)
elif c.endswith(")"):
c=int(re.sub("\)", "", c))
assert c in open_named_ents
start_tid=open_named_ents[c].pop()
named_ents.append((start_tid, tid, c))
except:
pass
sent.append(token)
return all_sents, all_ents, all_named_ents, all_antecedent_labels, all_max_words, all_max_ents, all_doc_names
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-t','--trainData', help='Folder containing train data', required=False)
parser.add_argument('-v','--valData', help='Folder containing test data', required=False)
parser.add_argument('-m','--mode', help='mode {train, predict}', required=False)
parser.add_argument('-w','--model', help='modelFile (to write to or read from)', required=False)
parser.add_argument('-o','--outFile', help='outFile', required=False)
parser.add_argument('-s','--path_to_scorer', help='Path to coreference scorer', required=False)
args = vars(parser.parse_args())
mode=args["mode"]
modelFile=args["model"]
valData=args["valData"]
outfile=args["outFile"]
path_to_scorer=args["path_to_scorer"]
cache_dir = os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(0))
model = LSTMTagger.from_pretrained('bert-base-cased',
cache_dir=cache_dir,
freeze_bert=True)
config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
model.to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
lr_scheduler=ExponentialLR(optimizer, gamma=0.999)
if mode == "train":
trainData=args["trainData"]
all_docs, all_ents, all_named_ents, all_truth, all_max_words, all_max_ents, doc_ids=read_conll(trainData, model)
test_all_docs, test_all_ents, test_all_named_ents, test_all_truth, test_all_max_words, test_all_max_ents, test_doc_ids=read_conll(valData, model)
best_f1=0.
cur_steps=0
best_idx=0
patience=10
for i in range(100):
model.train()
bigloss=0.
for idx in range(len(all_docs)):
if idx % 10 == 0:
print(idx, "/", len(all_docs))
sys.stdout.flush()
max_words=all_max_words[idx]
max_ents=all_max_ents[idx]
matrix, index, token_positions, ent_spans, starts, ends, widths, input_ids, masks, transforms, quotes=get_data(model, all_docs[idx], all_ents[idx], max_ents, max_words)
if max_ents > 1:
model.zero_grad()
loss=model.forward(matrix, index, truth=all_truth[idx], names=None, token_positions=token_positions, starts=starts, ends=ends, widths=widths, input_ids=input_ids, attention_mask=masks, transforms=transforms, quotes=quotes)
loss.backward()
optimizer.step()
cur_steps+=1
if cur_steps % 100 == 0:
lr_scheduler.step()
bigloss+=loss.item()
print(bigloss)
model.eval()
doTest=False
if i >= 2:
doTest=True
avg_f1=test(model, test_all_docs, test_all_ents, test_all_named_ents, test_all_max_words, test_all_max_ents, test_doc_ids, outfile, i, valData, path_to_scorer, doTest=doTest)
if doTest:
if avg_f1 > best_f1:
torch.save(model.state_dict(), modelFile)
print("Saving model ... %.3f is better than %.3f" % (avg_f1, best_f1))
best_f1=avg_f1
best_idx=i
if i-best_idx > patience:
print ("Stopping training at epoch %s" % i)
break
elif mode == "predict":
model.load_state_dict(torch.load(modelFile, map_location=device))
model.eval()
test_all_docs, test_all_ents, test_all_named_ents, test_all_truth, test_all_max_words, test_all_max_ents, test_doc_ids=read_conll(valData, model=model)
test(model, test_all_docs, test_all_ents, test_all_named_ents, test_all_max_words, test_all_max_ents, test_doc_ids, outfile, 0, valData, path_to_scorer, doTest=True)
| 24,602 | 24.233846 | 255 | py |
CGMM | CGMM-master/score.py | from typing import List
import torch
from pydgn.training.callback.metric import Metric
class CGMMCompleteLikelihoodScore(Metric):
@property
def name(self) -> str:
return 'Complete Log Likelihood'
def __init__(self, use_as_loss=False, reduction='mean', use_nodes_batch_size=True):
super().__init__(use_as_loss=use_as_loss, reduction=reduction, use_nodes_batch_size=use_nodes_batch_size)
def on_training_batch_end(self, state):
self.batch_metrics.append(state.batch_score[self.name].item())
if state.model.is_graph_classification:
self.num_samples += state.batch_num_targets
else:
# This works for unsupervised CGMM
self.num_samples += state.batch_num_nodes
def on_eval_epoch_end(self, state):
state.update(epoch_score={self.name: torch.tensor(self.batch_metrics).sum() / self.num_samples})
self.batch_metrics = None
self.num_samples = None
def on_eval_batch_end(self, state):
self.batch_metrics.append(state.batch_score[self.name].item())
if state.model.is_graph_classification:
self.num_samples += state.batch_num_targets
else:
# This works for unsupervised CGMM
self.num_samples += state.batch_num_nodes
def _score_fun(self, targets, *outputs, batch_loss_extra):
return outputs[2]
def forward(self, targets: torch.Tensor, *outputs: List[torch.Tensor], batch_loss_extra: dict = None) -> dict:
return outputs[2]
class CGMMTrueLikelihoodScore(Metric):
@property
def name(self) -> str:
return 'True Log Likelihood'
def __init__(self, use_as_loss=False, reduction='mean', use_nodes_batch_size=True):
super().__init__(use_as_loss=use_as_loss, reduction=reduction, use_nodes_batch_size=use_nodes_batch_size)
def on_training_batch_end(self, state):
self.batch_metrics.append(state.batch_score[self.name].item())
if state.model.is_graph_classification:
self.num_samples += state.batch_num_targets
else:
# This works for unsupervised CGMM
self.num_samples += state.batch_num_nodes
def on_eval_batch_end(self, state):
self.batch_metrics.append(state.batch_score[self.name].item())
if state.model.is_graph_classification:
self.num_samples += state.batch_num_targets
else:
# This works for unsupervised CGMM
self.num_samples += state.batch_num_nodes
def _score_fun(self, targets, *outputs, batch_loss_extra):
return outputs[3]
def forward(self, targets: torch.Tensor, *outputs: List[torch.Tensor], batch_loss_extra: dict = None) -> dict:
return outputs[3]
| 2,750 | 36.175676 | 114 | py |
CGMM | CGMM-master/cgmm_embedding_task.py | import os
import shutil
import torch
from cgmm_incremental_task import CGMMTask
# This works with graph classification only
from pydgn.static import LOSS, SCORE
class EmbeddingCGMMTask(CGMMTask):
def run_valid(self, dataset_getter, logger):
"""
This function returns the training and validation or test accuracy
:return: (training accuracy, validation/test accuracy)
"""
batch_size = self.model_config.layer_config['batch_size']
shuffle = self.model_config.layer_config['shuffle'] \
if 'shuffle' in self.model_config.layer_config else True
# Instantiate the Dataset
dim_node_features = dataset_getter.get_dim_node_features()
dim_edge_features = dataset_getter.get_dim_edge_features()
dim_target = dataset_getter.get_dim_target()
layers = []
l_prec = self.model_config.layer_config['previous_layers_to_use'].split(',')
concatenate_axis = self.model_config.layer_config['concatenate_on_axis']
max_layers = self.model_config.layer_config['max_layers']
assert concatenate_axis > 0, 'You cannot concat on the first axis for design reasons.'
dict_per_layer = []
stop = False
depth = 1
while not stop and depth <= max_layers:
# Change exp path to allow Stop & Resume
self.exp_path = os.path.join(self.root_exp_path, f'layer_{depth}')
if os.path.exists(os.path.join(self.root_exp_path, f'layer_{depth + 1}')):
# print("skip layer", depth)
depth += 1
continue
# load output will concatenate in reverse order
prev_outputs_to_consider = [(depth - int(x)) for x in l_prec if (depth - int(x)) > 0]
train_out = self._create_extra_dataset(prev_outputs_to_consider, mode='train', depth=depth)
val_out = self._create_extra_dataset(prev_outputs_to_consider, mode='validation', depth=depth)
train_loader = dataset_getter.get_inner_train(batch_size=batch_size, shuffle=False, extra=train_out)
val_loader = dataset_getter.get_inner_val(batch_size=batch_size, shuffle=False, extra=val_out)
# ==== # WARNING: WE ARE JUSTPRECOMPUTING OUTER_TEST EMBEDDINGS FOR SUBSEQUENT CLASSIFIERS
# WE ARE NOT TRAINING ON TEST (EVEN THOUGH UNSUPERVISED)
# ==== #
test_out = self._create_extra_dataset(prev_outputs_to_consider, mode='test', depth=depth)
test_loader = dataset_getter.get_outer_test(batch_size=batch_size, shuffle=False, extra=test_out)
# ==== #
# Instantiate the Model
new_layer = self.create_incremental_model(dim_node_features, dim_edge_features, dim_target, depth,
prev_outputs_to_consider)
# Instantiate the engine (it handles the training loop and the inference phase by abstracting the specifics)
incremental_training_engine = self.create_incremental_engine(new_layer)
train_loss, train_score, train_out, \
val_loss, val_score, val_out, \
_, _, test_out = incremental_training_engine.train(train_loader=train_loader,
validation_loader=val_loader,
test_loader=test_loader,
max_epochs=self.model_config.layer_config['epochs'],
logger=logger)
for loader, out, mode in [(train_loader, train_out, 'train'), (val_loader, val_out, 'validation'),
(test_loader, test_out, 'test')]:
v_out, e_out, g_out, vo_out, eo_out, go_out = out
# Reorder outputs, which are produced in shuffled order, to the original arrangement of the dataset.
v_out, e_out, g_out, vo_out, eo_out, go_out = self._reorder_shuffled_objects(v_out, e_out, g_out,
vo_out, eo_out, go_out,
loader)
# Store outputs
self._store_outputs(mode, depth, v_out, e_out, g_out, vo_out, eo_out, go_out)
depth += 1
# NOW LOAD ALL EMBEDDINGS AND STORE THE EMBEDDINGS DATASET ON a torch file.
# Consider all previous layers now, i.e. gather all the embeddings
prev_outputs_to_consider = [l for l in range(1, depth + 1)]
prev_outputs_to_consider.reverse() # load output will concatenate in reverse order
# Retrieve only the graph embeddings to save memory.
# In CGMM classfication task (see other experiment file), I will ignore the outer val and reuse the inner val as validation, as I cannot use the splitter.
train_out = self._create_extra_dataset(prev_outputs_to_consider, mode='train', depth=depth, only_g=True)
val_out = self._create_extra_dataset(prev_outputs_to_consider, mode='validation', depth=depth, only_g=True)
test_out = self._create_extra_dataset(prev_outputs_to_consider, mode='test', depth=depth, only_g=True)
# Necessary info to give a unique name to the dataset (some hyper-params like epochs are assumed to be fixed)
embeddings_folder = self.model_config.layer_config['embeddings_folder']
max_layers = self.model_config.layer_config['max_layers']
unibigram = self.model_config.layer_config['unibigram']
C = self.model_config.layer_config['C']
CA = self.model_config.layer_config['CA'] if 'CA' in self.model_config.layer_config else None
aggregation = self.model_config.layer_config['aggregation']
infer_with_posterior = self.model_config.layer_config['infer_with_posterior']
outer_k = dataset_getter.outer_k
inner_k = dataset_getter.inner_k
# ====
if not os.path.exists(os.path.join(embeddings_folder, dataset_getter.dataset_name)):
os.makedirs(os.path.join(embeddings_folder, dataset_getter.dataset_name))
unigram_dim = C + CA if CA is not None else C
assert unibigram == True
# Retrieve unigram if necessary
for unib in [False, True]:
base_path = os.path.join(embeddings_folder, dataset_getter.dataset_name,
f'{max_layers}_{unib}_{C}_{CA}_{aggregation}_{infer_with_posterior}_{outer_k + 1}_{inner_k + 1}')
train_out_emb = torch.cat([d.g_outs if unib else d.g_outs[:, :, :unigram_dim] for d in train_out], dim=0)
torch.save(train_out_emb, base_path + '_train.torch')
val_out_emb = torch.cat([d.g_outs if unib else d.g_outs[:, :, :unigram_dim] for d in val_out], dim=0)
torch.save(val_out_emb, base_path + '_val.torch')
test_out_emb = torch.cat([d.g_outs if unib else d.g_outs[:, :, :unigram_dim] for d in test_out], dim=0)
torch.save(test_out_emb, base_path + '_test.torch')
# CLEAR OUTPUTS
for mode in ['train', 'validation', 'test']:
shutil.rmtree(os.path.join(self.output_folder, mode), ignore_errors=True)
tr_res = {LOSS: {'main_loss': torch.zeros(1)}, SCORE: {'main_score': torch.zeros(1)}}
vl_res = {LOSS: {'main_loss': torch.zeros(1)}, SCORE: {'main_score': torch.zeros(1)}}
return tr_res, vl_res
def run_test(self, dataset_getter, logger):
tr_res = {LOSS: {'main_loss': torch.zeros(1)}, SCORE: {'main_score': torch.zeros(1)}}
vl_res = {LOSS: {'main_loss': torch.zeros(1)}, SCORE: {'main_score': torch.zeros(1)}}
te_res = {LOSS: {'main_loss': torch.zeros(1)}, SCORE: {'main_score': torch.zeros(1)}}
return tr_res, vl_res, te_res
| 7,955 | 53.122449 | 162 | py |
CGMM | CGMM-master/emission.py | import math
import scipy
import scipy.cluster
import scipy.cluster.vq
import torch
# Interface for all emission distributions
from torch.nn import ModuleList
class EmissionDistribution(torch.nn.Module):
def __init__(self):
super().__init__()
def init_accumulators(self):
raise NotImplementedError()
def e_step(self, x_labels, y_labels):
raise NotImplementedError()
def infer(self, p_Q, x_labels):
raise NotImplementedError()
def _m_step(self, x_labels, y_labels, posterior_estimate):
raise NotImplementedError()
def m_step(self):
raise NotImplementedError()
def __str__(self):
raise NotImplementedError()
# do not replace replace with torch.distributions yet, it allows GPU computation
class Categorical(EmissionDistribution):
def __init__(self, dim_target, dim_hidden_states):
"""
:param dim_target: dimension of output alphabet
:param dim_hidden_states: hidden states associated with each label
"""
super().__init__()
self.eps = 1e-8 # Laplace smoothing
self.K = dim_target # discrete output labels
self.C = dim_hidden_states # clusters
self.emission_distr = torch.nn.Parameter(torch.empty(self.K, self.C,
dtype=torch.float32),
requires_grad=False)
self.emission_numerator = torch.nn.Parameter(torch.empty_like(self.emission_distr),
requires_grad=False)
for i in range(0, self.C):
em = torch.nn.init.uniform_(torch.empty(self.K, dtype=torch.float32))
self.emission_distr[:, i] = em / em.sum()
self.init_accumulators()
def _flatten_labels(self, labels):
labels = torch.squeeze(labels)
if len(labels.shape) > 1:
# Compute discrete categories from one_hot_input
labels_squeezed = labels.argmax(dim=1)
return labels_squeezed
return labels.long()
def init_accumulators(self):
torch.nn.init.constant_(self.emission_numerator, self.eps)
def e_step(self, x_labels, y_labels):
"""
For each cluster i, returns the probability associated with a specific label.
:param x_labels: unused
:param y_labels: output observables
:return: a tensor of size ?xC representing the estimated posterior distribution for the E-step
"""
y_labels_squeezed = self._flatten_labels(y_labels)
# Returns the emission probability associated to each observable
emission_obs = self.emission_distr[y_labels_squeezed] # ?xC
return emission_obs
def infer(self, p_Q, x_labels):
"""
Compute probability of a label given the probability P(Q) as argmax_y \sum_i P(y|Q=i)P(Q=i)
:param p_Q: tensor of size ?xC
:param x_labels: unused
:return:
"""
'''
# OLD CODE
# We simply compute P(y|x) = \sum_i P(y|Q=i)P(Q=i|x) for each node
inferred_y = torch.mm(p_Q, self.emission_distr.transpose(0, 1)) # ?xK
return inferred_y
'''
p_K_CS = p_Q.unsqueeze(1) * self.emission_distr.unsqueeze(0) # ?xKxC
p_KCS = p_K_CS.reshape((-1, self.K * self.C)) # ?xKC
best_KCS = torch.argmax(p_KCS, dim=1)
best_K = best_KCS // self.C
best_CS = torch.remainder(best_KCS, self.C)
return best_K.unsqueeze(1)
def _m_step(self, x_labels, y_labels, posterior_estimate):
"""
Updates the minibatch accumulators
:param x_labels: unused
:param y_labels: output observable
:param posterior_estimate: a ?xC posterior estimate obtained using the output observables
"""
y_labels_squeezed = self._flatten_labels(y_labels)
self.emission_numerator.index_add_(dim=0, source=posterior_estimate,
index=y_labels_squeezed) # KxC
def m_step(self):
"""
Updates the emission parameters and re-initializes the accumulators.
:return:
"""
self.emission_distr.data = torch.div(self.emission_numerator,
self.emission_numerator.sum(0))
curr_device = self.emission_distr.get_device()
curr_device = curr_device if curr_device != -1 else 'cpu'
# assert torch.allclose(self.emission_distr.sum(0), torch.tensor([1.]).to(curr_device))
self.init_accumulators()
def __str__(self):
return str(self.emission_distr)
# do not replace replace with torch.distributions yet, it allows GPU computation
class ConditionedCategorical(EmissionDistribution):
def __init__(self, dim_features, dim_target, dim_hidden_states):
"""
:param dim_node_features: dimension of input alphabet
:param dim_target: dimension of output alphabet
:param dim_hidden_states: hidden states associated with each label
"""
super().__init__()
self.eps = 1e-8 # Laplace smoothing
self.K = dim_features # discrete input labels
self.Y = dim_target # discrete output labels
self.C = dim_hidden_states # clusters
self.emission_distr = torch.nn.Parameter(torch.empty(self.K,
self.Y,
self.C,
dtype=torch.float32),
requires_grad=False)
for i in range(self.C):
for k in range(self.K):
em = torch.nn.init.uniform_(torch.empty(self.Y,
dtype=torch.float32))
self.emission_distr[k, :, i] = em / em.sum()
self.emission_numerator = torch.nn.Parameter(torch.empty_like(self.emission_distr),
requires_grad=False)
self.init_accumulators()
def init_accumulators(self):
torch.nn.init.constant_(self.emission_numerator, self.eps)
def e_step(self, x_labels, y_labels):
"""
For each cluster i, returns the probability associated with a specific input and output label.
:param x_labels: input observables
:param y_labels: output observables
:return: a tensor of size ?xC representing the estimated posterior distribution for the E-step
"""
x_labels_squeezed = self._flatten_labels(x_labels)
y_labels_squeezed = self._flatten_labels(y_labels)
emission_of_labels = self.emission_distr[x_labels_squeezed, y_labels, :]
return emission_of_labels # ?xC
def infer(self, p_Q, x_labels):
"""
Compute probability of a label given the probability P(Q|x) as argmax_y \sum_i P(y|Q=i,x)P(Q=i|x)
:param p_Q: tensor of size ?xC
:return:
"""
# We simply compute P(y|x) = \sum_i P(y|Q=i,x)P(Q=i|x) for each node
x_labels_squeezed = self._flatten_labels(x_labels)
# First, condition the emission on the input labels
emission_distr_given_x = self.emission_distr[x_labels_squeezed, :, :]
# Then, perform inference
inferred_y = p_Q.unsqueeze(1) * emission_distr_given_x # ?xYxC
inferred_y = torch.sum(inferred_y, dim=2) # ?xY
return inferred_y
def _m_step(self, x_labels, y_labels, posterior_estimate):
"""
Updates the minibatch accumulators
:param x_labels: unused
:param y_labels: output observable
:param posterior_estimate: a ?xC posterior estimate obtained using the output observables
"""
x_labels_squeezed = self._flatten_labels(x_labels)
y_labels_squeezed = self._flatten_labels(y_labels)
for k in range(self.K):
# filter nodes based on their input value
mask = x_labels_squeezed == k
y_labels_masked = y_labels_squeezed[mask]
posterior_estimate_masked = posterior_estimate[mask, :]
# posterior_estimate has shape ?xC
delta_numerator = torch.zeros(self.Y, self.C)
delta_numerator.index_add_(dim=0, source=posterior_estimate_masked,
index=y_labels_masked) # --> Y x C
self.emission_numerator[k, :, :] += delta_numerator
def m_step(self):
"""
Updates the emission parameters and re-initializes the accumulators.
:return:
"""
self.emission_distr.data = torch.div(self.emission_numerator,
torch.sum(self.emission_numerator,
dim=1,
keepdim=True))
assert torch.allclose(self.emission_distr.sum(1), torch.tensor([1.]).to(self.emission_distr.get_device()))
self.init_accumulators()
def __str__(self):
return str(self.emission_distr)
# do not replace replace with torch.distributions yet, it allows GPU computation
class BernoulliEmission(EmissionDistribution):
def __init__(self, dim_target, dim_hidden_states):
super().__init__()
self.eps = 1e-8 # Laplace smoothing
self.C = dim_hidden_states # clusters
self.bernoulli_params = torch.nn.Parameter(torch.nn.init.uniform_(torch.empty(self.C,
dtype=torch.float32)),
requires_grad=False)
self.emission_numerator = torch.nn.Parameter(torch.empty_like(self.bernoulli_params),
requires_grad=False)
self.emission_denominator = torch.nn.Parameter(torch.empty_like(self.bernoulli_params),
requires_grad=False)
self.init_accumulators()
def init_accumulators(self):
torch.nn.init.constant_(self.emission_numerator, self.eps)
torch.nn.init.constant_(self.emission_denominator, self.eps * 2)
def bernoulli_density(self, labels, param):
return torch.mul(torch.pow(param, labels),
torch.pow(1 - param, 1 - labels))
def e_step(self, x_labels, y_labels):
"""
For each cluster i, returns the probability associated with a specific input and output label.
:param x_labels: unused
:param y_labels: output observables
:return: a tensor of size ?xC representing the estimated posterior distribution for the E-step
"""
emission_of_labels = None
for i in range(0, self.C):
if emission_of_labels is None:
emission_of_labels = torch.reshape(self.bernoulli_density(y_labels,
self.bernoulli_params[i]), (-1, 1))
else:
emission_of_labels = torch.cat((emission_of_labels,
torch.reshape(self.bernoulli_density(y_labels,
self.bernoulli_params[i]),
(-1, 1))),
dim=1)
return emission_of_labels
def infer(self, p_Q, x_labels):
"""
Compute probability of a label given the probability P(Q) as argmax_y \sum_i P(y|Q=i)P(Q=i)
:param p_Q: tensor of size ?xC
:param x_labels: unused
:return:
"""
# We simply compute P(y|x) = \sum_i P(y|Q=i)P(Q=i|x) for each node
inferred_y = torch.mm(p_Q, self.bernoulli_params.unsqueeze(1)) # ?x1
return inferred_y
def _m_step(self, x_labels, y_labels, posterior_estimate):
"""
Updates the minibatch accumulators
:param x_labels: unused
:param y_labels: output observable
:param posterior_estimate: a ?xC posterior estimate obtained using the output observables
"""
if len(y_labels.shape) == 1:
y_labels = y_labels.unsqueeze(1)
self.emission_numerator += torch.sum(torch.mul(posterior_estimate,
y_labels), dim=0) # --> 1 x C
self.emission_denominator += torch.sum(posterior_estimate, dim=0) # --> C
def m_step(self):
self.emission_distr = self.emission_numerator / self.emission_denominator
self.init_accumulators()
def __str__(self):
return str(self.bernoulli_params)
class IndependentMultivariateBernoulliEmission(EmissionDistribution):
def init_accumulators(self):
for b in self.indep_bernoulli:
b.init_accumulators()
def __init__(self, dim_target, dim_hidden_states):
super().__init__()
self.eps = 1e-8 # Laplace smoothing
self.indep_bernoulli = ModuleList([BernoulliEmission(dim_target, dim_hidden_states) for _ in range(dim_target)])
self.init_accumulators()
def e_step(self, x_labels, y_labels):
"""
For each cluster i, returns the probability associated with a specific input and output label.
:param x_labels: unused
:param y_labels: output observables
:return: a tensor of size ?xC representing the estimated posterior distribution for the E-step
"""
emission_of_labels = None
# Assume independence
for i, b in enumerate(self.indep_bernoulli):
est_post_dist = b.e_step(x_labels, y_labels[:, i].unsqueeze(1))
if emission_of_labels is None:
emission_of_labels = est_post_dist
else:
emission_of_labels *= est_post_dist
return emission_of_labels
def infer(self, p_Q, x_labels):
"""
Compute probability of a label given the probability P(Q) as argmax_y \sum_i P(y|Q=i)P(Q=i)
:param p_Q: tensor of size ?xC
:param x_labels: unused
:return:
"""
inferred_y = None
# Assume independence
for i, b in enumerate(self.indep_bernoulli):
inferred_yi = b.infer(p_Q, x_labels)
if inferred_y is None:
inferred_y = inferred_yi
else:
inferred_y = torch.cat((inferred_y, inferred_yi), dim=1)
return inferred_y
def _m_step(self, x_labels, y_labels, posterior_estimate):
"""
Updates the minibatch accumulators
:param x_labels: unused
:param y_labels: output observable
:param posterior_estimate: a ?xC posterior estimate obtained using the output observables
"""
# Assume independence
for i, b in enumerate(self.indep_bernoulli):
b._m_step(x_labels, y_labels[:, i].unsqueeze(1), posterior_estimate)
def m_step(self):
# Assume independence
for i, b in enumerate(self.indep_bernoulli):
b.m_step()
self.init_accumulators()
def __str__(self):
return '-'.join([str(b) for b in self.indep_bernoulli])
# do not replace replace with torch.distributions yet, it allows GPU computation
class IsotropicGaussian(EmissionDistribution):
def __init__(self, dim_features, dim_hidden_states, var_threshold=1e-16):
super().__init__()
self.eps = 1e-8 # Laplace smoothing
self.var_threshold = var_threshold # do not go below this value
self.F = dim_features
self.C = dim_hidden_states # clusters
self.mu = torch.nn.Parameter(torch.rand((self.C, self.F),
dtype=torch.float32),
requires_grad=False)
self.var = torch.nn.Parameter(torch.rand((self.C, self.F),
dtype=torch.float32),
requires_grad=False)
self.pi = torch.nn.Parameter(torch.FloatTensor([math.pi]),
requires_grad=False)
self.mu_numerator = torch.nn.Parameter(torch.empty([self.C, self.F],
dtype=torch.float32),
requires_grad=False)
self.mu_denominator = torch.nn.Parameter(torch.empty([self.C, 1],
dtype=torch.float32),
requires_grad=False)
self.var_numerator = torch.nn.Parameter(torch.empty([self.C, self.F],
dtype=torch.float32),
requires_grad=False)
self.var_denominator = torch.nn.Parameter(torch.empty([self.C, 1],
dtype=torch.float32),
requires_grad=False)
# To launch k-means the first time
self.initialized = False
self.init_accumulators()
def to(self, device):
super().to(device)
self.device = device
def initialize(self, labels):
codes, distortion = scipy.cluster.vq.kmeans(labels.cpu().detach().numpy()[:],
self.C, iter=20,
thresh=1e-05)
# Number of prototypes can be < than self.C
self.mu[:codes.shape[0], :] = torch.from_numpy(codes)
self.var[:, :] = torch.std(labels, dim=0)
self.mu = self.mu # .to(self.device)
self.var = self.var # .to(self.device)
def univariate_pdf(self, labels, mean, var):
"""
Univariate case, computes probability distribution for each data point
:param labels:
:param mean:
:param var:
:return:
"""
return torch.exp(-((labels.float() - mean) ** 2) / (2 * var)) / (torch.sqrt(2 * self.pi * var))
def multivariate_diagonal_pdf(self, labels, mean, var):
"""
Multivariate case, DIAGONAL cov. matrix. Computes probability distribution for each data point
:param labels:
:param mean:
:param var:
:return:
"""
diff = (labels.float() - mean)
log_normaliser = -0.5 * (torch.log(2 * self.pi) + torch.log(var))
log_num = - (diff * diff) / (2 * var)
log_probs = torch.sum(log_num + log_normaliser, dim=1)
probs = torch.exp(log_probs)
# Trick to avoid instability, in case variance collapses to 0
probs[probs != probs] = self.eps
probs[probs < self.eps] = self.eps
return probs
def init_accumulators(self):
"""
This method initializes the accumulators for the EM algorithm.
EM updates the parameters in batch, but needs to accumulate statistics in mini-batch style.
:return:
"""
torch.nn.init.constant_(self.mu_numerator, self.eps)
torch.nn.init.constant_(self.mu_denominator, self.eps * self.C)
torch.nn.init.constant_(self.var_numerator, self.eps)
torch.nn.init.constant_(self.var_denominator, self.eps * self.C)
def e_step(self, x_labels, y_labels):
"""
For each cluster i, returns the probability associated to a specific label.
:param x_labels: unused
:param y_labels: output observables
:return: a distribution associated to each layer
"""
if not self.initialized:
self.initialized = True
self.initialize(y_labels)
emission_of_labels = None
for i in range(0, self.C):
if emission_of_labels is None:
emission_of_labels = torch.reshape(self.multivariate_diagonal_pdf(y_labels, self.mu[i], self.var[i]),
(-1, 1))
else:
emission_of_labels = torch.cat((emission_of_labels,
torch.reshape(
self.multivariate_diagonal_pdf(y_labels, self.mu[i], self.var[i]),
(-1, 1))), dim=1)
emission_of_labels += self.eps
assert not torch.isnan(emission_of_labels).any(), (torch.sum(torch.isnan(emission_of_labels)))
return emission_of_labels.detach()
def infer(self, p_Q, x_labels):
"""
Compute probability of a label given the probability P(Q) as argmax_y \sum_i P(y|Q=i)P(Q=i)
:param p_Q: tensor of size ?xC
:param x_labels: unused
:return:
"""
# We simply compute P(y|x) = \sum_i P(y|Q=i)P(Q=i|x) for each node
inferred_y = torch.mm(p_Q, self.mu) # ?xF
return inferred_y
def _m_step(self, x_labels, y_labels, posterior_estimate):
"""
Updates the minibatch accumulators
:param x_labels: unused
:param y_labels: output observable
:param posterior_estimate: a ?xC posterior estimate obtained using the output observables
"""
y_labels = y_labels.float()
for i in range(0, self.C):
reshaped_posterior = torch.reshape(posterior_estimate[:, i], (-1, 1)) # for broadcasting with F > 1
den = torch.unsqueeze(torch.sum(posterior_estimate[:, i], dim=0), dim=-1) # size C
y_weighted = torch.mul(y_labels, reshaped_posterior) # ?xF x ?x1 --> ?xF
y_minus_mu_squared_tmp = y_labels - self.mu[i, :]
# DIAGONAL COV MATRIX
y_minus_mu_squared = torch.mul(y_minus_mu_squared_tmp, y_minus_mu_squared_tmp)
self.mu_numerator[i, :] += torch.sum(y_weighted, dim=0)
self.var_numerator[i] += torch.sum(torch.mul(y_minus_mu_squared, reshaped_posterior), dim=0)
self.mu_denominator[i, :] += den
self.var_denominator[i, :] += den
def m_step(self):
"""
Updates the emission parameters and re-initializes the accumulators.
:return:
"""
self.mu.data = self.mu_numerator / self.mu_denominator
# Laplace smoothing
self.var.data = (self.var_numerator + self.var_threshold) / (self.var_denominator + self.C * self.var_threshold)
self.init_accumulators()
def __str__(self):
return f"{str(self.mu)}, {str(self.mu)}"
| 22,661 | 40.734807 | 120 | py |
CGMM | CGMM-master/readout.py | import torch
from pydgn.model.interface import ReadoutInterface
class CGMMGraphReadout(ReadoutInterface):
def __init__(self, dim_node_features, dim_edge_features, dim_target, config):
super().__init__(dim_node_features, dim_edge_features, dim_target, config)
embeddings_node_features = dim_node_features
hidden_units = config['hidden_units']
self.fc_global = torch.nn.Linear(embeddings_node_features, hidden_units)
self.out = torch.nn.Linear(hidden_units, dim_target)
def forward(self, data):
out = self.out(torch.relu(self.fc_global(data.x.float())))
return out, data.x
| 641 | 32.789474 | 82 | py |
CGMM | CGMM-master/cgmm.py | import torch
from pydgn.model.interface import ModelInterface
from util import compute_bigram, compute_unigram
from torch_geometric.nn import global_mean_pool, global_add_pool
from torch_scatter import scatter_add, scatter_max
class CGMM(ModelInterface):
def __init__(self, dim_node_features, dim_edge_features, dim_target, readout_class, config):
super().__init__(dim_node_features, dim_edge_features, dim_target, readout_class, config)
self.device = None
self.readout_class = readout_class
self.is_first_layer = config['depth'] == 1
self.depth = config['depth']
self.training = False
self.return_node_embeddings = False
self.K = dim_node_features
self.Y = dim_target
self.L = len(config['prev_outputs_to_consider'])
self.A = config['A']
self.C = config['C']
self.C2 = config['C'] + 1
self.CS = config.get('CS', None)
self.is_graph_classification = self.CS is not None
# self.add_self_arc = config['self_arc'] if 'self_arc' in config else False
self.use_continuous_states = config['infer_with_posterior']
self.unibigram = config['unibigram']
self.aggregation = config['aggregation']
self.readout = readout_class(dim_node_features, dim_edge_features,
dim_target, config)
if self.is_first_layer:
self.transition = BaseTransition(self.C)
else:
self.transition = CGMMTransition(self.C, self.A,
self.C2, self.L)
self.init_accumulators()
def init_accumulators(self):
self.readout.init_accumulators()
self.transition.init_accumulators()
# Do not delete this!
if self.device: # set by to() method
self.to(self.device)
def to(self, device):
super().to(device)
self.device = device
def train(self):
self.readout.train()
self.transition.train()
self.training = True
def eval(self):
self.readout.eval()
self.transition.eval()
self.training = False
def forward(self, data):
extra = None
if not self.is_first_layer:
data, extra = data[0], data[1]
return self.e_step(data, extra)
def e_step(self, data, extra=None):
x, y, batch = data.x, data.y, data.batch
prev_stats = None if self.is_first_layer else extra.vo_outs
if prev_stats is not None:
prev_stats.to(self.device)
# --------------------------- FORWARD PASS --------------------------- #
# t = time.time()
# --- TRANSITION contribution
if self.is_first_layer:
# p_Q_given_obs --> ?xC
p_Q_given_obs = self.transition.e_step(x)
transition_posterior = p_Q_given_obs
rightmost_term = p_Q_given_obs
else:
# p_Q_given_obs --> ?xC / transition_posterior --> ?xLxAxCxC2
p_Q_given_obs, transition_posterior, rightmost_term = self.transition.e_step(x, prev_stats)
# assert torch.allclose(p_Q_given_obs.sum(1), torch.tensor([1.]).to(self.device)), p_Q_given_obs.sum(1)
# print(f"Transition E-step time: {time.time()-t}"); t = time.time()
# --- READOUT contribution
# true_log_likelihood --> ?x1 / readout_posterior --> ?xCSxCN or ?xCN
true_log_likelihood, readout_posterior, emission_target = self.readout.e_step(p_Q_given_obs, x, y, batch)
# print(f"Readout E-step time: {time.time()-t}"); t = time.time()
# likely_labels --> ? x Y
likely_labels = self.readout.infer(p_Q_given_obs, x, batch)
# print(f"Readout inference time: {time.time()-t}"); t = time.time()
# -------------------------------------------------------------------- #
if not self.is_graph_classification:
complete_log_likelihood, eui = self._e_step_node(x, y, p_Q_given_obs,
transition_posterior, rightmost_term,
readout_posterior, emission_target,
batch)
else:
complete_log_likelihood, eui = self._e_step_graph(x, y, p_Q_given_obs,
transition_posterior, rightmost_term,
readout_posterior, emission_target,
batch)
# print(f"Posterior E-step time: {time.time()-t}"); t = time.time()
num_nodes = x.shape[0]
# CGMM uses the true posterior (over node attributes) as it is unsupervised!
# Different from IO version
if self.return_node_embeddings:
# print("Computing intermediate outputs")
assert not self.training
statistics_batch = self._compute_statistics(eui, data, self.device)
node_unigram = compute_unigram(eui, self.use_continuous_states)
graph_unigram = self._get_aggregation_fun()(node_unigram, batch)
if self.unibigram:
node_bigram = compute_bigram(eui.float(), data.edge_index, batch,
self.use_continuous_states)
graph_bigram = self._get_aggregation_fun()(node_bigram, batch)
node_embeddings_batch = torch.cat((node_unigram, node_bigram), dim=1)
graph_embeddings_batch = torch.cat((graph_unigram, graph_bigram), dim=1)
else:
node_embeddings_batch = node_unigram
graph_embeddings_batch = graph_unigram
# to save time during debug
embeddings = (None, None, graph_embeddings_batch, statistics_batch, None, None)
else:
embeddings = None
return likely_labels, embeddings, complete_log_likelihood, \
true_log_likelihood, num_nodes
def _e_step_graph(self, x, y, p_Q_given_obs, transition_posterior,
rightmost_term, readout_posterior, emission_target, batch):
# batch (i.e., replicate) graph readout posterior for all nodes
b_readout_posterior = readout_posterior[batch] # ?nxCSxCN
if self.is_first_layer:
# ----------------------------- Posterior ---------------------------- #
# expand
exp_readout_posterior = b_readout_posterior.reshape((-1, self.CS,
self.C))
# expand
exp_transition_posterior = transition_posterior.unsqueeze(1)
# batch graph sizes + expand
b_graph_sizes = scatter_add(torch.ones_like(batch).to(self.device),
batch)[batch].reshape([-1, 1, 1])
unnorm_posterior_estimate = torch.div(torch.mul(exp_readout_posterior,
exp_transition_posterior),
b_graph_sizes)
Z = global_add_pool(unnorm_posterior_estimate.sum((1, 2), keepdim=True), batch)
Z[Z == 0.] = 1.
esui = unnorm_posterior_estimate / (Z[batch]) # --> ?n x CS x CN
eui = esui.sum(1) # ?n x CN
if self.training:
# Update the accumulators (also useful for minibatch training)
self.readout._m_step(x, y, esui, batch)
self.transition._m_step(x, y, eui)
# -------------------------------------------------------------------- #
# ---------------------- Complete Log Likelihood --------------------- #
complete_log_likelihood_readout = self.readout.complete_log_likelihood(esui, emission_target, batch)
complete_log_likelihood_transition = self.transition.complete_log_likelihood(eui, p_Q_given_obs)
complete_log_likelihood = complete_log_likelihood_readout + complete_log_likelihood_transition
# -------------------------------------------------------------------- #
else:
# ----------------------------- Posterior ---------------------------- #
# expand
exp_readout_posterior = b_readout_posterior.reshape((-1, self.CS,
1, 1,
self.C, 1))
# expand
exp_transition_posterior = transition_posterior.unsqueeze(1)
# batch graph sizes + expand
b_graph_sizes = scatter_add(torch.ones_like(batch).to(self.device),
batch)[batch].reshape([-1, 1, 1, 1, 1, 1])
unnorm_posterior_estimate = torch.div(torch.mul(exp_readout_posterior,
exp_transition_posterior),
b_graph_sizes)
Z = global_add_pool(unnorm_posterior_estimate.sum((1, 2, 3, 4, 5), keepdim=True), batch)
Z[Z == 0.] = 1.
esuilaj = unnorm_posterior_estimate / (Z[batch]) # --> ?n x CS x L x A x C x C2
euilaj = esuilaj.sum(1) # Marginalize over CS --> transition M-step
euila = euilaj.sum(4) # ?n x L x A x C
euil = euila.sum(2) # ?n x L x C
esui = esuilaj.sum((2, 3, 5)) # Marginalize over L,A,C2 --> readout M-step
eui = euil.sum(1) # ?n x C
if self.training:
# Update the accumulators (also useful for minibatch training)
self.readout._m_step(x, y, esui, batch)
self.transition._m_step(x, y, euilaj, euila, euil)
# -------------------------------------------------------------------- #
# ---------------------- Complete Log Likelihood --------------------- #
complete_log_likelihood_readout = self.readout.complete_log_likelihood(esui, emission_target, batch)
complete_log_likelihood_transition = self.transition.complete_log_likelihood(euilaj, euila, euil,
rightmost_term)
complete_log_likelihood = complete_log_likelihood_readout + complete_log_likelihood_transition
# -------------------------------------------------------------------- #
return complete_log_likelihood, eui
def _e_step_node(self, x, y, p_Q_given_obs, transition_posterior,
rightmost_term, readout_posterior, emission_target, batch):
if self.is_first_layer:
# ----------------------------- Posterior ---------------------------- #
unnorm_posterior_estimate = readout_posterior * transition_posterior
Z = unnorm_posterior_estimate.sum(1, keepdim=True)
Z[Z == 0.] = 1.
eui = unnorm_posterior_estimate / Z # --> ? x CN
if self.training:
# Update the accumulators (also useful for minibatch training)
self.readout._m_step(x, y, eui, batch)
self.transition._m_step(x, y, eui)
# -------------------------------------------------------------------- #
# ---------------------- Complete Log Likelihood --------------------- #
complete_log_likelihood_readout = self.readout.complete_log_likelihood(eui, emission_target, batch)
complete_log_likelihood_transition = self.transition.complete_log_likelihood(eui, p_Q_given_obs)
complete_log_likelihood = complete_log_likelihood_readout + complete_log_likelihood_transition
# -------------------------------------------------------------------- #
else:
# ----------------------------- Posterior ---------------------------- #
# expand
exp_readout_posterior = readout_posterior.reshape((-1, 1, 1, self.C, 1))
unnorm_posterior_estimate = torch.mul(exp_readout_posterior,
transition_posterior)
Z = unnorm_posterior_estimate.sum((1, 2, 3, 4), keepdim=True)
Z[Z == 0.] = 1.
euilaj = unnorm_posterior_estimate / Z # --> ?n x L x A x C x C2
euila = euilaj.sum(4) # ?n x L x A x C
euil = euila.sum(2) # ?n x L x C
eui = euil.sum(1) # ?n x C
if self.training:
# Update the accumulators (also useful for minibatch training)
self.readout._m_step(x, y, eui, batch)
self.transition._m_step(x, y, euilaj, euila, euil)
# -------------------------------------------------------------------- #
# ---------------------- Complete Log Likelihood --------------------- #
complete_log_likelihood_readout = self.readout.complete_log_likelihood(eui, emission_target, batch)
complete_log_likelihood_transition = self.transition.complete_log_likelihood(euilaj, euila, euil,
rightmost_term)
complete_log_likelihood = complete_log_likelihood_readout + complete_log_likelihood_transition
# -------------------------------------------------------------------- #
# assert torch.allclose(eui.sum(1), torch.tensor([1.]).to(self.device)), eui.sum(1)[eui.sum(1) != 1.]
return complete_log_likelihood, eui
def m_step(self):
self.readout.m_step()
self.transition.m_step()
self.init_accumulators()
def stopping_criterion(self, depth, max_layers, train_loss, train_score, val_loss, val_score,
dict_per_layer, layer_config, logger=None):
return depth == max_layers
def _compute_statistics(self, posteriors, data, device):
statistics = torch.full((posteriors.shape[0], self.A + 1, posteriors.shape[1] + 1), 0., dtype=torch.float32).to(
device)
srcs, dsts = data.edge_index
if self.A == 1:
sparse_adj_matr = torch.sparse_coo_tensor(data.edge_index, \
torch.ones(data.edge_index.shape[1], dtype=posteriors.dtype).to(
device), \
torch.Size([posteriors.shape[0],
posteriors.shape[0]])).to(device).transpose(0, 1)
statistics[:, 0, :-1] = torch.sparse.mm(sparse_adj_matr, posteriors)
else:
for arc_label in range(self.A):
sparse_label_adj_matr = torch.sparse_coo_tensor(data.edge_index, \
(data.edge_attr == arc_label).to(device).float(), \
torch.Size([posteriors.shape[0],
posteriors.shape[0]])).to(device).transpose(
0, 1)
statistics[:, arc_label, :-1] = torch.sparse.mm(sparse_label_adj_matr, posteriors)
# Deal with nodes with degree 0: add a single fake neighbor with uniform posterior
degrees = statistics[:, :, :-1].sum(dim=[1, 2]).floor()
statistics[degrees == 0., :, :] = 1. / self.C2
'''
if self.add_self_arc:
statistics[:, self.A, :-1] += posteriors
'''
# use self.A+1 as special edge for bottom states (all in self.C2-1)
max_arieties, _ = self._compute_max_ariety(degrees.int().to(self.device), data.batch)
max_arieties[max_arieties == 0] = 1
statistics[:, self.A, self.C] += degrees / max_arieties[data.batch].float()
return statistics
def _compute_sizes(self, batch, device):
return scatter_add(torch.ones(len(batch), dtype=torch.int).to(device), batch)
def _compute_max_ariety(self, degrees, batch):
return scatter_max(degrees, batch)
def _get_aggregation_fun(self):
if self.aggregation == 'mean':
aggregate = global_mean_pool
elif self.aggregation == 'sum':
aggregate = global_add_pool
return aggregate
class CGMMTransition(torch.nn.Module):
def __init__(self, c, a, c2, l):
super().__init__()
self.device = None
self.eps = 1e-8 # Laplace smoothing
self.C = c
self.orig_A = a
self.A = a + 1 # bottom state connected with a special arc
self.C2 = c2
self.L = l
self.layerS = torch.nn.Parameter(torch.nn.init.uniform_(torch.empty(self.L, dtype=torch.float32)),
requires_grad=False)
self.arcS = torch.nn.Parameter(torch.zeros((self.L, self.A), dtype=torch.float32), requires_grad=False)
self.transition = torch.nn.Parameter(torch.empty([self.L, self.A, self.C, self.C2], dtype=torch.float32),
requires_grad=False)
self.layerS /= self.layerS.sum() # inplace
for layer in range(self.L):
self.arcS[layer, :] = torch.nn.init.uniform_(self.arcS[layer, :])
self.arcS[layer, :] /= self.arcS[layer, :].sum()
for arc in range(self.A):
for j in range(self.C2):
tr = torch.nn.init.uniform_(torch.empty(self.C))
self.transition[layer, arc, :, j] = tr / tr.sum()
# These are variables where I accumulate intermediate minibatches' results
# These are needed by the M-step update equations at the end of an epoch
self.layerS_numerator = torch.nn.Parameter(torch.empty_like(self.layerS),
requires_grad=False)
self.arcS_numerator = torch.nn.Parameter(torch.empty_like(self.arcS),
requires_grad=False)
self.transition_numerator = torch.nn.Parameter(torch.empty_like(self.transition),
requires_grad=False)
self.init_accumulators()
def to(self, device):
super().to(device)
self.device = device
def init_accumulators(self):
torch.nn.init.constant_(self.layerS_numerator, self.eps)
torch.nn.init.constant_(self.arcS_numerator, self.eps)
torch.nn.init.constant_(self.transition_numerator, self.eps)
def e_step(self, x_labels, stats=None, batch=None):
# ---------------------------- Forward Pass -------------------------- #
stats = stats.float()
# Compute the neighbourhood dimension for each vertex
neighbDim = stats.sum(dim=3, keepdim=True).unsqueeze(4) # --> ?n x L x A x 1
# Replace zeros with ones to avoid divisions by zero
# This does not alter learning: the numerator can still be zero
neighbDim[neighbDim == 0] = 1.
transition = torch.unsqueeze(self.transition, 0) # --> 1 x L x A x C x C2
stats = stats.unsqueeze(3) # --> ?n x L x A x 1 x C2
rightmost_term = (transition * stats) / neighbDim # --> ?n x L x A x C x C2
layerS = torch.reshape(self.layerS, [1, self.L, 1]) # --> L x 1 x 1
arcS = torch.reshape(self.arcS, [1, self.L, self.A, 1]) # --> 1 x L x A x 1
tmp = (arcS * rightmost_term.sum(4)).sum(dim=2) # --> ?n x L x C
p_Q_given_obs = (layerS * tmp).sum(dim=1) # --> ?n x C
# -------------------------------------------------------------------- #
# ----------------------------- Posterior ---------------------------- #
layerS_expanded = torch.reshape(self.layerS, [1, self.L, 1, 1, 1])
arcS_expanded = torch.reshape(self.arcS, [1, self.L, self.A, 1, 1])
transition_posterior = layerS_expanded * arcS_expanded * rightmost_term
# -------------------------------------------------------------------- #
return p_Q_given_obs, transition_posterior, rightmost_term
def complete_log_likelihood(self, euilaj, euila, euil, rightmost_term):
layerS = torch.reshape(self.layerS, [1, self.L, 1])
term_1 = (euil * (layerS.log())).sum((1, 2)).sum()
arcS = torch.reshape(self.arcS, [1, self.L, self.A, 1])
term_2 = (euila * (arcS.log())).sum((1, 2, 3)).sum()
rightmost_term[rightmost_term == 0.] = 1
term_3 = (euilaj * (rightmost_term.log())).sum((1, 2, 3, 4)).sum()
return term_1 + term_2 + term_3
def _m_step(self, x_labels, y_labels, euilaj, euila, euil):
self.layerS_numerator += euil.sum(dim=(0, 2))
self.arcS_numerator += euila.sum(dim=(0, 3))
self.transition_numerator += euilaj.sum(0) # --> L x A x C x C2
def m_step(self):
self.layerS.data = self.layerS_numerator / self.layerS_numerator.sum(dim=0, keepdim=True)
self.arcS.data = self.arcS_numerator / self.arcS_numerator.sum(dim=1, keepdim=True)
self.transition.data = self.transition_numerator / self.transition_numerator.sum(dim=2, keepdim=True)
self.init_accumulators()
class BaseTransition(torch.nn.Module):
def __init__(self, c):
super().__init__()
self.device = None
self.eps = 1e-8 # Laplace smoothing
self.C = c
self.transition = torch.nn.Parameter(torch.empty([self.C], dtype=torch.float32), requires_grad=False)
tr = torch.nn.init.uniform_(torch.empty(self.C))
self.transition.data = tr / tr.sum()
self.transition_numerator = torch.nn.Parameter(torch.empty_like(self.transition), requires_grad=False)
self.init_accumulators()
def to(self, device):
super().to(device)
self.device = device
def init_accumulators(self):
torch.nn.init.constant_(self.transition_numerator, self.eps)
def e_step(self, x_labels, stats=None, batch=None):
# ---------------------------- Forward Pass -------------------------- #
p_Q_given_obs = self.transition.unsqueeze(0) # --> 1 x C
return p_Q_given_obs
def infer(self, x_labels, stats=None, batch=None):
p_Q_given_obs, _ = self.e_step(x_labels, stats, batch)
return p_Q_given_obs
def complete_log_likelihood(self, eui, p_Q_given_obs):
complete_log_likelihood = (eui * (p_Q_given_obs.log())).sum(1).sum()
return complete_log_likelihood
def _m_step(self, x_labels, y_labels, eui):
self.transition_numerator += eui.sum(0)
def m_step(self):
self.transition.data = self.transition_numerator / self.transition_numerator.sum()
self.init_accumulators()
| 22,943 | 43.638132 | 120 | py |
CGMM | CGMM-master/probabilistic_readout.py | from typing import Tuple, Optional, List
import torch
from pydgn.experiment.util import s2c
class ProbabilisticReadout(torch.nn.Module):
def __init__(self, dim_node_features, dim_edge_features, dim_target, config):
super().__init__()
self.K = dim_node_features
self.Y = dim_target
self.E = dim_edge_features
self.eps = 1e-8
def init_accumulators(self):
raise NotImplementedError()
def e_step(self, p_Q, x_labels, y_labels, batch):
raise NotImplementedError()
def infer(self, p_Q, x_labels, batch):
raise NotImplementedError()
def complete_log_likelihood(self, posterior, emission_target, batch):
raise NotImplementedError()
def _m_step(self, x_labels, y_labels, posterior, batch):
raise NotImplementedError()
def m_step(self):
raise NotImplementedError()
class ProbabilisticNodeReadout(ProbabilisticReadout):
def __init__(self, dim_node_features, dim_edge_features, dim_target, config):
super().__init__(dim_node_features, dim_edge_features, dim_target, config)
self.emission_class = s2c(config['emission'])
self.CN = config['C'] # number of states of a generic node
self.emission = self.emission_class(self.Y, self.CN)
def init_accumulators(self):
self.emission.init_accumulators()
def e_step(self, p_Q, x_labels, y_labels, batch):
emission_target = self.emission.e_step(x_labels, y_labels) # ?n x CN
readout_posterior = emission_target
# true log P(y) using the observables
# Mean of individual node terms
p_x = (p_Q * readout_posterior).sum(dim=1)
p_x[p_x == 0.] = 1.
true_log_likelihood = p_x.log().sum(dim=0)
return true_log_likelihood, readout_posterior, emission_target
def infer(self, p_Q, x_labels, batch):
return self.emission.infer(p_Q, x_labels)
def complete_log_likelihood(self, eui, emission_target, batch):
complete_log_likelihood = (eui * (emission_target.log())).sum(1).sum()
return complete_log_likelihood
def _m_step(self, x_labels, y_labels, eui, batch):
self.emission._m_step(x_labels, y_labels, eui)
def m_step(self):
self.emission.m_step()
self.init_accumulators()
class UnsupervisedProbabilisticNodeReadout(ProbabilisticReadout):
def __init__(self, dim_node_features, dim_edge_features, dim_target, config):
super().__init__(dim_node_features, dim_edge_features, dim_target, config)
self.emission_class = s2c(config['emission'])
self.CN = config['C'] # number of states of a generic node
self.emission = self.emission_class(self.K, self.CN)
def init_accumulators(self):
self.emission.init_accumulators()
def e_step(self, p_Q, x_labels, y_labels, batch):
# Pass x_labels as y_labels
emission_target = self.emission.e_step(x_labels, x_labels) # ?n x CN
readout_posterior = emission_target
# true log P(y) using the observables
# Mean of individual node terms
p_x = (p_Q * readout_posterior).sum(dim=1)
p_x[p_x == 0.] = 1.
true_log_likelihood = p_x.log().sum(dim=0)
return true_log_likelihood, readout_posterior, emission_target
def infer(self, p_Q, x_labels, batch):
return self.emission.infer(p_Q, x_labels)
def complete_log_likelihood(self, eui, emission_target, batch):
complete_log_likelihood = (eui * (emission_target.log())).sum(1).sum()
return complete_log_likelihood
def _m_step(self, x_labels, y_labels, eui, batch):
# Pass x_labels as y_labels
self.emission._m_step(x_labels, x_labels, eui)
def m_step(self):
self.emission.m_step()
self.init_accumulators()
| 3,817 | 33.396396 | 82 | py |
CGMM | CGMM-master/cgmm_incremental_task.py | import os
import shutil
import torch
from pydgn.experiment.experiment import Experiment
from pydgn.experiment.util import s2c
from pydgn.static import LOSS, SCORE
from torch.utils.data.sampler import SequentialSampler
from torch_geometric.data import Data
class CGMMTask(Experiment):
def __init__(self, model_configuration, exp_path, exp_seed):
super(CGMMTask, self).__init__(model_configuration, exp_path, exp_seed)
self.root_exp_path = exp_path # to distinguish from layers' exp_path
self.output_folder = os.path.join(exp_path, 'outputs')
self._concat_axis = self.model_config.layer_config['concatenate_on_axis']
def _create_extra_dataset(self, prev_outputs_to_consider, mode, depth, only_g=False):
# Load previous outputs if any according to prev. layers to consider (ALL TENSORS)
v_outs, e_outs, g_outs, vo_outs, eo_outs, go_outs = self._load_outputs(mode, prev_outputs_to_consider)
data_list = []
no_graphs = max(len(v_outs) if v_outs is not None else 0,
len(e_outs) if e_outs is not None else 0,
len(g_outs) if g_outs is not None else 0,
len(vo_outs) if vo_outs is not None else 0,
len(eo_outs) if eo_outs is not None else 0,
len(go_outs) if go_outs is not None else 0)
for index in range(no_graphs):
g = g_outs[index] if g_outs is not None else None
go = go_outs[index] if go_outs is not None else None
if not only_g:
v = v_outs[index] if v_outs is not None else None
e = e_outs[index] if e_outs is not None else None
vo = vo_outs[index] if vo_outs is not None else None
eo = eo_outs[index] if eo_outs is not None else None
data_list.append(Data(v_outs=v, e_outs=e, g_outs=g,
vo_outs=vo, eo_outs=eo, go_outs=go))
else:
data_list.append(Data(g_outs=g, go_outs=go))
return data_list
@staticmethod
def _reorder_shuffled_objects(v_out, e_out, g_out, vo_out, eo_out, go_out, data_loader):
if type(data_loader.sampler) == SequentialSampler: # No permutation
return v_out, e_out, g_out, vo_out, eo_out, go_out
idxs = data_loader.sampler.permutation # permutation of the last data_loader iteration
def reorder(obj, perm):
assert len(obj) == len(perm) and len(obj) > 0
return [y for (x, y) in sorted(zip(perm, obj))]
if v_out is not None:
# print(len(v_out))
v_out = reorder(v_out, idxs)
if e_out is not None:
raise NotImplementedError('This feature has not been implemented yet!')
# e_out = reorder(e_out, idxs)
if g_out is not None:
g_out = reorder(g_out, idxs)
if vo_out is not None:
# print(len(o_out))
vo_out = reorder(vo_out, idxs)
if eo_out is not None:
# print(len(o_out))
eo_out = reorder(eo_out, idxs)
if go_out is not None:
# print(len(o_out))
go_out = reorder(go_out, idxs)
return v_out, e_out, g_out, vo_out, eo_out, go_out
def _load_outputs(self, mode, prev_outputs_to_consider):
outs_dict = {
'vertex_outputs': None,
'edge_outputs': None,
'graph_outputs': None,
'vertex_other_outputs': None,
'edge_other_outputs': None,
'graph_other_outputs': None,
}
# The elements of prev_outputs_to_consider will be concatenated in
# reverse, i.e., if prev_outputs_to_consider = 1,2,3...L
# the contribution of layer L will appear in position 0 across
# self._concat_axis, then L-1 in position 1 and so on
# this is because a hyper-parameter l_prec=1 means "previous layer"
# and prev_outputs_to_consider will be = L,L-1,...1
# so we want to reorder layers from 1 to L
for prev in prev_outputs_to_consider:
for path, o_key in [(os.path.join(self.output_folder, mode, f'vertex_output_{prev}.pt'), 'vertex_outputs'),
(os.path.join(self.output_folder, mode, f'edge_output_{prev}.pt'), 'edge_outputs'),
(os.path.join(self.output_folder, mode, f'graph_output_{prev}.pt'), 'graph_outputs'),
(os.path.join(self.output_folder, mode, f'vertex_other_output_{prev}.pt'),
'vertex_other_outputs'),
(os.path.join(self.output_folder, mode, f'edge_other_output_{prev}.pt'),
'edge_other_outputs'),
(os.path.join(self.output_folder, mode, f'graph_other_output_{prev}.pt'),
'graph_other_outputs'), ]:
if os.path.exists(path):
out = torch.load(path)
outs = outs_dict[o_key]
if outs is None:
# print('None!')
outs = [None] * len(out)
# print(path, o_key, len(out))
# print(out[0].shape)
for graph_id in range(len(out)): # iterate over graphs
outs[graph_id] = out[graph_id] if outs[graph_id] is None \
else torch.cat((out[graph_id], outs[graph_id]), self._concat_axis)
outs_dict[o_key] = outs
return outs_dict['vertex_outputs'], outs_dict['edge_outputs'], \
outs_dict['graph_outputs'], outs_dict['vertex_other_outputs'], \
outs_dict['edge_other_outputs'], outs_dict['graph_other_outputs']
def _store_outputs(self, mode, depth, v_tensor_list, e_tensor_list=None, g_tensor_list=None,
vo_tensor_list=None, eo_tensor_list=None, go_tensor_list=None):
if not os.path.exists(os.path.join(self.output_folder, mode)):
os.makedirs(os.path.join(self.output_folder, mode))
if v_tensor_list is not None:
vertex_filepath = os.path.join(self.output_folder, mode, f'vertex_output_{depth}.pt')
torch.save([torch.unsqueeze(v_tensor, self._concat_axis) for v_tensor in v_tensor_list], vertex_filepath)
if e_tensor_list is not None:
edge_filepath = os.path.join(self.output_folder, mode, f'edge_output_{depth}.pt')
torch.save([torch.unsqueeze(e_tensor, self._concat_axis) for e_tensor in e_tensor_list], edge_filepath)
if g_tensor_list is not None:
graph_filepath = os.path.join(self.output_folder, mode, f'graph_output_{depth}.pt')
torch.save([torch.unsqueeze(g_tensor, self._concat_axis) for g_tensor in g_tensor_list], graph_filepath)
if vo_tensor_list is not None:
vertex_other_filepath = os.path.join(self.output_folder, mode, f'vertex_other_output_{depth}.pt')
torch.save([torch.unsqueeze(vo_tensor, self._concat_axis) for vo_tensor in vo_tensor_list],
vertex_other_filepath)
if eo_tensor_list is not None:
edge_other_filepath = os.path.join(self.output_folder, mode, f'edge_other_output_{depth}.pt')
torch.save([torch.unsqueeze(eo_tensor, self._concat_axis) for eo_tensor in eo_tensor_list],
edge_other_filepath)
if go_tensor_list is not None:
graph_other_filepath = os.path.join(self.output_folder, mode, f'graph_other_output_{depth}.pt')
torch.save([torch.unsqueeze(go_tensor, self._concat_axis) for go_tensor in go_tensor_list],
graph_other_filepath)
def run_valid(self, dataset_getter, logger):
"""
This function returns the training and validation or test accuracy
:return: (training accuracy, validation/test accuracy)
"""
batch_size = self.model_config.layer_config['batch_size']
arbitrary_logic_batch_size = self.model_config.layer_config['arbitrary_function_config']['batch_size']
shuffle = self.model_config.layer_config['shuffle'] \
if 'shuffle' in self.model_config.layer_config else True
arbitrary_logic_shuffle = self.model_config.layer_config['arbitrary_function_config']['shuffle'] \
if 'shuffle' in self.model_config.layer_config['arbitrary_function_config'] else True
# Instantiate the Dataset
dim_node_features = dataset_getter.get_dim_node_features()
dim_edge_features = dataset_getter.get_dim_edge_features()
dim_target = dataset_getter.get_dim_target()
layers = []
l_prec = self.model_config.layer_config['previous_layers_to_use'].split(',')
concatenate_axis = self.model_config.layer_config['concatenate_on_axis']
max_layers = self.model_config.layer_config['max_layers']
assert concatenate_axis > 0, 'You cannot concat on the first axis for design reasons.'
dict_per_layer = []
stop = False
depth = 1
while not stop and depth <= max_layers:
# Change exp path to allow Stop & Resume
self.exp_path = os.path.join(self.root_exp_path, f'layer_{depth}')
# load output will concatenate in reverse order
prev_outputs_to_consider = [(depth - int(x)) for x in l_prec if (depth - int(x)) > 0]
train_out = self._create_extra_dataset(prev_outputs_to_consider, mode='train', depth=depth)
val_out = self._create_extra_dataset(prev_outputs_to_consider, mode='validation', depth=depth)
train_loader = dataset_getter.get_inner_train(batch_size=batch_size, shuffle=shuffle, extra=train_out)
val_loader = dataset_getter.get_inner_val(batch_size=batch_size, shuffle=shuffle, extra=val_out)
# Instantiate the Model
new_layer = self.create_incremental_model(dim_node_features, dim_edge_features, dim_target, depth,
prev_outputs_to_consider)
# Instantiate the engine (it handles the training loop and the inference phase by abstracting the specifics)
incremental_training_engine = self.create_incremental_engine(new_layer)
train_loss, train_score, train_out, \
val_loss, val_score, val_out, \
_, _, _ = incremental_training_engine.train(train_loader=train_loader,
validation_loader=val_loader,
test_loader=None,
max_epochs=self.model_config.layer_config['epochs'],
logger=logger)
for loader, out, mode in [(train_loader, train_out, 'train'), (val_loader, val_out, 'validation')]:
v_out, e_out, g_out, vo_out, eo_out, go_out = out
# Reorder outputs, which are produced in shuffled order, to the original arrangement of the dataset.
v_out, e_out, g_out, vo_out, eo_out, go_out = self._reorder_shuffled_objects(v_out, e_out, g_out,
vo_out, eo_out, go_out,
loader)
# Store outputs
self._store_outputs(mode, depth, v_out, e_out, g_out, vo_out, eo_out, go_out)
# Consider all previous layers now, i.e. gather all the embeddings
prev_outputs_to_consider = [l for l in range(1, depth + 1)]
prev_outputs_to_consider.reverse() # load output will concatenate in reverse order
train_out = self._create_extra_dataset(prev_outputs_to_consider, mode='train', depth=depth)
val_out = self._create_extra_dataset(prev_outputs_to_consider, mode='validation', depth=depth)
train_loader = dataset_getter.get_inner_train(batch_size=arbitrary_logic_batch_size,
shuffle=arbitrary_logic_shuffle, extra=train_out)
val_loader = dataset_getter.get_inner_val(batch_size=arbitrary_logic_batch_size,
shuffle=arbitrary_logic_shuffle, extra=val_out)
# Change exp path to allow Stop & Resume
self.exp_path = os.path.join(self.root_exp_path, f'layer_{depth}_stopping_criterion')
# Stopping criterion based on training of the model
stop = new_layer.stopping_criterion(depth, max_layers, train_loss, train_score, val_loss, val_score,
dict_per_layer, self.model_config.layer_config, logger=logger)
# Change exp path to allow Stop & Resume
self.exp_path = os.path.join(self.root_exp_path, f'layer_{depth}_arbitrary_config')
if stop:
if 'CA' in self.model_config.layer_config:
# ECGMM
dim_features = new_layer.dim_node_features, new_layer.C * new_layer.depth + new_layer.CA * new_layer.depth if not new_layer.unibigram else (
new_layer.C + new_layer.CA + new_layer.C * new_layer.C) * new_layer.depth
else:
# CGMM
dim_features = new_layer.dim_node_features, new_layer.C * new_layer.depth if not new_layer.unibigram else (
new_layer.C + new_layer.C * new_layer.C) * new_layer.depth
config = self.model_config.layer_config['arbitrary_function_config']
device = config['device']
predictor_class = s2c(config['predictor'])
model = predictor_class(dim_node_features=dim_features,
dim_edge_features=0,
dim_target=dim_target,
config=config)
predictor_engine = self._create_engine(config, model, device, log_every=self.model_config.log_every)
train_loss, train_score, _, \
val_loss, val_score, _, \
_, _, _ = predictor_engine.train(train_loader=train_loader,
validation_loader=val_loader,
test_loader=None,
max_epochs=config['epochs'],
logger=logger)
d = {'train_loss': train_loss, 'train_score': train_score,
'validation_loss': val_loss, 'validation_score': val_score}
else:
d = {}
# Append layer
layers.append(new_layer)
dict_per_layer.append(d)
# Give priority to arbitrary function
stop = d['stop'] if 'stop' in d else stop
depth += 1
# CLEAR OUTPUTS TO SAVE SPACE
for mode in ['train', 'validation']:
shutil.rmtree(os.path.join(self.output_folder, mode), ignore_errors=True)
train_res = {LOSS: dict_per_layer[-1]['train_loss'], SCORE: dict_per_layer[-1]['train_score']}
val_res = {LOSS: dict_per_layer[-1]['validation_loss'], SCORE: dict_per_layer[-1]['validation_score']}
return train_res, val_res
def run_test(self, dataset_getter, logger):
"""
This function returns the training and test accuracy. DO NOT USE THE TEST FOR ANY REASON
:return: (training accuracy, test accuracy)
"""
batch_size = self.model_config.layer_config['batch_size']
arbitrary_logic_batch_size = self.model_config.layer_config['arbitrary_function_config']['batch_size']
shuffle = self.model_config.layer_config['shuffle'] \
if 'shuffle' in self.model_config.layer_config else True
arbitrary_logic_shuffle = self.model_config.layer_config['arbitrary_function_config']['shuffle'] \
if 'shuffle' in self.model_config.layer_config['arbitrary_function_config'] else True
# Instantiate the Dataset
dim_node_features = dataset_getter.get_dim_node_features()
dim_edge_features = dataset_getter.get_dim_edge_features()
dim_target = dataset_getter.get_dim_target()
layers = []
l_prec = self.model_config.layer_config['previous_layers_to_use'].split(',')
concatenate_axis = self.model_config.layer_config['concatenate_on_axis']
max_layers = self.model_config.layer_config['max_layers']
assert concatenate_axis > 0, 'You cannot concat on the first axis for design reasons.'
dict_per_layer = []
stop = False
depth = 1
while not stop and depth <= max_layers:
# Change exp path to allow Stop & Resume
self.exp_path = os.path.join(self.root_exp_path, f'layer_{depth}')
prev_outputs_to_consider = [(depth - int(x)) for x in l_prec if (depth - int(x)) > 0]
train_out = self._create_extra_dataset(prev_outputs_to_consider, mode='train', depth=depth)
val_out = self._create_extra_dataset(prev_outputs_to_consider, mode='validation', depth=depth)
test_out = self._create_extra_dataset(prev_outputs_to_consider, mode='test', depth=depth)
train_loader = dataset_getter.get_outer_train(batch_size=batch_size, shuffle=shuffle, extra=train_out)
val_loader = dataset_getter.get_outer_val(batch_size=batch_size, shuffle=shuffle, extra=val_out)
test_loader = dataset_getter.get_outer_test(batch_size=batch_size, shuffle=shuffle, extra=test_out)
# Instantiate the Model
new_layer = self.create_incremental_model(dim_node_features, dim_edge_features, dim_target,
depth, prev_outputs_to_consider)
# Instantiate the engine (it handles the training loop and inference phase by abstracting the specifics)
incremental_training_engine = self.create_incremental_engine(new_layer)
train_loss, train_score, train_out, \
val_loss, val_score, val_out, \
test_loss, test_score, test_out = incremental_training_engine.train(train_loader=train_loader,
validation_loader=val_loader,
test_loader=test_loader,
max_epochs=
self.model_config.layer_config[
'epochs'],
logger=logger)
for loader, out, mode in [(train_loader, train_out, 'train'),
(val_loader, val_out, 'validation'),
(test_loader, test_out, 'test')]:
v_out, e_out, g_out, vo_out, eo_out, go_out = out
# Reorder outputs, which are produced in shuffled order, to the original arrangement of the dataset.
v_out, e_out, g_out, vo_out, eo_out, go_out = self._reorder_shuffled_objects(v_out, e_out, g_out,
vo_out, eo_out, go_out,
loader)
# Store outputs
self._store_outputs(mode, depth, v_out, e_out, g_out, vo_out, eo_out, go_out)
# Consider all previous layers now, i.e. gather all the embeddings
prev_outputs_to_consider = [l for l in range(1, depth + 1)]
train_out = self._create_extra_dataset(prev_outputs_to_consider, mode='train', depth=depth,
only_g_outs=True)
val_out = self._create_extra_dataset(prev_outputs_to_consider, mode='validation', depth=depth,
only_g_outs=True)
test_out = self._create_extra_dataset(prev_outputs_to_consider, mode='test', depth=depth, only_g_outs=True)
train_loader = dataset_getter.get_outer_train(batch_size=arbitrary_logic_batch_size,
shuffle=arbitrary_logic_shuffle, extra=train_out)
val_loader = dataset_getter.get_outer_val(batch_size=arbitrary_logic_batch_size,
shuffle=arbitrary_logic_shuffle, extra=val_out)
test_loader = dataset_getter.get_outer_test(batch_size=arbitrary_logic_batch_size,
shuffle=arbitrary_logic_shuffle, extra=test_out)
# Change exp path to allow Stop & Resume
self.exp_path = os.path.join(self.root_exp_path, f'layer_{depth}_stopping_criterion')
# Stopping criterion based on training of the model
stop = new_layer.stopping_criterion(depth, max_layers, train_loss, train_score, val_loss, val_score,
dict_per_layer, self.model_config.layer_config,
logger=logger)
# Change exp path to allow Stop & Resume
self.exp_path = os.path.join(self.root_exp_path, f'layer_{depth}_arbitrary_config')
if stop:
if 'CA' in self.model_config.layer_config:
# ECGMM
dim_features = new_layer.dim_node_features, new_layer.C * new_layer.depth + new_layer.CA * new_layer.depth if not new_layer.unibigram else (
new_layer.C + new_layer.CA + new_layer.C * new_layer.C) * new_layer.depth
else:
# CGMM
dim_features = new_layer.dim_node_features, new_layer.C * new_layer.depth if not new_layer.unibigram else (
new_layer.C + new_layer.C * new_layer.C) * new_layer.depth
config = self.model_config.layer_config['arbitrary_function_config']
device = config['device']
predictor_class = s2c(config['predictor'])
model = predictor_class(dim_node_features=dim_features,
dim_edge_features=0,
dim_target=dim_target,
config=config)
predictor_engine = self._create_engine(config, model, device, log_every=self.model_config.log_every)
train_loss, train_score, _, \
val_loss, val_score, _, \
test_loss, test_score, _ = predictor_engine.train(train_loader=train_loader,
validation_loader=val_loader,
test_loader=test_loader,
max_epochs=config['epochs'],
logger=logger)
d = {'train_loss': train_loss, 'train_score': train_score,
'validation_loss': val_loss, 'validation_score': val_score,
'test_loss': test_loss, 'test_score': test_score}
else:
d = {}
# Append layer
layers.append(new_layer)
dict_per_layer.append(d)
# Give priority to arbitrary function
stop = d['stop'] if 'stop' in d else stop
depth += 1
# CLEAR OUTPUTS TO SAVE SPACE
for mode in ['train', 'validation', 'test']:
shutil.rmtree(os.path.join(self.output_folder, mode), ignore_errors=True)
# Use last training and test scores
train_res = {LOSS: dict_per_layer[-1]['train_loss'], SCORE: dict_per_layer[-1]['train_score']}
val_res = {LOSS: dict_per_layer[-1]['validation_loss'], SCORE: dict_per_layer[-1]['validation_score']}
test_res = {LOSS: dict_per_layer[-1]['test_loss'], SCORE: dict_per_layer[-1]['test_score']}
return train_res, val_res, test_res
| 25,222 | 54.557269 | 240 | py |
CGMM | CGMM-master/util.py | from typing import Optional, Tuple, List
import torch
import torch_geometric
def extend_lists(data_list: Optional[Tuple[Optional[List[torch.Tensor]]]],
new_data_list: Tuple[Optional[List[torch.Tensor]]]) -> Tuple[Optional[List[torch.Tensor]]]:
r"""
Extends the semantic of Python :func:`extend()` over lists to tuples
Used e.g., to concatenate results of mini-batches in incremental architectures such as :obj:`CGMM`
Args:
data_list: tuple of lists, or ``None`` if there is no list to extend.
new_data_list: object of the same form of :obj:`data_list` that has to be concatenated
Returns:
the tuple of extended lists
"""
if data_list is None:
return new_data_list
assert len(data_list) == len(new_data_list)
for i in range(len(data_list)):
if new_data_list[i] is not None:
data_list[i].extend(new_data_list[i])
return data_list
def to_tensor_lists(embeddings: Tuple[Optional[torch.Tensor]],
batch: torch_geometric.data.batch.Batch,
edge_index: torch.Tensor) -> Tuple[Optional[List[torch.Tensor]]]:
r"""
Reverts batched outputs back to a list of Tensors elements.
Can be useful to build incremental architectures such as :obj:`CGMM` that store intermediate results
before training the next layer.
Args:
embeddings (tuple): a tuple of embeddings :obj:`(vertex_output, edge_output, graph_output, vertex_extra_output, edge_extra_output, graph_extra_output)`.
Each embedding can be a :class:`torch.Tensor` or ``None``.
batch (:class:`torch_geometric.data.batch.Batch`): Batch information used to split the tensors.
edge_index (:class:`torch.Tensor`): a :obj:`2 x num_edges` tensor as defined in Pytorch Geometric.
Used to split edge Tensors graph-wise.
Returns:
a tuple with the same semantics as the argument ``embeddings``, but this time each element holds a list of
Tensors, one for each graph in the dataset.
"""
# Crucial: Detach the embeddings to free the computation graph!!
# TODO this code can surely be made more compact, but leave it as is until future refactoring or removal from PyDGN.
v_out, e_out, g_out, vo_out, eo_out, go_out = embeddings
v_out = v_out.detach() if v_out is not None else None
v_out_list = [] if v_out is not None else None
e_out = e_out.detach() if e_out is not None else None
e_out_list = [] if e_out is not None else None
g_out = g_out.detach() if g_out is not None else None
g_out_list = [] if g_out is not None else None
vo_out = vo_out.detach() if vo_out is not None else None
vo_out_list = [] if vo_out is not None else None
eo_out = eo_out.detach() if eo_out is not None else None
eo_out_list = [] if eo_out is not None else None
go_out = go_out.detach() if go_out is not None else None
go_out_list = [] if go_out is not None else None
_, node_counts = torch.unique_consecutive(batch, return_counts=True)
node_cumulative = torch.cumsum(node_counts, dim=0)
if e_out is not None or eo_out is not None:
edge_batch = batch[edge_index[0]]
_, edge_counts = torch.unique_consecutive(edge_batch, return_counts=True)
edge_cumulative = torch.cumsum(edge_counts, dim=0)
if v_out_list is not None:
v_out_list.append(v_out[:node_cumulative[0]])
if e_out_list is not None:
e_out_list.append(e_out[:edge_cumulative[0]])
if g_out_list is not None:
g_out_list.append(g_out[0].unsqueeze(0)) # recreate batch dimension by unsqueezing
if vo_out_list is not None:
vo_out_list.append(vo_out[:node_cumulative[0]])
if eo_out_list is not None:
eo_out_list.append(eo_out[:edge_cumulative[0]])
if go_out_list is not None:
go_out_list.append(go_out[0].unsqueeze(0)) # recreate batch dimension by unsqueezing
for i in range(1, len(node_cumulative)):
if v_out_list is not None:
v_out_list.append(v_out[node_cumulative[i - 1]:node_cumulative[i]])
if e_out_list is not None:
e_out_list.append(e_out[edge_cumulative[i - 1]:edge_cumulative[i]])
if g_out_list is not None:
g_out_list.append(g_out[i].unsqueeze(0)) # recreate batch dimension by unsqueezing
if vo_out_list is not None:
vo_out_list.append(vo_out[node_cumulative[i - 1]:node_cumulative[i]])
if eo_out_list is not None:
eo_out_list.append(eo_out[edge_cumulative[i - 1]:edge_cumulative[i]])
if go_out_list is not None:
go_out_list.append(go_out[i].unsqueeze(0)) # recreate batch dimension by unsqueezing
return v_out_list, e_out_list, g_out_list, vo_out_list, eo_out_list, go_out_list
def compute_unigram(posteriors: torch.Tensor, use_continuous_states: bool) -> torch.Tensor:
r"""
Computes the unigram representation of nodes as defined in https://www.jmlr.org/papers/volume21/19-470/19-470.pdf
Args:
posteriors (torch.Tensor): tensor of posterior distributions of nodes with shape `(#nodes,num_latent_states)`
use_continuous_states (bool): whether or not to use the most probable state (one-hot vector) or a "soft" version
Returns:
a tensor of unigrams with shape `(#nodes,num_latent_states)`
"""
num_latent_states = posteriors.shape[1]
if use_continuous_states:
node_embeddings_batch = posteriors
else:
node_embeddings_batch = make_one_hot(posteriors.argmax(dim=1), num_latent_states)
return node_embeddings_batch.double()
def compute_bigram(posteriors: torch.Tensor, edge_index: torch.Tensor, batch: torch.Tensor,
use_continuous_states: bool) -> torch.Tensor:
r"""
Computes the bigram representation of nodes as defined in https://www.jmlr.org/papers/volume21/19-470/19-470.pdf
Args:
posteriors (torch.Tensor): tensor of posterior distributions of nodes with shape `(#nodes,num_latent_states)`
edge_index (torch.Tensor): tensor of edge indices with shape `(2,#edges)` that adheres to PyG specifications
batch (torch.Tensor): vector that assigns each node to a graph id in the batch
use_continuous_states (bool): whether or not to use the most probable state (one-hot vector) or a "soft" version
Returns:
a tensor of bigrams with shape `(#nodes,num_latent_states*num_latent_states)`
"""
C = posteriors.shape[1]
device = posteriors.get_device()
device = 'cpu' if device == -1 else device
if use_continuous_states:
# Code provided by Daniele Atzeni to speed up the computation!
nodes_in_batch = len(batch)
sparse_adj_matrix = torch.sparse.FloatTensor(edge_index,
torch.ones(edge_index.shape[1]).to(device),
torch.Size([nodes_in_batch, nodes_in_batch]))
tmp1 = torch.sparse.mm(sparse_adj_matrix, posteriors.float()).repeat(1, C)
tmp2 = posteriors.reshape(-1, 1).repeat(1, C).reshape(-1, C * C)
node_bigram_batch = torch.mul(tmp1, tmp2)
else:
# Convert into one hot
posteriors_one_hot = make_one_hot(posteriors.argmax(dim=1), C).float()
# Code provided by Daniele Atzeni to speed up the computation!
nodes_in_batch = len(batch)
sparse_adj_matrix = torch.sparse.FloatTensor(edge_index,
torch.ones(edge_index.shape[1]).to(device),
torch.Size([nodes_in_batch, nodes_in_batch]))
tmp1 = torch.sparse.mm(sparse_adj_matrix, posteriors_one_hot).repeat(1, C)
tmp2 = posteriors_one_hot.reshape(-1, 1).repeat(1, C).reshape(-1, C * C)
node_bigram_batch = torch.mul(tmp1, tmp2)
return node_bigram_batch.double()
def make_one_hot(labels: torch.Tensor, num_unique_ids: torch.Tensor) -> torch.Tensor:
r"""
Converts a vector of ids into a one-hot matrix
Args:
labels (torch.Tensor): the vector of ids
num_unique_ids (torch.Tensor): number of unique ids
Returns:
a one-hot tensor with shape `(samples,num_unique_ids)`
"""
device = labels.get_device()
device = 'cpu' if device == -1 else device
one_hot = torch.zeros(labels.size(0), num_unique_ids).to(device)
one_hot[torch.arange(labels.size(0)).to(device), labels] = 1
return one_hot
| 8,585 | 41.50495 | 160 | py |
CGMM | CGMM-master/incremental_engine.py | import torch
from pydgn.training.engine import TrainingEngine
from util import extend_lists, to_tensor_lists
class IncrementalTrainingEngine(TrainingEngine):
def __init__(self, engine_callback, model, loss, **kwargs):
super().__init__(engine_callback, model, loss, **kwargs)
def _to_list(self, data_list, embeddings, batch, edge_index, y):
if isinstance(embeddings, tuple):
embeddings = tuple([e.detach().cpu() if e is not None else None for e in embeddings])
elif isinstance(embeddings, torch.Tensor):
embeddings = embeddings.detach().cpu()
else:
raise NotImplementedError('Embeddings not understood, should be Tensor or Tuple of Tensors')
data_list = extend_lists(data_list, to_tensor_lists(embeddings, batch, edge_index))
return data_list | 838 | 40.95 | 104 | py |
CGMM | CGMM-master/cgmm_classifier_task.py | import os
import torch
from cgmm_incremental_task import CGMMTask
from pydgn.experiment.util import s2c
from pydgn.static import LOSS, SCORE
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader
# This works with graph classification only
class ClassifierCGMMTask(CGMMTask):
def run_valid(self, dataset_getter, logger):
"""
This function returns the training and validation or test accuracy
:return: (training accuracy, validation/test accuracy)
"""
# Necessary info to give a unique name to the dataset (some hyper-params like epochs are assumed to be fixed)
embeddings_folder = self.model_config.layer_config['embeddings_folder']
max_layers = self.model_config.layer_config['max_layers']
layers = self.model_config.layer_config['layers']
unibigram = self.model_config.layer_config['unibigram']
C = self.model_config.layer_config['C']
CA = self.model_config.layer_config['CA'] if 'CA' in self.model_config.layer_config else None
aggregation = self.model_config.layer_config['aggregation']
infer_with_posterior = self.model_config.layer_config['infer_with_posterior']
outer_k = dataset_getter.outer_k
inner_k = dataset_getter.inner_k
# ====
base_path = os.path.join(embeddings_folder, dataset_getter.dataset_name,
f'{max_layers}_{unibigram}_{C}_{CA}_{aggregation}_{infer_with_posterior}_{outer_k + 1}_{inner_k + 1}')
train_out_emb = torch.load(base_path + '_train.torch')[:, :layers, :]
val_out_emb = torch.load(base_path + '_val.torch')[:, :layers, :]
train_out_emb = torch.reshape(train_out_emb, (train_out_emb.shape[0], -1))
val_out_emb = torch.reshape(val_out_emb, (val_out_emb.shape[0], -1))
# Recover the targets
fake_train_loader = dataset_getter.get_inner_train(batch_size=1, shuffle=False)
fake_val_loader = dataset_getter.get_inner_val(batch_size=1, shuffle=False)
train_y = [el.y for el in fake_train_loader.dataset]
val_y = [el.y for el in fake_val_loader.dataset]
arbitrary_logic_batch_size = self.model_config.layer_config['arbitrary_function_config']['batch_size']
arbitrary_logic_shuffle = self.model_config.layer_config['arbitrary_function_config']['shuffle'] \
if 'shuffle' in self.model_config.layer_config['arbitrary_function_config'] else True
# build data lists
train_list = [Data(x=train_out_emb[i].unsqueeze(0), y=train_y[i]) for i in range(train_out_emb.shape[0])]
val_list = [Data(x=val_out_emb[i].unsqueeze(0), y=val_y[i]) for i in range(val_out_emb.shape[0])]
train_loader = DataLoader(train_list, batch_size=arbitrary_logic_batch_size, shuffle=arbitrary_logic_shuffle)
val_loader = DataLoader(val_list, batch_size=arbitrary_logic_batch_size, shuffle=arbitrary_logic_shuffle)
# Instantiate the Dataset
dim_features = train_out_emb.shape[1]
dim_target = dataset_getter.get_dim_target()
config = self.model_config.layer_config['arbitrary_function_config']
device = config['device']
predictor_class = s2c(config['readout'])
model = predictor_class(dim_node_features=dim_features,
dim_edge_features=0,
dim_target=dim_target,
config=config)
predictor_engine = self._create_engine(config, model, device, evaluate_every=self.model_config.evaluate_every)
train_loss, train_score, _, \
val_loss, val_score, _, \
_, _, _ = predictor_engine.train(train_loader=train_loader,
validation_loader=val_loader,
test_loader=None,
max_epochs=config['epochs'],
logger=logger)
train_res = {LOSS: train_loss, SCORE: train_score}
val_res = {LOSS: val_loss, SCORE: val_score}
return train_res, val_res
def run_test(self, dataset_getter, logger):
"""
This function returns the training and test accuracy. DO NOT USE THE TEST FOR ANY REASON
:return: (training accuracy, test accuracy)
"""
# Necessary info to give a unique name to the dataset (some hyper-params like epochs are assumed to be fixed)
embeddings_folder = self.model_config.layer_config['embeddings_folder']
max_layers = self.model_config.layer_config['max_layers']
layers = self.model_config.layer_config['layers']
unibigram = self.model_config.layer_config['unibigram']
C = self.model_config.layer_config['C']
CA = self.model_config.layer_config['CA'] if 'CA' in self.model_config.layer_config else None
aggregation = self.model_config.layer_config['aggregation']
infer_with_posterior = self.model_config.layer_config['infer_with_posterior']
outer_k = dataset_getter.outer_k
inner_k = dataset_getter.inner_k
if inner_k is None: # workaround the "safety" procedure of evaluation protocol, but we will not do anything wrong.
dataset_getter.set_inner_k(0)
inner_k = 0 # pick the split of the first inner fold
# ====
# NOTE: We reload the associated inner train and val splits, using the outer_test for assessment.
# This is slightly different from standard exps, where we compute a different outer train-val split, but it should not change things much.
base_path = os.path.join(embeddings_folder, dataset_getter.dataset_name,
f'{max_layers}_{unibigram}_{C}_{CA}_{aggregation}_{infer_with_posterior}_{outer_k + 1}_{inner_k + 1}')
train_out_emb = torch.load(base_path + '_train.torch')[:, :layers, :]
val_out_emb = torch.load(base_path + '_val.torch')[:, :layers, :]
test_out_emb = torch.load(base_path + '_test.torch')[:, :layers, :]
train_out_emb = torch.reshape(train_out_emb, (train_out_emb.shape[0], -1))
val_out_emb = torch.reshape(val_out_emb, (val_out_emb.shape[0], -1))
test_out_emb = torch.reshape(test_out_emb, (test_out_emb.shape[0], -1))
# Recover the targets
fake_train_loader = dataset_getter.get_inner_train(batch_size=1, shuffle=False)
fake_val_loader = dataset_getter.get_inner_val(batch_size=1, shuffle=False)
fake_test_loader = dataset_getter.get_outer_test(batch_size=1, shuffle=False)
train_y = [el.y for el in fake_train_loader.dataset]
val_y = [el.y for el in fake_val_loader.dataset]
test_y = [el.y for el in fake_test_loader.dataset]
arbitrary_logic_batch_size = self.model_config.layer_config['arbitrary_function_config']['batch_size']
arbitrary_logic_shuffle = self.model_config.layer_config['arbitrary_function_config']['shuffle'] \
if 'shuffle' in self.model_config.layer_config['arbitrary_function_config'] else True
# build data lists
train_list = [Data(x=train_out_emb[i].unsqueeze(0), y=train_y[i]) for i in range(train_out_emb.shape[0])]
val_list = [Data(x=val_out_emb[i].unsqueeze(0), y=val_y[i]) for i in range(val_out_emb.shape[0])]
test_list = [Data(x=test_out_emb[i].unsqueeze(0), y=test_y[i]) for i in range(test_out_emb.shape[0])]
train_loader = DataLoader(train_list, batch_size=arbitrary_logic_batch_size, shuffle=arbitrary_logic_shuffle)
val_loader = DataLoader(val_list, batch_size=arbitrary_logic_batch_size, shuffle=arbitrary_logic_shuffle)
test_loader = DataLoader(test_list, batch_size=arbitrary_logic_batch_size, shuffle=arbitrary_logic_shuffle)
# Instantiate the Dataset
dim_features = train_out_emb.shape[1]
dim_target = dataset_getter.get_dim_target()
config = self.model_config.layer_config['arbitrary_function_config']
device = config['device']
predictor_class = s2c(config['readout'])
model = predictor_class(dim_node_features=dim_features,
dim_edge_features=0,
dim_target=dim_target,
config=config)
predictor_engine = self._create_engine(config, model, device, evaluate_every=self.model_config.evaluate_every)
train_loss, train_score, _, \
val_loss, val_score, _, \
test_loss, test_score, _ = predictor_engine.train(train_loader=train_loader,
validation_loader=val_loader,
test_loader=test_loader,
max_epochs=config['epochs'],
logger=logger)
train_res = {LOSS: train_loss, SCORE: train_score}
val_res = {LOSS: val_loss, SCORE: val_score}
test_res = {LOSS: test_loss, SCORE: test_score}
return train_res, val_res, test_res
| 9,149 | 55.481481 | 146 | py |
CGMM | CGMM-master/provider.py | import random
import numpy as np
from pydgn.data.dataset import ZipDataset
from pydgn.data.provider import DataProvider
from pydgn.data.sampler import RandomSampler
from torch.utils.data import Subset
def seed_worker(exp_seed, worker_id):
np.random.seed(exp_seed + worker_id)
random.seed(exp_seed + worker_id)
class IncrementalDataProvider(DataProvider):
"""
An extension of the DataProvider class to deal with the intermediate outputs produced by incremental architectures
Used by CGMM to deal with node/graph classification/regression.
"""
def _get_loader(self, indices, **kwargs):
"""
Takes the "extra" argument from kwargs and zips it together with the original data into a ZipDataset
:param indices: indices of the subset of the data to be extracted
:param kwargs: an arbitrary dictionary
:return: a DataLoader
"""
dataset = self._get_dataset()
dataset = Subset(dataset, indices)
dataset_extra = kwargs.pop("extra", None)
if dataset_extra is not None and isinstance(dataset_extra, list) and len(dataset_extra) > 0:
assert len(dataset) == len(dataset_extra), (dataset, dataset_extra)
datasets = [dataset, dataset_extra]
dataset = ZipDataset(datasets)
elif dataset_extra is None or (isinstance(dataset_extra, list) and len(dataset_extra) == 0):
pass
else:
raise NotImplementedError("Check that extra is None, an empty list or a non-empty list")
shuffle = kwargs.pop("shuffle", False)
assert self.exp_seed is not None, 'DataLoader seed has not been specified! Is this a bug?'
kwargs['worker_init_fn'] = lambda worker_id: seed_worker(worker_id, self.exp_seed)
kwargs.update(self.data_loader_args)
if shuffle is True:
sampler = RandomSampler(dataset)
dataloader = self.data_loader_class(dataset, sampler=sampler,
**kwargs)
else:
dataloader = self.data_loader_class(dataset, shuffle=False,
**kwargs)
return dataloader
| 2,201 | 37.631579 | 118 | py |
BVQI | BVQI-master/temporal_naturalness.py | import torch
import argparse
import pickle as pkl
import numpy as np
import math
import torch
import torch.nn.functional as F
import yaml
from scipy.stats import pearsonr, spearmanr
from scipy.stats import kendalltau as kendallr
from tqdm import tqdm
from sklearn import decomposition
import time
from buona_vista import datasets
from V1_extraction.gabor_filter import GaborFilters
from V1_extraction.utilities import compute_v1_curvature, compute_discrete_v1_curvature
class PCA:
def __init__(self, n_components):
self.n_components = n_components
def fit_transform(self, X):
# Center the data
X_centered = X - X.mean(dim=0)
# Compute the SVD
U, S, V = torch.svd(X_centered)
# Compute the principal components
components = V[:, :self.n_components]
# Project the data onto the principal components
scores = torch.matmul(X_centered, components)
return scores
def rescale(x):
x = np.array(x)
x = (x - x.mean()) / x.std()
return 1 / (1 + np.exp(x))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-o",
"--opt",
type=str,
default="buona_vista_tn_index.yml",
help="the option file",
)
parser.add_argument(
"-d", "--device", type=str, default="cuda", help="the running device"
)
args = parser.parse_args()
results = {}
with open(args.opt, "r") as f:
opt = yaml.safe_load(f)
scale = 6
orientations = 8
kernel_size = 39
row_downsample = 4
column_downsample = 4
pca_d = 5
frame_bs = 32
pca = PCA(pca_d)
gb = GaborFilters(scale,
orientations, (kernel_size - 1) // 2,
row_downsample,
column_downsample,
device=args.device
)
val_datasets = {}
for name, dataset in opt["data"].items():
val_datasets[name] = getattr(datasets, dataset["type"])(dataset["args"])
for val_name, val_dataset in val_datasets.items():
prs, gts = [], []
results[val_name] = {"gt": [], "tn_index": []}
val_loader = torch.utils.data.DataLoader(
val_dataset, batch_size=1, num_workers=opt["num_workers"], pin_memory=True,
)
for i, data in enumerate(tqdm(val_loader, desc=f"Evaluating in dataset [{val_name}].")):
with torch.no_grad():
video_frames = data["original_tn"].squeeze(0).to(args.device).transpose(0,1)
if video_frames.shape[-1] > 600:
video_frames = F.interpolate(video_frames, (270,480))
video_frames = video_frames.mean(1,keepdim=True)
zero_frames = torch.zeros(video_frames.shape).to(args.device)
complex_frames = torch.stack((video_frames, zero_frames), -1)
video_frames = torch.view_as_complex(complex_frames)
v1_features = []
for i in range((video_frames.shape[0] - 1) // frame_bs):
these_frames = video_frames[i * frame_bs:(i+1)* frame_bs]
with torch.no_grad():
these_features = gb(these_frames)
v1_features.append(these_features)
last_start = ((video_frames.shape[0] - 1) // frame_bs) * frame_bs
v1_features += [gb(video_frames[last_start:])]
v1_features = torch.cat(v1_features, 0)
v1_features = torch.nan_to_num(v1_features)
v1_PCA = pca.fit_transform(v1_features)
v1_score = compute_v1_curvature(v1_PCA.cpu().numpy(), fsize=8)
try:
temporal_naturalness_index = math.log(np.mean(v1_score))
except:
#print(np.mean(v1_score))
temporal_naturalness_index = min(prs) - 1
results[val_name]["tn_index"].append(temporal_naturalness_index)
if not np.isnan(temporal_naturalness_index):
prs.append(temporal_naturalness_index)
gts.append(data["gt_label"][0].item())
#if i % 200 == 0:
#print(i)
#print(spearmanr(prs, gts)[0])
# Sigmoid-like Rescaling
prs = rescale(prs)
#results[val_name]["tn_index"] = rescale(results[val_name]["tn_index"])
with open("temporal_naturalness_39.pkl", "wb") as f:
pkl.dump(results, f)
print(
"Dataset:",
val_name,
"Length:",
len(val_dataset),
"SRCC:",
spearmanr(prs, gts)[0],
"PLCC:",
pearsonr(prs, gts)[0],
"KRCC:",
kendallr(prs, gts)[0],
) | 4,901 | 30.625806 | 96 | py |
BVQI | BVQI-master/semantic_affinity.py | ## Contributed by Teo Haoning Wu, Daniel Annan Wang
import argparse
import pickle as pkl
import open_clip
import numpy as np
import torch
import yaml
from scipy.stats import pearsonr, spearmanr
from scipy.stats import kendalltau as kendallr
from tqdm import tqdm
from buona_vista import datasets
def rescale(x):
x = np.array(x)
x = (x - x.mean()) / x.std()
return 1 / (1 + np.exp(-x))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-o",
"--opt",
type=str,
default="./buona_vista_sa_index.yml",
help="the option file",
)
parser.add_argument(
"-d", "--device", type=str, default="cuda", help="the running device"
)
parser.add_argument(
"-l", "--local", action="store_true", help="Use BVQI-Local"
)
args = parser.parse_args()
with open(args.opt, "r") as f:
opt = yaml.safe_load(f)
val_datasets = {}
for name, dataset in opt["data"].items():
val_datasets[name] = getattr(datasets, dataset["type"])(dataset["args"])
print(open_clip.list_pretrained())
model, _, preprocess = open_clip.create_model_and_transforms("RN50",pretrained="openai")
model = model.to(args.device)
print("loading succeed")
texts = [
"a high quality photo",
"a low quality photo",
"a good photo",
"a bad photo",
]
tokenizer = open_clip.get_tokenizer("RN50")
text_tokens = tokenizer(texts).to(args.device)
print(f"Prompt_loading_succeed, {texts}")
results = {}
for val_name, val_dataset in val_datasets.items():
prs, gts = [], []
results[val_name] = {"gt": [], "sa_index": [], "raw_index": []}
val_loader = torch.utils.data.DataLoader(
val_dataset, batch_size=1, num_workers=opt["num_workers"], pin_memory=True,
)
for i, data in enumerate(tqdm(val_loader, desc=f"Evaluating in dataset [{val_name}].")):
video_frames = data["aesthetic"].squeeze(0)
image_input = torch.transpose(video_frames, 0, 1).to(args.device)
with torch.no_grad():
image_features = model.encode_image(image_input).float() #.mean(0)
text_features = model.encode_text(text_tokens).float()
logits_per_image = image_features @ text_features.T
#logits_per_image = logits_per_image.softmax(dim=-1)
#logits_per_image, logits_per_text = model(image_input, text_tokens)
probs_a = logits_per_image.cpu().numpy()
semantic_affinity_index = 0
for k in [0,1]:
pn_pair = torch.from_numpy(probs_a[..., 2 * k : 2 * k + 2]).float().numpy()
semantic_affinity_index += pn_pair[...,0] - pn_pair[...,1]
if args.local:
# Use the local feature after AttnPooling
prs.append(semantic_affinity_index[1:].mean())
else:
# Use the global feature after AttnPooling
prs.append(semantic_affinity_index[0].mean())
results[val_name]["gt"].append(data["gt_label"][0].item())
gts.append(data["gt_label"][0].item())
results[val_name]["raw_index"].append(semantic_affinity_index)
prs = rescale(prs)
with open("semantic_affinity_pubs.pkl", "wb") as f:
results[val_name]["sa_index"] = prs
pkl.dump(results, f)
print(
"Dataset:",
val_name,
"Length:",
len(val_dataset),
"SRCC:",
spearmanr(prs, gts)[0],
"PLCC:",
pearsonr(prs, gts)[0],
"KRCC:",
kendallr(prs, gts)[0],
)
| 3,856 | 30.614754 | 96 | py |
BVQI | BVQI-master/spatial_naturalness.py | # Contributed by Teo Haoning Wu, Erli Zhang Karl
import argparse
import glob
import math
import os
import pickle as pkl
from collections import OrderedDict
import decord
import numpy as np
import torch
import torchvision as tv
import yaml
from pyiqa import create_metric
from pyiqa.default_model_configs import DEFAULT_CONFIGS
from pyiqa.utils.img_util import imread2tensor
from pyiqa.utils.registry import ARCH_REGISTRY
from scipy.stats import kendalltau as kendallr
from scipy.stats import pearsonr, spearmanr
from tqdm import tqdm
from torch.nn.functional import interpolate
from buona_vista.datasets import ViewDecompositionDataset
from skvideo.measure import niqe
def rescale(x):
x = np.array(x)
x = (x - x.mean()) / x.std()
return 1 / (1 + np.exp(x))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-o",
"--opt",
type=str,
default="./buona_vista_sn_index.yml",
help="the option file",
)
parser.add_argument(
"-d", "--device", type=str, default="cuda", help="the running device"
)
args = parser.parse_args()
with open(args.opt, "r") as f:
opt = yaml.safe_load(f)
metric_name = "niqe"
# set up IQA model
iqa_model = create_metric(metric_name, metric_mode="NR")
# pbar = tqdm(total=test_img_num, unit='image')
lower_better = DEFAULT_CONFIGS[metric_name].get("lower_better", False)
device = args.device
net_opts = OrderedDict()
kwargs = {}
if metric_name in DEFAULT_CONFIGS.keys():
default_opt = DEFAULT_CONFIGS[metric_name]["metric_opts"]
net_opts.update(default_opt)
# then update with custom setting
net_opts.update(kwargs)
network_type = net_opts.pop("type")
net = ARCH_REGISTRY.get(network_type)(**net_opts)
net = net.to(device)
for key in opt["data"].keys():
if "val" not in key and "test" not in key:
continue
dopt = opt["data"][key]["args"]
val_dataset = ViewDecompositionDataset(dopt)
val_loader = torch.utils.data.DataLoader(
val_dataset, batch_size=1, num_workers=opt["num_workers"], pin_memory=True,
)
pr_labels, gt_labels = [], []
for data in tqdm(val_loader, desc=f"Evaluating in dataset [{key}]."):
target = (
data["original"].squeeze(0).transpose(0, 1)
) # C, T, H, W to N(T), C, H, W
if min(target.shape[2:]) < 224:
target = interpolate(target, scale_factor = 224 / min(target.shape[2:]))
with torch.no_grad():
score = net((target.to(device))).mean().item()
if math.isnan(score):
print(score, target.shape)
score = max(pr_labels) + 1
#with open(output_result_csv, "a") as w:
# w.write(f'{data["name"][0]}, {score}\n')
pr_labels.append(score)
gt_labels.append(data["gt_label"].item())
pr_labels = rescale(pr_labels)
s = spearmanr(gt_labels, pr_labels)[0]
p = pearsonr(gt_labels, pr_labels)[0]
k = kendallr(gt_labels, pr_labels)[0]
with open(f"spatial_naturalness_{key}.pkl", "wb") as f:
pkl.dump({"pr_labels": pr_labels,
"gt_labels": gt_labels}, f)
print(s, p, k)
| 3,380 | 28.657895 | 88 | py |
Subsets and Splits