分析tensorflow代码(Hello world)

Hello, Tensor World!

让我们来分析一下你刚才跑的 Hello World 的代码。代码如下:

import tensorflow as tf

# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')

with tf.Session() as sess:
    # Run the tf.constant operation in the session
    output = sess.run(hello_constant)
    print(output)

Tensor

在 TensorFlow 中,数据不是以整数,浮点数或者字符串形式存在的。这些值被封装在一个叫做 tensor 的对象中。在 hello_constant = tf.constant('Hello World!') 代码中,hello_constant是一个 0 维度的字符串 tensor,tensors 还有很多不同大小:

# A is a 0-dimensional int32 tensor
A = tf.constant(1234) 
# B is a 1-dimensional int32 tensor
B = tf.constant([123,456,789]) 
 # C is a 2-dimensional int32 tensor
C = tf.constant([ [123,456,789], [222,333,444] ])

tf.constant() 是你在这课中多个 TensorFlow 运算之一。tf.constant() 返回的 tensor 是一个常量 tensor,因为这个 tensor 的值不会变。

Session

TensorFlow 的 api 构建在 computational graph 的概念上,它是一种对数学运算过程进行可视化的一种方法。让我们把你刚才运行的 TensorFlow 的代码变成一个图:

如上图所示,一个 "TensorFlow Session" 是用来运行图的环境。这个 session 负责分配 GPU(s) 和/或 CPU(s) 包括远程计算机的运算。让我们看看怎么使用它:

with tf.Session() as sess:
    output = sess.run(hello_constant)

这段代码已经从上一行创建了一个 tensor hello_constant。下一行是在session里对 tensor 求值。

这段代码用 tf.Session 创建了一个sess的 session 实例。 sess.run() 函数对 tensor 求值,并返回结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值