在tensorflow[1.x/2.x]下,实现tensor与numpy互转

在tensorflow的开发中,常常需要将tensor与numpy互相配合,而是实现特定的功能。而tensor与numpy的互相转换,必不可少。

请注意,tf2因为使用eager机制,转换时不需要new session。出现如下错误,多半是没有搞清楚所在环境。‘Tensor’ object has no attribute ‘numpy’

TF1.x

tensor -> numpy

    with tf.Session() as sess:
        numpy_data = tensor_data.eval()

numpy->tensor

tensor_data= tf.convert_to_tensor(numpy_data)

TF2.x

tensor -> numpy

numpy_data = tensor_data.numpy()

numpy -> tensor

tensor_data = tf.cast(numpy_data, dtype=tf.float32)#numpy转张量

你可能感兴趣的:(机器学习,tensorflow,深度学习,人工智能,python,numpy)