tensorflow 2.0 基础知识点2(创建常见张量)

<1>创建张量

张量由Tensor类实现,每一个张量都是一个Tensor对象

tf.constant(value,dtype,shape) 创建张量

value:数字、python列表、numpy数组

dtype:元素的数据类型

shape:张量的形状


<2>全0张量、全1张量及相同元素张量

tf.zeros(shape,dtype)  创建全0 张量

tf.zeros(shape=(2,1),dtype = tf.float32)

<tf.Tensor: shape=(2, 1), dtype=float32, numpy= array([[0.], [0.]], dtype=float32)>

tf.ones(shape,dtype)  创建全1 张量

tf.zeros(shape=(2,2),dtype = tf.int32)

<tf.Tensor: shape=(2, 2), dtype=int32, numpy= array([[1, 1], [1, 1]])>

tf.fill(dims,value) 创建元素值相同的张量

tf.fill()函数没有dtype参数,根据value自行判断数据类型

tf.fill([2,3],9)

<tf.Tensor: shape=(2, 3), dtype=int32, numpy= array([[9, 9, 9], [9, 9, 9]])>

除此之外,还可以使用tf.constant(9,shape=[2,3]) 创建元素值相同的张量


<3>创建随机数张量

tf.random.normal(shape,mean,stddev,dtype) 创建正态分布张量

mean:均值 stddev: 方差

tf.random.normal([2,2],0,1)

<tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[1.7779471 , 0.7681969 ], [0.7035667 , 0.07748909]], dtype=float32)>

注意:若未指明均值与方差默认是标准正态分布

tf.random.truncated_normal(shape,mean,stddev,stype) 创建截断正态分布

tf.random.truncated_normal([2,2],0,1)

<tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[-1.3776016, 0.9348862], [-1.0636672, 1.5856758]], dtype=float32)>

tf.random.uniform(shape,minval,maxval,dtype) 创建均匀分布张量

tf.random.uniform(shape=(2,2),minval = 1,maxval = 3 ,dtype = tf.float32)

<tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[2.1126585, 2.001746 ], [1.2562537, 2.7128727]], dtype=float32)>

tf.range(start,limit,delta,dtype) 创建序列

start起始数字,limit结束数字,前闭后开,delta步长,不指定默认为1,以下三种常见情况

tf.range(1,10,delta=1)

<tf.Tensor: shape=(9,), dtype=int32, numpy=array([1, 2, 3, 4, 5, 6, 7, 8, 9])>

tf.range(1,10,delta=2)

<tf.Tensor: shape=(5,), dtype=int32, numpy=array([1, 3, 5, 7, 9])>

tf.range(10,delta=1)

<tf.Tensor: shape=(10,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值