viterbi_decode.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from paddle import _C_ops
  15. from ..base.data_feeder import check_type, check_variable_and_dtype
  16. from ..base.framework import in_dynamic_or_pir_mode
  17. from ..base.layer_helper import LayerHelper
  18. from ..nn import Layer
  19. __all__ = ['viterbi_decode', 'ViterbiDecoder']
  20. def viterbi_decode(
  21. potentials, transition_params, lengths, include_bos_eos_tag=True, name=None
  22. ):
  23. """
  24. Decode the highest scoring sequence of tags computed by transitions and potentials and get the viterbi path.
  25. Args:
  26. potentials (Tensor): The input tensor of unary emission. This is a 3-D
  27. tensor with shape of [batch_size, sequence_length, num_tags]. The data type is float32 or float64.
  28. transition_params (Tensor): The input tensor of transition matrix. This is a 2-D
  29. tensor with shape of [num_tags, num_tags]. The data type is float32 or float64.
  30. lengths (Tensor): The input tensor of length of each sequence. This is a 1-D tensor with shape of [batch_size]. The data type is int64.
  31. include_bos_eos_tag (`bool`, optional): If set to True, the last row and the last column of transitions will be considered
  32. as start tag, the second to last row and the second to last column of transitions will be considered as stop tag. Defaults to ``True``.
  33. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please
  34. refer to :ref:`api_guide_Name`.
  35. Returns:
  36. scores(Tensor): The output tensor containing the score for the Viterbi sequence. The shape is [batch_size]
  37. and the data type is float32 or float64.
  38. paths(Tensor): The output tensor containing the highest scoring tag indices. The shape is [batch_size, sequence_length]
  39. and the data type is int64.
  40. Examples:
  41. .. code-block:: python
  42. >>> import paddle
  43. >>> paddle.seed(2023)
  44. >>> batch_size, seq_len, num_tags = 2, 4, 3
  45. >>> emission = paddle.rand((batch_size, seq_len, num_tags), dtype='float32')
  46. >>> length = paddle.randint(1, seq_len + 1, [batch_size])
  47. >>> tags = paddle.randint(0, num_tags, [batch_size, seq_len])
  48. >>> transition = paddle.rand((num_tags, num_tags), dtype='float32')
  49. >>> scores, path = paddle.text.viterbi_decode(emission, transition, length, False)
  50. >>> print(scores)
  51. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  52. [2.57385254, 2.04533720])
  53. >>> print(path)
  54. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  55. [[0, 0],
  56. [1, 1]])
  57. """
  58. if in_dynamic_or_pir_mode():
  59. return _C_ops.viterbi_decode(
  60. potentials, transition_params, lengths, include_bos_eos_tag
  61. )
  62. check_variable_and_dtype(
  63. potentials, 'input', ['float32', 'float64'], 'viterbi_decode'
  64. )
  65. check_variable_and_dtype(
  66. transition_params,
  67. 'transitions',
  68. ['float32', 'float64'],
  69. 'viterbi_decode',
  70. )
  71. check_variable_and_dtype(lengths, 'length', 'int64', 'viterbi_decode')
  72. check_type(include_bos_eos_tag, 'include_tag', bool, 'viterbi_decode')
  73. helper = LayerHelper('viterbi_decode', **locals())
  74. attrs = {'include_bos_eos_tag': include_bos_eos_tag}
  75. scores = helper.create_variable_for_type_inference(potentials.dtype)
  76. path = helper.create_variable_for_type_inference('int64')
  77. helper.append_op(
  78. type='viterbi_decode',
  79. inputs={
  80. 'Input': potentials,
  81. 'Transition': transition_params,
  82. 'Length': lengths,
  83. },
  84. outputs={'Scores': scores, 'Path': path},
  85. attrs=attrs,
  86. )
  87. return scores, path
  88. class ViterbiDecoder(Layer):
  89. """
  90. Decode the highest scoring sequence of tags computed by transitions and potentials and get the viterbi path.
  91. Args:
  92. transitions (`Tensor`): The transition matrix. Its dtype is float32 and has a shape of `[num_tags, num_tags]`.
  93. include_bos_eos_tag (`bool`, optional): If set to True, the last row and the last column of transitions will be considered
  94. as start tag, the second to last row and the second to last column of transitions will be considered as stop tag. Defaults to ``True``.
  95. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please
  96. refer to :ref:`api_guide_Name`.
  97. Shape:
  98. potentials (Tensor): The input tensor of unary emission. This is a 3-D tensor with shape of
  99. [batch_size, sequence_length, num_tags]. The data type is float32 or float64.
  100. lengths (Tensor): The input tensor of length of each sequence. This is a 1-D tensor with shape of
  101. [batch_size]. The data type is int64.
  102. Returns:
  103. scores(Tensor): The output tensor containing the score for the Viterbi sequence. The shape is [batch_size]
  104. and the data type is float32 or float64.
  105. paths(Tensor): The output tensor containing the highest scoring tag indices. The shape is [batch_size, sequence_length]
  106. and the data type is int64.
  107. Examples:
  108. .. code-block:: python
  109. >>> import paddle
  110. >>> paddle.seed(2023)
  111. >>> batch_size, seq_len, num_tags = 2, 4, 3
  112. >>> emission = paddle.rand((batch_size, seq_len, num_tags), dtype='float32')
  113. >>> length = paddle.randint(1, seq_len + 1, [batch_size])
  114. >>> tags = paddle.randint(0, num_tags, [batch_size, seq_len])
  115. >>> transition = paddle.rand((num_tags, num_tags), dtype='float32')
  116. >>> decoder = paddle.text.ViterbiDecoder(transition, include_bos_eos_tag=False)
  117. >>> scores, path = decoder(emission, length)
  118. >>> print(scores)
  119. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  120. [2.57385254, 2.04533720])
  121. >>> print(path)
  122. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  123. [[0, 0],
  124. [1, 1]])
  125. """
  126. def __init__(self, transitions, include_bos_eos_tag=True, name=None):
  127. super().__init__()
  128. self.transitions = transitions
  129. self.include_bos_eos_tag = include_bos_eos_tag
  130. self.name = name
  131. def forward(self, potentials, lengths):
  132. return viterbi_decode(
  133. potentials,
  134. self.transitions,
  135. lengths,
  136. self.include_bos_eos_tag,
  137. self.name,
  138. )