zoukankan      html  css  js  c++  java
  • Tensorflow 学习二 tf.Session().run

    以下为tf.Session().run 说明,其接受的fetches参数可以有多种类型。

      def run(self, fetches, feed_dict=None, options=None, run_metadata=None):
        """Runs operations and evaluates tensors in `fetches`.
    
        This method runs one "step" of TensorFlow computation, by
        running the necessary graph fragment to execute every `Operation`
        and evaluate every `Tensor` in `fetches`, substituting the values in
        `feed_dict` for the corresponding input values.
    
        The `fetches` argument may be a single graph element, or an arbitrarily
        nested list, tuple, namedtuple, dict, or OrderedDict containing graph
        elements at its leaves.  A graph element can be one of the following types:
    
        * An [`Operation`](../../api_docs/python/framework.md#Operation).
          The corresponding fetched value will be `None`.
        * A [`Tensor`](../../api_docs/python/framework.md#Tensor).
          The corresponding fetched value will be a numpy ndarray containing the
          value of that tensor.
        * A [`SparseTensor`](../../api_docs/python/sparse_ops.md#SparseTensor).
          The corresponding fetched value will be a
          [`SparseTensorValue`](../../api_docs/python/sparse_ops.md#SparseTensorValue)
          containing the value of that sparse tensor.
        * A `get_tensor_handle` op.  The corresponding fetched value will be a
          numpy ndarray containing the handle of that tensor.
        * A `string` which is the name of a tensor or operation in the graph.
    
        The value returned by `run()` has the same shape as the `fetches` argument,
        where the leaves are replaced by the corresponding values returned by
        TensorFlow.
    
        Example:
    
        ```python
           a = tf.constant([10, 20])
           b = tf.constant([1.0, 2.0])
           # 'fetches' can be a singleton
           v = session.run(a)
           # v is the numpy array [10, 20]
           # 'fetches' can be a list.
           v = session.run([a, b])
           # v a Python list with 2 numpy arrays: the numpy array [10, 20] and the
           # 1-D array [1.0, 2.0]
           # 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:
           MyData = collections.namedtuple('MyData', ['a', 'b'])
           v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
           # v is a dict with
           # v['k1'] is a MyData namedtuple with 'a' the numpy array [10, 20] and
           # 'b' the numpy array [1.0, 2.0]
           # v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
           # [10, 20].
        ```
    
        The optional `feed_dict` argument allows the caller to override
        the value of tensors in the graph. Each key in `feed_dict` can be
        one of the following types:
    
        * If the key is a [`Tensor`](../../api_docs/python/framework.md#Tensor), the
          value may be a Python scalar, string, list, or numpy ndarray
          that can be converted to the same `dtype` as that
          tensor. Additionally, if the key is a
          [placeholder](../../api_docs/python/io_ops.md#placeholder), the shape of
          the value will be checked for compatibility with the placeholder.
        * If the key is a
          [`SparseTensor`](../../api_docs/python/sparse_ops.md#SparseTensor),
          the value should be a
          [`SparseTensorValue`](../../api_docs/python/sparse_ops.md#SparseTensorValue).
        * If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value
          should be a nested tuple with the same structure that maps to their
          corresponding values as above.
    
        Each value in `feed_dict` must be convertible to a numpy array of the dtype
        of the corresponding key.
    
        The optional `options` argument expects a [`RunOptions`] proto. The options
        allow controlling the behavior of this particular step (e.g. turning tracing
        on).
    
        The optional `run_metadata` argument expects a [`RunMetadata`] proto. When
        appropriate, the non-Tensor output of this step will be collected there. For
        example, when users turn on tracing in `options`, the profiled info will be
        collected into this argument and passed back.
    
        Args:
          fetches: A single graph element, a list of graph elements,
            or a dictionary whose values are graph elements or lists of graph
            elements (described above).
          feed_dict: A dictionary that maps graph elements to values
            (described above).
          options: A [`RunOptions`] protocol buffer
          run_metadata: A [`RunMetadata`] protocol buffer
    
        Returns:
          Either a single value if `fetches` is a single graph element, or
          a list of values if `fetches` is a list, or a dictionary with the
          same keys as `fetches` if that is a dictionary (described above).
    
        Raises:
          RuntimeError: If this `Session` is in an invalid state (e.g. has been
            closed).
          TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type.
          ValueError: If `fetches` or `feed_dict` keys are invalid or refer to a
            `Tensor` that doesn't exist.
        """

    下例中可以看到,当以列表作为参数,运算中有赋值时,大多数时候返回的是旧值,偶尔返回新值。

    import tensorflow as tf
    
    state = tf.Variable(0.0,dtype=tf.float32)
    new_val = tf.add(state, 1.0)
    update = tf.assign(state, new_val)
    temp_val = tf.add(update, 1.0)
    up2=tf.assign(update, temp_val)
    init = tf.initialize_all_variables()
    with tf.Session() as sess:
        sess.run(init)
        for _ in range(10):
            x=sess.run(state)
            print 'x=',x
            u2,u,s,n,t = sess.run([up2,update,state,new_val,temp_val])
            print u2,u,s,n,t
    
    
    """
    x= 0.0
    2.0 1.0 0.0 1.0 2.0
    x= 2.0
    4.0 3.0 2.0 3.0 4.0
    x= 4.0
    6.0 5.0 4.0 5.0 6.0
    x= 6.0
    8.0 7.0 6.0 7.0 8.0
    x= 8.0
    10.0 9.0 8.0 9.0 10.0
    x= 10.0
    12.0 12.0 12.0 11.0 12.0
    x= 12.0
    14.0 13.0 12.0 13.0 14.0
    x= 14.0
    16.0 15.0 14.0 15.0 16.0
    x= 16.0
    18.0 17.0 16.0 17.0 18.0
    x= 18.0
    20.0 19.0 18.0 19.0 20.0
    """

    分开则不会。

    表明列表中的运算是独立并行的。

    import tensorflow as tf
    
    state = tf.Variable(0.0,dtype=tf.float32)
    new_val = tf.add(state, 1.0)
    update = tf.assign(state, new_val)
    temp_val = tf.add(update, 1.0)
    up2=tf.assign(update, temp_val)
    init = tf.initialize_all_variables()
    with tf.Session() as sess:
        sess.run(init)
        for _ in range(20):
            x=sess.run(state)
            print 'x=',x
            u = sess.run(update)
            s = sess.run(state)
            print 'u,s=',u,s
    
    """
    x= 0.0
    u,s= 1.0 1.0
    x= 1.0
    u,s= 2.0 2.0
    x= 2.0
    u,s= 3.0 3.0
    x= 3.0
    u,s= 4.0 4.0
    x= 4.0
    u,s= 5.0 5.0
    x= 5.0
    u,s= 6.0 6.0
    x= 6.0
    u,s= 7.0 7.0
    x= 7.0
    u,s= 8.0 8.0
    x= 8.0
    u,s= 9.0 9.0
    x= 9.0
    u,s= 10.0 10.0
    x= 10.0
    u,s= 11.0 11.0
    x= 11.0
    u,s= 12.0 12.0
    x= 12.0
    u,s= 13.0 13.0
    x= 13.0
    u,s= 14.0 14.0
    x= 14.0
    u,s= 15.0 15.0
    x= 15.0
    u,s= 16.0 16.0
    x= 16.0
    u,s= 17.0 17.0
    x= 17.0
    u,s= 18.0 18.0
    x= 18.0
    u,s= 19.0 19.0
    x= 19.0
    u,s= 20.0 20.0
    """
  • 相关阅读:
    进入Docker 报错
    Oauth一直无限重定向
    jquery.click() not working in iOS
    IOS 系统 form 表单提交的问题;一直当前页面刷新
    Word 搜索功能显示bug
    百度脑图bug
    微信分享链接添加参数后缩略图不显示如何解决?
    微信分享到朋友圈 QQ空间 代码实现
    文献复现 | The support of human genetic evidence for approved drug indications
    生物医药领域 | 知名投资人 | VC | PE | IBD | 公募 | 私募
  • 原文地址:https://www.cnblogs.com/qw12/p/6238460.html
Copyright © 2011-2022 走看看