其他分享
首页 > 其他分享> > NumPy和Tensor之间得转换

NumPy和Tensor之间得转换

作者:互联网

Converting between a TensorFlow tf.Tensors and a NumPy ndarray is easy:

1.TensorFlow operations automatically convert NumPy ndarrays to Tensors.
2,NumPy operations automatically convert Tensors to NumPy ndarrays.

Tensors are explicitly converted to NumPy ndarrays using their .numpy() method. These conversions are typically cheap since the array and tf.Tensor share the underlying memory representation, if possible. However, sharing the underlying representation isn’t always possible since the tf.Tensor may be hosted in GPU memory while NumPy arrays are always backed by host memory, and the conversion involves a copy from GPU to host memory.

import numpy as np

ndarray = np.ones([3, 3])

print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)


print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))

print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())

标签:operations,转换,Tensor,numpy,print,NumPy,Tensors
来源: https://blog.csdn.net/weixin_43824178/article/details/99208554