在tensorflow的开发中,常常需要将tensor与numpy互相配合,而是实现特定的功能。而tensor与numpy的互相转换,必不可少。
请注意,tf2因为使用eager机制,转换时不需要new session。出现如下错误,多半是没有搞清楚所在环境。‘Tensor’ object has no attribute ‘numpy’
TF1.x
tensor -> numpy
1 2 | with tf.Session() as sess: numpy_data = tensor_data.eval() |
numpy->tensor
1 | tensor_data= tf.convert_to_tensor(numpy_data) |
TF2.x
tensor -> numpy
1 | numpy_data = tensor_data.numpy() |
numpy -> tensor
1 | tensor_data = tf.cast(numpy_data, dtype=tf.float32)#numpy转张量 |