python - tf.Session() 是否应该在 tf.Graph() 的上下文中?

标签 python python-3.x machine-learning tensorflow

我经常在 Tensorflow 代码中看到以下模式,但经常通过忽略它们来获得更好的性能。

with tf.Graph().as_default():

    # Build graph here ...
    loss, train_op = ...

    with tf.Session() as sess: # OR: with sv.managed_sess() as sess, etc.

        # Run training steps here ...
        sess.run(train_op)

但我更喜欢先定义我的图形,然后按如下方式单独运行 session (尤其是在 Jupyter 笔记本中)。

在一个单元格中:

with tf.Graph().as_default():

    # Build graph here ...
    loss, train_op = ...

在另一个单元格中:

with tf.Session() as sess: # OR: with sv.managed_sess() as sess, etc.

    # Run training steps here ...
    sess.run(train_op)

我注意到在第一种方法中创建图形需要时间。有时我会使用多个图表,而第二种方法是我唯一的选择。为什么一种方法会比另一种更好?

最佳答案

这两种方法在常规 python 脚本中没有区别。但是,如果您使用笔记本并分别执行单元格,那么显然不重新创建图表比从头开始制作要快。

关于python - tf.Session() 是否应该在 tf.Graph() 的上下文中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45403253/

相关文章:

python pandas dataframe 将列重命名为多索引列

machine-learning - 如何解释SoftMax回归中的 "soft"和 "max"?

python - SageMaker 线性学习器结果不准确?

python - PyCharm:列出一个类的所有方法的所有用法

python - 我想使用 python 中的 BeautifulSoup 库对谷歌新闻进行一些网络抓取

machine-learning - 哪些分类器提供权重向量?

python - Pandas 在 Excel 中的位置

python - 如何从 python 中的命名元组中获取名称?

python - Scipy basinhopping 不尊重 stepsize?

python - boolean 值不在Python中