-
更新时间:2017.2.27
tensorflow 1.0出来了,API和以前有了一些不一样,所以这里把把之前的代码迁移到新的上面去。 -
更新时间:2017.5.4
对于一些性质有了新的认识。补充一些新的东西 -
更新时间:2019.3.7
tensorflow 2.0出来了,把基本的代码风格向tensorflow 2.0转移。移除了placeholder
和图的一些内容,精简了内容
这一部分内容的所有完整代码以及notebook,都可以在我的Github:LearningTensorFlow/2.constant_and_Variable/ 找到。
一.概览
还记的上节TensorFlow学习(一):感受一下 的hello word的例子吗?是不是出现了一些新的编程思路和一个函数类等等。我们学任何一门编程语言的时候,都会讲一些量的操作,因为这是基本。这节的主要任务就是熟悉最基本的一些量怎么来定义。
先列出来,然后一个一个细讲。
类:
- 1.Tensor
- 2.Variable
函数
- 1.constant()
- 2.初始化变量的一些函数
二.基本类讲解
Ⅰ.tf.Tensor
官方文档:tf.Tensor
Tensor类应该是最基本最核心的数据结构了,他表示的是一个操作的输出,简单来说,你可以把这个当做一个结果或者是一个数据什么的。下面举一个简单例子直观感受一下。
import tensorflow as tf
#basic
a=tf.constant([[1,2],[3,4]])
b=tf.constant([[1,1],[0,1]])
print("a:",a)
print("b:",b)
print("type of a:",type(a))
c=tf.matmul(a,b)
print("c:",c)
print("c.numpy:\n",c.numpy())
print("type of c.numpy():",type(c.numpy()))
print("\n")
#attribute
print("device:",c.device)
print("dtype:",c.dtype)
print("shape:",type(c.shape))
结果:
a:
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int32)
b:
tf.Tensor(
[[1 1]
[0 1]], shape=(2, 2), dtype=int32)
type of a:
<class 'tensorflow.python.framework.ops.EagerTensor'>
c:
tf.Tensor(
[[1 3]
[3 7]], shape=(2, 2), dtype=int32)
c.numpy:
[[1 3]
[3 7]]
type of c.numpy():
<class 'numpy.ndarray'>
device: /job:localhost/replica:0/task:0/device:CPU:0
dtype: <dtype: 'int32'>
shape: <class 'tensorflow.python.framework.tensor_shape.TensorShape'>
分析:
一开始就用
constant()
函数弄了两个tensor分别是a
和b
(下面有对于constant函数的介绍),然后我们直接输出a
和b
,然后我们把a
和b
这两个tensor传递给tf.matmul()
函数,这个函数是用来计算矩阵乘法的函数。返回的依然是tensor用c
来接受。到这里为止,可以发现tensor里面并不负责仅仅储存值,想要得到最终的结果,还需要使用numpy()
转成最后的结果。
刚刚这里例子主要是形象的表示tensor到底是干嘛的,比抽象的去看要好。接下来就讲一下Tensor类的一些属性和函数成员。
常见属性:
- device:表示tensor将被产生的设备名称
- dtype:tensor元素类型
- shape:tensor的形状(返回的是
tf.TensorShape
这个表示tensor形状的类) - value_index:表示这个tensor在其操作结果中的索引,注意,在eager execution模式下面,这个属性没哟意义。