创建张量
使用constant创建张量
# 使用constant函数创建张量
# 其中[1,5]表示张量内容,dtype表示数据类型
a = tf.constant([1, 5], dtype=tf.int32)
# 输出a,a的数据类型,a的形状
print(a)
print(a.dtype)
print(a.shape)
# 输出结果
tf.Tensor([1 5], shape=(2,), dtype=int32)
<dtype: 'int32'>
(2,)
使用convert_to_tensor创建张量
# 使用convert_to_tensor函数将数据类型转换成张量
a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print(a)
print(b)
#输出结果
[0 1 2 3 4]
tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)
创建特殊张量
# 其中zeros表示创建全为0的张量,[3,4]表示张量的维数
# ones表示创建全为1的张量,3表示维度
# fill表示创建全为指定值的函数,[2,2]表示维度
a = tf.zeros([3, 4], dtype=tf.int32)
b = tf.ones(3, dtype=tf.int32)
c = tf.fill([2, 2], 9)
print(a)
print(b)
print(c)
tf.Tensor(
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]], shape=(3, 4), dtype=int32)
tf.Tensor([1 1 1], shape=(3,), dtype=int32)
tf.Tensor(
[[9 9]
[9 9]], shape=(2, 2), dtype=int32)
随机生成张量
#生成正态分布的随机变量,其中均值=0.5,标准差=1
a = tf.random.normal([2, 2], mean=0.5, stddev=1)
生成截断式正态分布的随机变量
b = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1)
# 生成均匀分布的随机数
c = tf.random.uniform([2, 2], minval=0.5, maxval=1)
# 输出结果
# 正态分布
tf.Tensor(
[[-0.40264213 1.7012755 ]
[ 0.2710414 1.6012648 ]], shape=(2, 2), dtype=float32)
#截断式分布
tf.Tensor(
[[0.4462757 1.2510767 ]
[0.8421626 0.28103304]], shape=(2, 2), dtype=float32)
# 均匀分布
tf.Tensor(
[[0.53592265 0.68155897]
[0.5985845 0.9714481 ]], shape=(2, 2), dtype=float32)