走近tensor常量

常量(constant)篇

import tensorflow as tf
最常规
x = tf.constant([1, 2, 3, 4, 5, 6])
x
<tf.Tensor: id=1, shape=(6,), dtype=int32, numpy=array([1, 2, 3, 4, 5, 6])>
加上形状属性
x = tf.constant([1, 2, 3, 4, 5, 6], shape=(2,3))
x
<tf.Tensor: id=4, shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]])>
只包含一个数,可以是任意常数哦
x = tf.constant(3.414, shape=(2,3))
x
<tf.Tensor: id=106, shape=(2, 3), dtype=float32, numpy=
array([[3.414, 3.414, 3.414],
       [3.414, 3.414, 3.414]], dtype=float32)>
进一步理解常量

这里的常量是和变量相对应的,要更改常量的值,有两种方式,一种是整体更改,一种是转换成变量之后单独更改。

  • 整体更改
x += 1
x
<tf.Tensor: id=108, shape=(2, 3), dtype=float32, numpy=
array([[4.414, 4.414, 4.414],
       [4.414, 4.414, 4.414]], dtype=float32)>
  • 更改第一个值
xv = tf.Variable(x)
xv[0,0].assign(0.24)
xv
<tf.Variable 'Variable:0' shape=(2, 3) dtype=float32, numpy=
array([[0.24 , 4.414, 4.414],
       [4.414, 4.414, 4.414]], dtype=float32)>
  • 与numpy的相互转化
xn = x.numpy()
xn
array([[4.414, 4.414, 4.414],
       [4.414, 4.414, 4.414]], dtype=float32)
tf.constant(xn)
<tf.Tensor: id=126, shape=(2, 3), dtype=float32, numpy=
array([[4.414, 4.414, 4.414],
       [4.414, 4.414, 4.414]], dtype=float32)>
  • 查看属性
x.device
'/job:localhost/replica:0/task:0/device:CPU:0'
x.dtype
tf.float32
x.ndim
2
x.shape
TensorShape([2, 3])
获取常量的其他方式
全一
tf.ones(shape=(2, 2))
<tf.Tensor: id=191, shape=(2, 2), dtype=float32, numpy=
array([[1., 1.],
       [1., 1.]], dtype=float32)>
全零
tf.zeros(shape=(2, 2))
<tf.Tensor: id=196, shape=(2, 2), dtype=float32, numpy=
array([[0., 0.],
       [0., 0.]], dtype=float32)>
全一个数(跟constant的最后一种用法差不多)
tf.fill([2,2],3.14)
<tf.Tensor: id=181, shape=(2, 2), dtype=float32, numpy=
array([[3.14, 3.14],
       [3.14, 3.14]], dtype=float32)>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羊城迷鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值