常量(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)>