TensorFlow学习框架(一)

本文深入探讨了Python中eval函数的用法,演示了如何通过eval执行字符串表达式并返回结果。同时,详细介绍了TensorFlow中run函数的应用,特别是在Session上下文中执行计算图的方式,对比了run函数和eval方法在执行效率上的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于eval 函数和run函数

  1. eval函数:返回传入字符串的表达式的结果。
# coding:utf-8

import tensorflow as tf

x = 1
y = 2
print(eval('x+y'))

输出结果:

3
  1. run函数:常用于 Session.run() 执行图
# coding:utf-8

import tensorflow as tf

matrix1 = tf.Variable([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])

preduct = tf.matmul(matrix1, matrix2)

sess_ = tf.InteractiveSession()  # 默认会话
tf.global_variables_initializer().run()  # 初始化变量

print(preduct)
print(preduct.eval())
print(sess_.run(preduct))
sess_.close()

输出结果:

Tensor("MatMul:0", shape=(1, 1), dtype=float32)
[[12.]]
[[12.]]

结果分析:

1.执行 print(preduct)
参数 preduct 是一个Tensor(张量)所以打印结果为:
Tensor(“MatMul:0”, shape=(1, 1), dtype=float32)

2.执行 print(preduct.eval()) 和 print(sess_.run(preduct))
在上面的代码块中,对于单一的Tensor,执行两者效果相同
preduct.eval() 等价于 tf.get_default_session().run(preduct)
即 sess_.run(preduct)

对于多个Tensor,你可以使用sess.run()在同一步获取多个Tensor中的值,但是使用Tensor.eval()时只能在同一步当中获取一个tensor值,并且每次使用 eval 和 run时,都会执行整个计算图。

# coding:utf-8
import tensorflow as tf

t = tf.constant(42.0)
u = tf.constant(37.0)

tu = tf.multiply(t, u)
ut = tf.add(u, t)

with tf.Session() as sess:
    tu.eval()  # runs one step
    ut.eval()  # runs one step
    print(sess.run([tu, ut]))  # evaluates both tensors in a single step

输出结果

[1554.0, 79.0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值