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'>
'''

看上面这段代码,ab都是Tensor,并且在执行完b=a*a后,计算结果就已经产生了。

2. Tensor VS Numpy ndarray

Numpy ndarray可以作为整个计算流程的输入,也可以作为整个计算流程的输出,但是注意,它只能作为输入和输出,进入tf之后都要用Tensor,除非一些之后不在计算流程中使用的Tensor可以通过tf.Tensor.numpy()方法可以将Tensorndarray导出。

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值