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