TensorFlow笔记-变量,图,会话

变量

存储一些临时值的作用或者长久存储。在Tensorflow中当训练模型时,用变量来存储和更新参数。变量包含张量(Tensor)存放于内存的缓存区。建模时它们需要被明确地初始化,模型训练后它们必须被存储到磁盘。值可在之后模型训练和分析是被加载。

Variable类

tf.global_variables_initializer().run()

要点

1、转换静态形状的时候,1-D到1-D,2-D到2-D,不能跨阶数改变形状

2、 对于已经固定或者设置静态形状的张量/变量,不能再次设置静态形状

3、tf.reshape()动态创建新张量时,元素个数不能不匹配

4、运行时候,动态获取张量的形状值,只能通过tf.shape(tensor)[]

变量作用域域

通过tf.variable_scope()创建指定名字的变量作用域可嵌套使用

with tf.variable_scope("itcast") as scope:
  print("----")

tf.Graph

TensorFlow计算,表示为数据流图。一个图包含一组表示 tf.Operation计算单位的对象和tf.Tensor表示操作之间流动的数据单元的对象。默认Graph值始终注册,并可通过调用访问 tf.get_default_graph。

g1= tf.Graph()
g2= tf.Graph()
​
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(g1,g2,tf.get_default_graph())

as_default()

返回一个上下文管理器,使其成为Graph默认图形。

g = tf.Graph()
with g.as_default():
  a = tf.constant(1.0)
  assert c.graph is g

会话

tf.Session

运行TensorFlow操作图的类,一个包含ops执行和tensor被评估

a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
​
sess = tf.Session()
​
print(sess.run(c))

在开启会话的时候指定图(with 后会自动施放资源)

with tf.Session(graph=g) as sess:

run(fetches, feed_dict=None, options=None, run_metadata=None)

运行ops和计算tensor

  • fetches 可以是单个图形元素,或任意嵌套列表,元组,namedtuple,dict或OrderedDict

  • feed_dict 允许调用者覆盖图中指定张量的值

如果a,b是其它的类型,比如tensor,同样可以覆盖原先的值


a = tf.placeholder(tf.float32, shape=[])
b = tf.placeholder(tf.float32, shape=[])
c = tf.constant([1,2,3])
​
with tf.Session() as sess:
    a,b,c = sess.run([a,b,c],feed_dict={a: 1, b: 2,c:[4,5,6]})
    print(a,b,c)
  • RuntimeError:如果它Session处于无效状态(例如已关闭)。

  • TypeError:如果fetches或feed_dict键是不合适的类型。

  • ValueError:如果fetches或feed_dict键无效或引用 Tensor不存在。

变量实现加法:

import tensorflow as tf
import os
# 防止警告
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.add(input1,input2)
with tf.Session() as sess:
    print(sess.run([output],feed_dict={input1:10.0,input2:20.0}))
原文地址:https://www.cnblogs.com/TimVerion/p/11224129.html