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!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

input.py 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #
  2. # Copyright (C) Stanislaw Adaszewski, 2020
  3. # License: GPLv3
  4. #
  5. import torch
  6. from typing import Union, \
  7. List
  8. from .data import Data
  9. class InputLayer(torch.nn.Module):
  10. def __init__(self, data: Data, output_dim: Union[int, List[int]] = None, **kwargs) -> None:
  11. output_dim = output_dim or \
  12. list(map(lambda a: a.count, data.node_types))
  13. if not isinstance(output_dim, list):
  14. output_dim = [output_dim,] * len(data.node_types)
  15. super().__init__(**kwargs)
  16. self.output_dim = output_dim
  17. self.data = data
  18. self.is_sparse=False
  19. self.node_reps = None
  20. self.build()
  21. def build(self) -> None:
  22. self.node_reps = []
  23. for i, nt in enumerate(self.data.node_types):
  24. reps = torch.rand(nt.count, self.output_dim[i])
  25. reps = torch.nn.Parameter(reps)
  26. self.register_parameter('node_reps[%d]' % i, reps)
  27. self.node_reps.append(reps)
  28. def forward(self, x) -> List[torch.nn.Parameter]:
  29. return self.node_reps
  30. def __repr__(self) -> str:
  31. s = ''
  32. s += 'Icosagon input layer with output_dim: %s\n' % self.output_dim
  33. s += ' # of node types: %d\n' % len(self.data.node_types)
  34. for nt in self.data.node_types:
  35. s += ' - %s (%d)\n' % (nt.name, nt.count)
  36. return s.strip()
  37. class OneHotInputLayer(torch.nn.Module):
  38. def __init__(self, data: Data, **kwargs) -> None:
  39. output_dim = [ a.count for a in data.node_types ]
  40. super().__init__(**kwargs)
  41. self.output_dim = output_dim
  42. self.data = data
  43. self.is_sparse=True
  44. self.node_reps = None
  45. self.build()
  46. def build(self) -> None:
  47. self.node_reps = []
  48. for i, nt in enumerate(self.data.node_types):
  49. reps = torch.eye(nt.count).to_sparse()
  50. reps = torch.nn.Parameter(reps)
  51. self.register_parameter('node_reps[%d]' % i, reps)
  52. self.node_reps.append(reps)
  53. def forward(self, x) -> List[torch.nn.Parameter]:
  54. return self.node_reps
  55. def __repr__(self) -> str:
  56. s = ''
  57. s += 'One-hot Icosagon input layer\n'
  58. s += ' # of node types: %d\n' % len(self.data.node_types)
  59. for nt in self.data.node_types:
  60. s += ' - %s (%d)\n' % (nt.name, nt.count)
  61. return s.strip()