创建tensor的几种常用方式

  • 使用tf.constant
     
    In [14]: tf.constant(1)
    Out[14]: <tf.Tensor: id=34, shape=(), dtype=int32, numpy=1>
    
    In [15]: tf.constant([1])
    Out[15]: <tf.Tensor: id=35, shape=(1,), dtype=int32, numpy=array([1])>

     

  • 从numpy、list转换
     
    In [4]: tf.convert_to_tensor(np.ones([3,2]))
    Out[4]:
    <tf.Tensor: id=1, shape=(3, 2), dtype=float64, numpy=
    array([[1., 1.],
           [1., 1.],
           [1., 1.]])>
    
    In [5]: tf.convert_to_tensor([1,2])
    Out[5]: <tf.Tensor: id=2, shape=(2,), dtype=int32, numpy=array([1, 2])>

     

  • 使用tf.zeros与tf.ones新建(或者zeros_like\ones_like)
     
    In [6]: tf.zeros([2,3])
    Out[6]:
    <tf.Tensor: id=5, shape=(2, 3), dtype=float32, numpy=
    array([[0., 0., 0.],
           [0., 0., 0.]], dtype=float32)>
    
    In [9]: tf.ones([2,3])
    Out[9]:
    <tf.Tensor: id=11, shape=(2, 3), dtype=float32, numpy=
    array([[1., 1., 1.],
           [1., 1., 1.]], dtype=float32)>

     

  • 使用tf.fill
     
    In [10]: tf.fill([2,2],5)
    Out[10]:
    <tf.Tensor: id=14, shape=(2, 2), dtype=int32, numpy=
    array([[5, 5],
           [5, 5]])>

     
  • 使用tf.random
     
    In [11]: tf.random.normal([2,2],mean=1,stddev=1)
    Out[11]:
    <tf.Tensor: id=20, shape=(2, 2), dtype=float32, numpy=
    array([[2.4201162, 3.4596694],
           [1.5751202, 1.7929654]], dtype=float32)>
    
    In [12]: tf.random.truncated_normal([2,2],mean=1,stddev=1)
    Out[12]:
    <tf.Tensor: id=26, shape=(2, 2), dtype=float32, numpy=
    array([[-0.4416641 ,  0.67318285],
           [ 1.886663  ,  2.2497933 ]], dtype=float32)>
    
    In [13]: tf.random.uniform([3,3],minval=0,maxval=1)
    Out[13]:
    <tf.Tensor: id=33, shape=(3, 3), dtype=float32, numpy=
    array([[9.2511845e-01, 2.5272369e-04, 3.9773893e-01],
           [3.6400330e-01, 8.9616191e-01, 1.0065639e-01],
           [1.7627370e-01, 1.8939865e-01, 7.1537638e-01]], dtype=float32)>

     

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值