博客
关于我
tensorflow入门变量常量
阅读量:358 次
发布时间:2019-03-04

本文共 1308 字,大约阅读时间需要 4 分钟。

TensorFlow入门

TensorFlow 是一个开源的深度学习框架,最初由 Google 开发,现由社区维护。它以灵活的计算图和易于使用的API著称,适用于机器学习和深度学习任务。

常量与变量

TensorFlow 中,常量和变量的定义有明确区别。常量使用 tf.constant() 定义,值在定义时就确定下来。变量则使用 tf.Variable() 定义,其值可以通过训练改变。

示例代码

import tensorflow as tf# 定义常量data1 = tf.constant(2, dtype=tf.int32)# 定义变量data2 = tf.Variable(10, name='var')print(data1)print(data2)

输出结果

tf.Tensor(2, shape=(), dtype=int32)tf.Variable 'var:0' shape=() dtype=int32, numpy=10

注意事项

所有使用变量的操作都需要在 Session 中初始化。正确的做法是:

import tensorflow as tf# 定义变量data2 = tf.Variable(10, name='var')# 初始化变量sess = tf.Session()init = tf.global_variables_initializer()sess.run(init)# 使用变量print(sess.run(data2))

版本问题及解决方案

如果你使用的是 TensorFlow 2.1.0,可能会遇到 Session 未定义的错误。解决方法是切换到 TensorFlow 1.14.0:

conda install -n tensorflow tensorflow==1.14.0

变量初始化

确保在使用变量之前对其进行初始化,否则会抛出 FailedPreconditionError

import tensorflow as tf# 定义变量data2 = tf.Variable(10, name='var')# 初始化变量sess = tf.Session()init = tf.global_variables_initializer()sess.run(init)print(sess.run(data2))

TensorFlow运算原理

TensorFlow 的本质是张量 Tensor 加上计算图 Graph。张量是数据,图则是操作。通过 Session 执行计算图,实现数据操作。

关闭Session

记得在使用完 Session 后关闭它:

with sess:    # 初始化变量    init = tf.global_variables_initializer()    sess.run(init)    # 打印变量值    print(sess.run(data2))

TensorFlow核心原理

TensorFlow 的核心是张量和计算图。张量表示数据,图表示操作。通过定义计算图,TensorFlow 可以自动执行任务。

转载地址:http://dyfr.baihongyu.com/

你可能感兴趣的文章
os.environ 没有设置环境变量
查看>>
os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
查看>>
os.removexattr 的 Python 文档——‘*‘(星号)参数是什么意思?
查看>>
os.system 在 Python 中不起作用
查看>>
OS2ATC2017:阿里研究员林昊畅谈操作系统创新与挑战
查看>>
OSCACHE介绍
查看>>
SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
查看>>
OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
查看>>
SQL--mysql索引
查看>>
OSChina 周四乱弹 ——程序员为啥要买苹果手机啊?
查看>>
OSChina 周日乱弹 —— 2014 年各种奇葩评论集合
查看>>
OSChina 技术周刊第十期,每周技术抢先看!
查看>>
OSError: no library called “cairo-2“ was foundno library called “cairo“ was foundno library called
查看>>
OSError: [WinError 193] %1 不是有效的 Win32 应用程序。
查看>>
osgearth介绍
查看>>
OSGi与Maven、Eclipse PlugIn的区别
查看>>
Osgi环境配置
查看>>
OSG——选取和拖拽
查看>>
OSG中找到特定节点的方法(转)
查看>>
OSG学习:C#调用非托管C++方法——C++/CLI
查看>>