TensorFlow的核心是张量(Tensor)和计算图(Gragh)
Tensor指的就是一种多维的数据结构和numoy的数据结构很像。
张量 分 常量张量(tf.constant()创建)和变量张量(tf.Variable(),tf.get_Variable()创建)。
常量在计算中不能被赋值,变量在计算中可以使用tf.assgn()、tf.assign_add()操作进行赋值,加法等计算
1、张量常量介绍
我们可以近似认为constant内有几个框框,就是几维的常量
tf.rank()的结果和我们的认知似乎不太一样
import tensorflow as tf
import numpy as np
# 查看常量的维度大小
a = tf.constant([1.0, 2.0])
b = tf.constant([[1,2], [2,3]])
c = tf.constant([[[1,2], [2,3]]])
print("a的维度为:{},b的维度为:{},c的维度为:{}".format(tf.rank(a), tf.rank(b), tf.rank(c)))
print(a.shape)
print(b.shape)
print(c.shape)
a的维度为:Tensor("Rank:0", shape=(), dtype=int32),b的维度为:Tensor("Rank_1:0", shape=(), dtype=int32),c的维度为:Tensor("Rank_2:0", shape=(), dtype=int32)
(2,)
(2, 2)
(1, 2, 2)
由于tensor和np的array的数组结构相同,我们来介绍一下这两种数据结构的互相转化过程
tensor转array() :
sess.run()该节点或者sess.eval()
array()转tensor:
tf.convert_to_tensor()函数
tf.cast()函数
sess = tf.Session()
a = tf.constant([1., 2., 3.])
b = tf.convert_to_tensor(a)
print("tensor:", b)
print("array:", sess.run(b))
print("tensor:", tf.cast(a, dtype=tf.float32))
Tensor("Const:0", shape=(3,), dtype=float32)
[1. 2. 3.]
Tensor("Const:0", shape=(3,), dtype=float32)
tf.cast()可以修改张量的数据类型,shape属性可以查看张量的尺寸
a = tf.constant([1., 2., 3.])
print(a.shape)
print(a.dtype)
print(tf.cast(a, dtype=tf.int32).dtype)
(3,)
<dtype: 'float32'>
<dtype: 'int32'>
2、变量张量介绍
变量张量一般通过两个函数来创建:
(1)、tf.Variable()
1)参数说明:
tf.Variable是一个Variable类。通过变量维持图graph的状态,以便在sess.run()中执行;可以用Variable类创建一个实例在图中增加变量
2)定义变量的常用两种方式:
1、使用固定的值初始化变量:w = tf.Variable(initial-value,name=optional-name)
2、用tf的初始化器初始化变量:
w = tf.Variable(tf.truncated_normal([3,4],mean=0,stddev=.5),name=‘weight’)
3)执行初始化的三种方式:
1、在回话中运行initializer 操作:
tf.global_variable_initializer().run()
2、从文件中恢复,如restore from checkpoint
saver = tf.train.Saver()
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state(checkpoint_path)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess,ckpt.model_checkpoint_path)
else:
print('No checkpoint file found')
3、也可自己通过tf.assign()给变量附初值
a = tf.Variable(1.0)
a = tf.assign(a,5.0)
b = tf.Variable(2.0)
b = tf.assign(b,6.0)
c = a+b
with tf.Session() as sess:
#相当于调用tf.assign()给变量赋初值
sess.run([a,b])
print(c.eval())
(2)、tf.get_variable()
参数和tf.Variable()不一致,其他的用法一致
get_variable(
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
custom_getter=None,
constraint=None
)