(self, tensor_type: Union[None, str, TensorType], prepend_batch_axis: bool = False)
| 474 | return self._encodings[batch_index].char_to_word(char_index) |
| 475 | |
| 476 | def convert_to_tensors(self, tensor_type: Union[None, str, TensorType], prepend_batch_axis: bool = False): |
| 477 | if tensor_type is None: |
| 478 | return self |
| 479 | |
| 480 | # Convert to TensorType |
| 481 | if not isinstance(tensor_type, TensorType): |
| 482 | tensor_type = TensorType(tensor_type) |
| 483 | |
| 484 | # Get a function reference for the correct framework |
| 485 | if tensor_type == TensorType.TENSORFLOW and is_tf_available(): |
| 486 | as_tensor = tf.constant |
| 487 | elif tensor_type == TensorType.PYTORCH and is_torch_available(): |
| 488 | as_tensor = torch.tensor |
| 489 | elif tensor_type == TensorType.NUMPY: |
| 490 | as_tensor = np.asarray |
| 491 | else: |
| 492 | raise ImportError( |
| 493 | "Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format( |
| 494 | tensor_type |
| 495 | ) |
| 496 | ) |
| 497 | |
| 498 | # Do the tensor conversion in batch |
| 499 | for key, value in self.items(): |
| 500 | try: |
| 501 | if prepend_batch_axis: |
| 502 | value = [value] |
| 503 | |
| 504 | tensor = as_tensor(value) |
| 505 | |
| 506 | # at-least2d |
| 507 | if tensor.ndim > 2: |
| 508 | tensor = tensor.squeeze(0) |
| 509 | elif tensor.ndim < 2: |
| 510 | tensor = tensor[None, :] |
| 511 | |
| 512 | self[key] = tensor |
| 513 | except: # noqa E722 |
| 514 | raise ValueError( |
| 515 | "Unable to create tensor, you should probably activate truncation and/or padding " |
| 516 | "with 'padding=True' 'truncation=True' to have batched tensors with the same length." |
| 517 | ) |
| 518 | |
| 519 | return self |
| 520 | |
| 521 | @torch_required |
| 522 | def to(self, device: str): |
no test coverage detected