博客
关于我
tensorflow入门变量常量
阅读量:353 次
发布时间: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/

你可能感兴趣的文章
Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>