首页 技术 正文
技术 2022年11月9日
0 收藏 877 点赞 3,437 浏览 1688 个字

变量

存储一些临时值的作用或者长久存储。在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'] = ''
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}))
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898