IF YOU WOULD LIKE TO GET AN ACCOUNT, please write an email to s dot adaszewski at gmail dot com. User accounts are meant only to report issues and/or generate pull requests. This is a purpose-specific Git hosting for ADARED projects. Thank you for your understanding!
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

77 Zeilen
2.7KB

  1. #
  2. # Copyright (C) Stanislaw Adaszewski, 2020
  3. # License: GPLv3
  4. #
  5. import torch
  6. from .data import Data
  7. from .trainprep import PreparedData, \
  8. TrainValTest
  9. from typing import Type, \
  10. List, \
  11. Callable, \
  12. Union, \
  13. Dict, \
  14. Tuple
  15. from .decode import DEDICOMDecoder
  16. class DecodeLayer(torch.nn.Module):
  17. def __init__(self,
  18. input_dim: List[int],
  19. data: Union[Data, PreparedData],
  20. keep_prob: float = 1.,
  21. decoder_class: Union[Type, Dict[Tuple[int, int], Type]] = DEDICOMDecoder,
  22. activation: Callable[[torch.Tensor], torch.Tensor] = torch.sigmoid,
  23. **kwargs) -> None:
  24. super().__init__(**kwargs)
  25. assert all([ a == input_dim[0] \
  26. for a in input_dim ])
  27. self.input_dim = input_dim
  28. self.output_dim = 1
  29. self.data = data
  30. self.keep_prob = keep_prob
  31. self.decoder_class = decoder_class
  32. self.activation = activation
  33. self.decoders = None
  34. self.build()
  35. def build(self) -> None:
  36. self.decoders = {}
  37. for (node_type_row, node_type_column), rels in self.data.relation_types.items():
  38. if len(rels) == 0:
  39. continue
  40. if isinstance(self.decoder_class, dict):
  41. if (node_type_row, node_type_column) in self.decoder_class:
  42. decoder_class = self.decoder_class[node_type_row, node_type_column]
  43. elif (node_type_column, node_type_row) in self.decoder_class:
  44. decoder_class = self.decoder_class[node_type_column, node_type_row]
  45. else:
  46. raise KeyError('Decoder not specified for edge type: %s -- %s' % (
  47. self.data.node_types[node_type_row].name,
  48. self.data.node_types[node_type_column].name))
  49. else:
  50. decoder_class = self.decoder_class
  51. self.decoders[node_type_row, node_type_column] = \
  52. decoder_class(self.input_dim[node_type_row],
  53. num_relation_types = len(rels),
  54. keep_prob = self.keep_prob,
  55. activation = self.activation)
  56. def forward(self, last_layer_repr: List[torch.Tensor]) -> Dict[Tuple[int, int], List[torch.Tensor]]:
  57. res = {}
  58. for (node_type_row, node_type_column), dec in self.decoders.items():
  59. inputs_row = last_layer_repr[node_type_row]
  60. inputs_column = last_layer_repr[node_type_column]
  61. pred_adj_matrices = [ dec(inputs_row, inputs_column, k) for k in range(dec.num_relation_types) ]
  62. res[node_type_row, node_type_column] = pred_adj_matrices
  63. return res