创建Tensor
使用numpy创建tensor
tf.convert_to_tensor()
可接受array或list
tf.convert_to_tensor(np.ones([2,3]))
# <tf.Tensor: id=42, shape=(2, 3), dtype=float64, numpy=array([[1., 1., 1.], [1., 1., 1.]])>
tf.convert_to_tensor([1,2.]) #类型不统一时转换为float
# <tf.Tensor: id=46, shape=(2,), dtype=float32, numpy=array([1,2], dtype=int32)>
tf.zeros()
tf.zeros([2,3])
# []内为shape而不是data,指2行3列
tf.zeros_like()
根据传入tensor的shape创建tensor
a = tf.zeros([2,3,3])
tf.zeros_like(a)
tf.zeros(a.shape) #两者相同
tf.ones()
a = tf.ones([1])
tf.ones_like(a)
Fill
根据输入参数填充
tf.fill([2,2],3)
随机初始化
正态分布
tf.random.normal([2,2], mean=1, stddev=1) #均值,标准差
tf.random.truncated_normal([2,2],mean=0,stddev=1) #切割后
均匀分布
tf.random.uniform([2,2],minval=0,maxval=1)
# 0——1均匀分布
应用-随机打散
idx = tf.range(10)
idy = tf.random.shuffle(idx)
print(idx) # tf.Tensor([0 1 2 3 4 5 6 7 8 9], shape=(10,), dtype=int32)
print(idy) # tf.Tensor([2 4 1 9 0 8 5 7 6 3], shape=(10,), dtype=int32)
a=tf.gather(a.idx)
b=tf.gather(b,idx) #一一对应随机打散