1.tensor和ndarray相互转换
import numpy as np
import tensorflow as tf
ndarray = np.ones([3, 3])
# tf.multiply将ndarrray转换成tensor,将数组乘以后面的值
tensor = tf.multiply(ndarray, 42)
print(tensor)
# tf.convert_to_tensor将数组转换成tensor
num = 9
print(tf.convert_to_tensor(num))
# numpy操作会自动将tensor转换成numpy数组
print(np.add(tensor, 1))
# .numpy()方法将Tensor明确转换成numpy数组
print(tensor.numpy())
输出
tf.Tensor(
[[42. 42. 42.]
[42. 42. 42.]
[42. 42. 42.]]],shape=(3,3),dtype = float64)
tf.Tensor(9, shape=(), dtype=int32)
[[43. 43. 43.]
[43. 43. 43.]
[43. 43. 43.]]
[[42. 42. 42.]
[42. 42. 42.]
[42. 42. 42.]]