【问题标题】:Does tensorflow cache data?张量流是否缓存数据?
【发布时间】:2018-03-21 11:36:10
【问题描述】:

在以下代码中:

import tensorflow as tf
import numpy as np

with tf.Session():
    input_features = tf.constant(np.reshape([2, 1, 1, 2], (1, 4)).astype(np.float32))
    print(input_features)
    weights = tf.constant(np.random.randn(4, 2).astype(np.float32))
    output = tf.matmul(input_features, weights)
    print("Input:")
    print(input_features.eval())
    print("Weights:")
    print(weights.eval())
    print("Output:")
    print(output.eval())

当它调用print(weights.eval()) 时,将计算权重。当它调用output.eval()时,会重新计算权重,还是使用之前调用的缓存值?

【问题讨论】:

    标签: python tensorflow constants


    【解决方案1】:

    weights 是一个常数张量,它在运行这一行时得到一个值:

    weights = tf.constant(np.random.randn(4, 2).astype(np.float32))
    

    ... 这个值实际上存储在图表中并且永远不会改变,就像input_features。您可以评估 weights 或任何相关操作并始终获得相同的结果。当然,Tensorflow 将所有常量和变量的值存储在一个会话中,如果你愿意,你可以称之为缓存。

    这里唯一的随机点是值本身:np.random.randn(4, 2)。每次运行脚本时,该数组都会有所不同(但在脚本中是相同的,如上所述)。

    【讨论】:

    • 非常感谢,这很有帮助!
    • 嗨@user9524761,如果这个或任何答案已经解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 2016-11-20
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多