TensorFlow基础(一)
来源:互联网 发布:志鸿优化答案查询 编辑:程序博客网 时间:2024/06/06 20:24
1. 定义两个不同的图
Tensorflow会自动将定义的计算转换为计算图上的节点
import tensorflow as tfg1 = tf.Graph()with g1.as_default(): v = tf.get_variable("v", [1], initializer = tf.zeros_initializer()) # 设置初始值为0g2 = tf.Graph()with g2.as_default(): v = tf.get_variable("v", [1], initializer = tf.ones_initializer()) # 设置初始值为1# 在计算图1中读取变量‘v’的取值 with tf.Session(graph = g1) as sess: tf.global_variables_initializer().run() with tf.variable_scope("", reuse=True):#在计算图g1中,变量‘v’的初始0(tf.zeros_initializer(shape[1]),所以这行输出[0.] print(sess.run(tf.get_variable("v")))#在计算图1中读取变量‘v’的取值 with tf.Session(graph = g2) as sess: tf.global_variables_initializer().run() with tf.variable_scope("", reuse=True): print(sess.run(tf.get_variable("v")))
2. 张量的概念及生成会话
在Tensorflow程序中,所有数据通过张量的形式来表示。张量可以理解为多维数组。零阶张量表示标量(Scalar)为一个数。第n阶张量理解为一个n维数组。Tensorflow保存的是计算过程不是计算值
import tensorflow as tfa = tf.constant([1.0, 2.0], name="a")b = tf.constant([2.0, 3.0], name="b")result=a+bsess = tf.InteractiveSession ()print(result.eval())sess.close()
- 创建一个会话,并通过Python中的上下文管理器管理这个会话
- 当上下文退出时会话关闭和资源释放自动完成
- Python上下文管理机制:将计算放在“with”,解决了异常退出资源释放问题
with tf.Session() as sess: print(sess.run(result))
- 使用tf.Session().as_default()或者tf.InteractiveSession构建会话,tf.InteractiveSession自动将生成的会话注册为默认会话,省去了注册的过程
- 在交互环境下,通过设置默认会话的方式获取张量的取值更加方便
sess = tf.Session()with sess.as_default(): print(result.eval())
sess = tf.InteractiveSession ()print(result.eval())sess.close()
- 下面的两个命令有相同的功能,输出会话内的结果
sess = tf.Session()print(sess.run(result))print(result.eval(session=sess))
- 通过ConfigProto Protocol Buffer配置需要生成的会话
- ConfigProto 可以配置并行的线程数、GPU分配策略、运算时间等参数。
- allow_soft_placement=True 任意条件成立GPU上运算可以放到CPU上运算,该布尔型变量设置为True可以让程序在拥有不同数量的GPU机器上运行
- 运算无法在GPU上运行;没有GPU资源(运算被指定在地问个GPU上但是机器就只有一个GPU);运算输入包含对CPU计算结果引用
- log_device_placement=True 记录了每个节点安排在哪个设备上方便调试(设备日志)。参数为False减少了日志量。
config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)sess1 = tf.InteractiveSession(config=config)sess2 = tf.Session(config=config)
0 0
- TensorFlow基础(一)
- TensorFlow基础(一)
- TensorFlow基础(一)--入门
- 一文读懂TensorFlow基础
- Tensorflow(一)- 初识tensorflow
- TensorFlow基础知识点(一)切换CPU或GPU
- 《TensorfFlow实战》读书笔记(一) —— Tensorflow 基础
- tensorflow API简单整理(一、常量与变量基础)
- 零基础学TensorFlow(一):virtualenv及TensorFlow环境搭建
- TensorFlow基础(二)
- Tensorflow 基础(二)
- tensorflow安装(一)
- (一)Tensorflow安装
- TensorFlow笔记(一)
- TensorFlow学习(一)
- TensorFlow读书笔记(一)
- TensorFlow入门(一)
- 【tensorflow学习】(一)
- Android 对话框弹出(支持Android 6.0及其以上)
- 上传iOS应用时 ERROR ITMS-90096: Your binary is not optimized for iPhone 5。。。
- JavaScript之异步
- MySql--基本查询
- VC/C#调用lazarus写的dll
- TensorFlow基础(一)
- 常见排序算法
- 算法
- 5.12
- Embedded Wizard 研究笔记 1
- [Binder机制]众多Service启动流程-java层Service(一)
- Unix哲学
- HDU-2191 完全背包
- Android 内容提供者