Tensorflow2.0学习笔记-创建张量

创建张量

使用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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值