02_理解Tensor
1. Tensor的本质
Tensor
的本质其实是一套计算的流程。
在TensorFlow2.0
中之所以定义好这个流程之后结果就出来了,是因为Eager Execution
这种模式。在Eager Execution
之前,Tensor
都是只定义,所以在tf1.x
中都是先定义出计算图,在需要计算的时候再通过session
来执行计算。在Eager Execution
之后,Tensor
定义好后,结果也计算好了。
a = tf.constant([[1,2],[3,4]])
b = a*a
print(a,b,type(a),type(b))
'''
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[ 1 4]
[ 9 16]], shape=(2, 2), dtype=int32)
<class 'tensorflow.python.framework.ops.EagerTensor'>
<class 'tensorflow.python.framework.ops.EagerTensor'>
'''
看上面这段代码,a
和b
都是Tensor
,并且在执行完b=a*a
后,计算结果就已经产生了。
2. Tensor VS Numpy ndarray
Numpy ndarray
可以作为整个计算流程的输入,也可以作为整个计算流程的输出,但是注意,它只能作为输入和输出,进入tf
之后都要用Tensor
,除非一些之后不在计算流程中使用的Tensor
可以通过tf.Tensor.numpy()
方法可以将Tensor
以ndarray
导出。
ndarry to tensor:
c = np.array([[1,2],[3,4]])
d = tf.constant(c)
print(c)
print(d)
print(type(c))
print(type(d))
'''
[[1 2]
[3 4]]
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int64)
<class 'numpy.ndarray'>
<class 'tensorflow.python.framework.ops.EagerTensor'>
'''
tensor to ndarray:
e = d.numpy()
print(e)
print(type(e))
print("\n")
'''
[[1 2]
[3 4]]
<class 'numpy.ndarray'>
'''
3. tf.Tensor VS tf.Variable
tf.Variable
是在Tensor
基础上的进一步封装,Variable
可以当成Tensor
处理,但是Tensor
不一定能当作Variable
。
f = tf.Variable([[1,2],[3,4]])
print(f)
print(type(f))
print("\n")
'''
<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy=
array([[1, 2],
[3, 4]], dtype=int32)>
<class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
'''
修改Tensor
的值
g = tf.constant(100)
print(g)
g.assign(20)
print(g)
报错:
tf.Tensor(100, shape=(), dtype=int32)
Traceback (most recent call last):
File "/home/peco/Desktop/Learn_TensorFlow2.0/01_tf_keras/tensor_and_basic_op/tensor.py", line 84, in <module>
g.assign(20)
AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'
可以看出,tf.Tensor
不可更改。
h = tf.Variable(100)
print(h)
h.assign(50)
print(h)
'''
tf.Tensor(100, shape=(), dtype=int32)
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=100>
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=50>
'''
可以看出,tf.Variable
可以更改。
4.总结:Numpy ndarray VS tf.Tensor VS tf.Variable
- 从前往后,逐层封装,增加功能,
ndarray
不可以放在GPU或者TPU上,后两者则可以。 tf.Tensor
不可更改,tf.Variable
可以更改。tf.Variable
是面向用户,tf.Tensor
面向Tensorflow
内部。
5.附录
本部分完整代码:01_tensor.py