Create a numpy ndarray from a tensor. Create a numpy ndarray with the same shape and data as the tensor. Args: tensor: A TensorProto. Returns: A numpy array with the tensor contents. Raises: TypeError: if tensor has unsupported type.
(tensor)
| 561 | |
| 562 | @tf_export("make_ndarray") |
| 563 | def MakeNdarray(tensor): |
| 564 | """Create a numpy ndarray from a tensor. |
| 565 | |
| 566 | Create a numpy ndarray with the same shape and data as the tensor. |
| 567 | |
| 568 | Args: |
| 569 | tensor: A TensorProto. |
| 570 | |
| 571 | Returns: |
| 572 | A numpy array with the tensor contents. |
| 573 | |
| 574 | Raises: |
| 575 | TypeError: if tensor has unsupported type. |
| 576 | |
| 577 | """ |
| 578 | shape = [d.size for d in tensor.tensor_shape.dim] |
| 579 | num_elements = np.prod(shape, dtype=np.int64) |
| 580 | tensor_dtype = dtypes.as_dtype(tensor.dtype) |
| 581 | dtype = tensor_dtype.as_numpy_dtype |
| 582 | |
| 583 | if tensor.tensor_content: |
| 584 | return (np.frombuffer(tensor.tensor_content, |
| 585 | dtype=dtype).copy().reshape(shape)) |
| 586 | |
| 587 | if tensor_dtype == dtypes.string: |
| 588 | # np.pad throws on these arrays of type np.object. |
| 589 | values = list(tensor.string_val) |
| 590 | padding = num_elements - len(values) |
| 591 | if padding > 0: |
| 592 | last = values[-1] if values else "" |
| 593 | values.extend([last] * padding) |
| 594 | return np.array(values, dtype=dtype).reshape(shape) |
| 595 | |
| 596 | if tensor_dtype == dtypes.float16 or tensor_dtype == dtypes.bfloat16: |
| 597 | # the half_val field of the TensorProto stores the binary representation |
| 598 | # of the fp16: we need to reinterpret this as a proper float16 |
| 599 | values = np.fromiter(tensor.half_val, dtype=np.uint16) |
| 600 | values.dtype = tensor_dtype.as_numpy_dtype |
| 601 | elif tensor_dtype == dtypes.float32: |
| 602 | values = np.fromiter(tensor.float_val, dtype=dtype) |
| 603 | elif tensor_dtype == dtypes.float64: |
| 604 | values = np.fromiter(tensor.double_val, dtype=dtype) |
| 605 | elif tensor_dtype in [ |
| 606 | dtypes.int32, dtypes.uint8, dtypes.uint16, dtypes.int16, dtypes.int8, |
| 607 | dtypes.qint32, dtypes.quint8, dtypes.qint8, dtypes.qint16, dtypes.quint16 |
| 608 | ]: |
| 609 | values = np.fromiter(tensor.int_val, dtype=dtype) |
| 610 | elif tensor_dtype == dtypes.int64: |
| 611 | values = np.fromiter(tensor.int64_val, dtype=dtype) |
| 612 | elif tensor_dtype == dtypes.complex64: |
| 613 | it = iter(tensor.scomplex_val) |
| 614 | values = np.array([complex(x[0], x[1]) for x in zip(it, it)], dtype=dtype) |
| 615 | elif tensor_dtype == dtypes.complex128: |
| 616 | it = iter(tensor.dcomplex_val) |
| 617 | values = np.array([complex(x[0], x[1]) for x in zip(it, it)], dtype=dtype) |
| 618 | elif tensor_dtype == dtypes.bool: |
| 619 | values = np.fromiter(tensor.bool_val, dtype=dtype) |
| 620 | else: |
no test coverage detected