TensorFlow教程之API DOC 6.3.2. CLIENT

简介:

本文档为TensorFlow参考文档,本转载已得到TensorFlow中文社区授权。



Running Graphs

Contents

Running Graphs

This library contains classes for launching graphs and executing operations.

The basic usage guide has examples of how a graph is launched in a tf.Session.

Session management


class tf.Session

A class for running TensorFlow operations.

Session object encapsulates the environment in which Operation objects are executed, and Tensorobjects are evaluated. For example:

# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b

# Launch the graph in a session.
sess = tf.Session()

# Evaluate the tensor `c`.
print sess.run(c)

A session may own resources, such as variablesqueues, and readers. It is important to release these resources when they are no longer required. To do this, either invoke the close() method on the session, or use the session as a context manager. The following two examples are equivalent:

# Using the `close()` method.
sess = tf.Session()
sess.run(...)
sess.close()

# Using the context manager.
with tf.Session() as sess:
  sess.run(...)

The [ConfigProto] (https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/core/framework/config.proto) protocol buffer exposes various configuration options for a session. For example, to create a session that uses soft constraints for device placement, and log the resulting placement decisions, create a session as follows:

# Launch the graph in a session that allows soft device placement and
# logs the placement decisions.
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                        log_device_placement=True))

tf.Session.__init__(target='', graph=None, config=None)

Creates a new TensorFlow session.

If no graph argument is specified when constructing the session, the default graph will be launched in the session. If you are using more than one graph (created with tf.Graph() in the same process, you will have to use different sessions for each graph, but each graph can be used in multiple sessions. In this case, it is often clearer to pass the graph to be launched explicitly to the session constructor.

Args:
  • target: (Optional.) The execution engine to connect to. Defaults to using an in-process engine. At present, no value other than the empty string is supported.
  • graph: (Optional.) The Graph to be launched (described above).
  • config: (Optional.) A ConfigProto protocol buffer with configuration options for the session.

tf.Session.run(fetches, feed_dict=None)

Runs the operations and evaluates the 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_dictfor the corresponding input values.

The fetches argument may be a list of graph elements or a single graph element, and these determine the return value of this method. A graph element can be one of the following types:

  • If the ith element of fetches is an Operation, the ith return value will be None.
  • If the ith element of fetches is a Tensor, the ith return value will be a numpy ndarray containing the value of that tensor.
  • If the ith element of fetches is a SparseTensor, the ith return value will be a SparseTensorValuecontaining the value of that sparse tensor.

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, 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, the shape of the value will be checked for compatibility with the placeholder.
  • If the key is a SparseTensor, the value should be a SparseTensorValue.
Args:
  • fetches: A single graph element, or a list of graph elements (described above).
  • feed_dict: A dictionary that maps graph elements to values (described above).
Returns:

Either a single value if fetches is a single graph element, or a list of values if fetches is a list (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.

tf.Session.close()

Closes this session.

Calling this method frees all resources associated with the session.

Raises:
  • RuntimeError: If an error occurs while closing the session.

tf.Session.graph

The graph that was launched in this session.


tf.Session.as_default()

Returns a context manager that makes this object the default session.

Use with the with keyword to specify that calls to Operation.run() or Tensor.run() should be executed in this session.

c = tf.constant(..)
sess = tf.Session()

with sess.as_default():
  assert tf.get_default_session() is sess
  print c.eval()

To get the current default session, use tf.get_default_session().

N.B. The as_default context manager does not close the session when you exit the context, and you must close the session explicitly.

c = tf.constant(...)
sess = tf.Session()
with sess.as_default():
  print c.eval()
# ...
with sess.as_default():
  print c.eval()

sess.close()

Alternatively, you can use with tf.Session(): to create a session that is automatically closed on exiting the context, including when an uncaught exception is raised.

N.B. The default graph is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a with sess.as_default(): in that thread's function.

Returns:

A context manager using this session as the default session.


class tf.InteractiveSession

A TensorFlow Session for use in interactive contexts, such as a shell.

The only difference with a regular Session is that an InteractiveSession installs itself as the default session on construction. The methods Tensor.eval() and Operation.run() will use that session to run ops.

This is convenient in interactive shells and IPython notebooks, as it avoids having to pass an explicitSession object to run ops.

For example:

sess = tf.InteractiveSession()
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
# We can just use 'c.eval()' without passing 'sess'
print c.eval()
sess.close()

Note that a regular session installs itself as the default session when it is created in a with statement. The common usage in non-interactive programs is to follow that pattern:

a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
with tf.Session():
  # We can also use 'c.eval()' here.
  print c.eval()

tf.InteractiveSession.__init__(target='', graph=None)

Creates a new interactive TensorFlow session.

If no graph argument is specified when constructing the session, the default graph will be launched in the session. If you are using more than one graph (created with tf.Graph() in the same process, you will have to use different sessions for each graph, but each graph can be used in multiple sessions. In this case, it is often clearer to pass the graph to be launched explicitly to the session constructor.

Args:
  • target: (Optional.) The execution engine to connect to. Defaults to using an in-process engine. At present, no value other than the empty string is supported.
  • graph: (Optional.) The Graph to be launched (described above).

tf.InteractiveSession.close()

Closes an InteractiveSession.


tf.get_default_session()

Returns the default session for the current thread.

The returned Session will be the innermost session on which a Session or Session.as_default()context has been entered.

N.B. The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a with sess.as_default(): in that thread's function.

Returns:

The default Session being used in the current thread.

Error classes


class tf.OpError

A generic error that is raised when TensorFlow execution fails.

Whenever possible, the session will raise a more specific subclass of OpError from the tf.errorsmodule.


tf.OpError.op

The operation that failed, if known.

N.B. If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no correspondingOperation object. In that case, this will return None, and you should instead use the OpError.node_defto discover information about the op.

Returns:

The Operation that failed, or None.


tf.OpError.node_def

The NodeDef proto representing the op that failed.

Other Methods


tf.OpError.__init__(node_def, op, message, error_code)

Creates a new OpError indicating that a particular op failed.

Args:
  • node_def: The graph_pb2.NodeDef proto representing the op that failed.
  • op: The ops.Operation that failed, if known; otherwise None.
  • message: The message string describing the failure.
  • error_code: The error_codes_pb2.Code describing the error.

tf.OpError.error_code

The integer error code that describes the error.


tf.OpError.message

The error message that describes the error.


class tf.errors.CancelledError

Raised when an operation or step is cancelled.

For example, a long-running operation (e.g. queue.enqueue() may be cancelled by running another operation (e.g. queue.close(cancel_pending_enqueues=True), or by closing the session. A step that is running such a long-running operation will fail by raising CancelledError.


tf.errors.CancelledError.__init__(node_def, op, message)

Creates a CancelledError.


class tf.errors.UnknownError

Unknown error.

An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known to this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.


tf.errors.UnknownError.__init__(node_def, op, message, error_code=2)

Creates an UnknownError.


class tf.errors.InvalidArgumentError

Raised when an operation receives an invalid argument.

This may occur, for example, if an operation is receives an input tensor that has an invalid value or shape. For example, the tf.matmul() op will raise this error if it receives an input that is not a matrix, and thetf.reshape() op will raise this error if the new shape does not match the number of elements in the input tensor.


tf.errors.InvalidArgumentError.__init__(node_def, op, message)

Creates an InvalidArgumentError.


class tf.errors.DeadlineExceededError

Raised when a deadline expires before an operation could complete.

This exception is not currently used.


tf.errors.DeadlineExceededError.__init__(node_def, op, message)

Creates a DeadlineExceededError.


class tf.errors.NotFoundError

Raised when a requested entity (e.g., a file or directory) was not found.

For example, running the tf.WholeFileReader.read() operation could raise NotFoundError if it receives the name of a file that does not exist.


tf.errors.NotFoundError.__init__(node_def, op, message)

Creates a NotFoundError.


class tf.errors.AlreadyExistsError

Raised when an entity that we attempted to create already exists.

For example, running an operation that saves a file (e.g. tf.train.Saver.save()) could potentially raise this exception if an explicit filename for an existing file was passed.


tf.errors.AlreadyExistsError.__init__(node_def, op, message)

Creates an AlreadyExistsError.


class tf.errors.PermissionDeniedError

Raised when the caller does not have permission to run an operation.

For example, running the tf.WholeFileReader.read() operation could raise PermissionDeniedError if it receives the name of a file for which the user does not have the read file permission.


tf.errors.PermissionDeniedError.__init__(node_def, op, message)

Creates a PermissionDeniedError.


class tf.errors.UnauthenticatedError

The request does not have valid authentication credentials.

This exception is not currently used.


tf.errors.UnauthenticatedError.__init__(node_def, op, message)

Creates an UnauthenticatedError.


class tf.errors.ResourceExhaustedError

Some resource has been exhausted.

For example, this error might be raised if a per-user quota is exhausted, or perhaps the entire file system is out of space.


tf.errors.ResourceExhaustedError.__init__(node_def, op, message)

Creates a ResourceExhaustedError.


class tf.errors.FailedPreconditionError

Operation was rejected because the system is not in a state to execute it.

This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.


tf.errors.FailedPreconditionError.__init__(node_def, op, message)

Creates a FailedPreconditionError.


class tf.errors.AbortedError

The operation was aborted, typically due to a concurrent action.

For example, running a queue.enqueue() operation may raise AbortedError if a queue.close()operation previously ran.


tf.errors.AbortedError.__init__(node_def, op, message)

Creates an AbortedError.


class tf.errors.OutOfRangeError

Raised when an operation executed past the valid range.

This exception is raised in "end-of-file" conditions, such as when a queue.dequeue() operation is blocked on an empty queue, and a queue.close() operation executes.


tf.errors.OutOfRangeError.__init__(node_def, op, message)

Creates an OutOfRangeError.


class tf.errors.UnimplementedError

Raised when an operation has not been implemented.

Some operations may raise this error when passed otherwise-valid arguments that it does not currently support. For example, running the tf.nn.max_pool() operation would raise this error if pooling was requested on the batch dimension, because this is not yet supported.


tf.errors.UnimplementedError.__init__(node_def, op, message)

Creates an UnimplementedError.


class tf.errors.InternalError

Raised when the system experiences an internal error.

This exception is raised when some invariant expected by the runtime has been broken. Catching this exception is not recommended.


tf.errors.InternalError.__init__(node_def, op, message)

Creates an InternalError.


class tf.errors.UnavailableError

Raised when the runtime is currently unavailable.

This exception is not currently used.


tf.errors.UnavailableError.__init__(node_def, op, message)

Creates an UnavailableError.


class tf.errors.DataLossError

Raised when unrecoverable data loss or corruption is encountered.

For example, this may be raised by running a tf.WholeFileReader.read() operation, if the file is truncated while it is being read.


tf.errors.DataLossError.__init__(node_def, op, message)

Creates a DataLossError.

相关文章
|
2月前
|
JSON 监控 API
在线网络PING接口检测服务器连通状态免费API教程
接口盒子提供免费PING检测API,可测试域名或IP的连通性与响应速度,支持指定地域节点,适用于服务器运维和网络监控。
|
2月前
|
JSON API PHP
通用图片搜索API:百度源免费接口教程
本文介绍一款基于百度图片搜索的免费API接口,由接口盒子提供。支持关键词搜索,具备详细请求与返回参数说明,并提供PHP及Python调用示例。开发者可快速集成实现图片搜索功能,适用于内容聚合、素材库建设等场景。
|
2月前
|
JSON 机器人 API
随机昵称网名API接口教程:轻松获取百万创意昵称库
接口盒子提供随机昵称网名API,拥有百万级中文昵称库,支持聊天机器人、游戏角色等场景的昵称生成。提供详细调用指南及多语言示例代码,助力开发者高效集成。
|
2月前
|
存储 JSON API
文本存储免费API接口教程
接口盒子提供免费文本存储服务,支持1000条记录,每条最多5000字符,适用于公告、日志、配置等场景,支持修改与读取。
|
2月前
|
数据采集 JSON 监控
获取网页状态码(可指定地域)免费API接口教程
本文介绍如何使用接口盒子的免费API获取网页状态码,支持国内、香港、美国等不同地域访问节点。内容包括接口参数、调用方法及示例,适用于网站监控、链接检查等场景。
|
9月前
|
机器学习/深度学习 人工智能 算法
猫狗宠物识别系统Python+TensorFlow+人工智能+深度学习+卷积网络算法
宠物识别系统使用Python和TensorFlow搭建卷积神经网络,基于37种常见猫狗数据集训练高精度模型,并保存为h5格式。通过Django框架搭建Web平台,用户上传宠物图片即可识别其名称,提供便捷的宠物识别服务。
787 55
|
10月前
|
机器学习/深度学习 数据采集 数据可视化
TensorFlow,一款由谷歌开发的开源深度学习框架,详细讲解了使用 TensorFlow 构建深度学习模型的步骤
本文介绍了 TensorFlow,一款由谷歌开发的开源深度学习框架,详细讲解了使用 TensorFlow 构建深度学习模型的步骤,包括数据准备、模型定义、损失函数与优化器选择、模型训练与评估、模型保存与部署,并展示了构建全连接神经网络的具体示例。此外,还探讨了 TensorFlow 的高级特性,如自动微分、模型可视化和分布式训练,以及其在未来的发展前景。
853 5
|
10月前
|
机器学习/深度学习 人工智能 TensorFlow
基于TensorFlow的深度学习模型训练与优化实战
基于TensorFlow的深度学习模型训练与优化实战
436 3
|
10月前
|
机器学习/深度学习 人工智能 算法
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
垃圾识别分类系统。本系统采用Python作为主要编程语言,通过收集了5种常见的垃圾数据集('塑料', '玻璃', '纸张', '纸板', '金属'),然后基于TensorFlow搭建卷积神经网络算法模型,通过对图像数据集进行多轮迭代训练,最后得到一个识别精度较高的模型文件。然后使用Django搭建Web网页端可视化操作界面,实现用户在网页端上传一张垃圾图片识别其名称。
412 0
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
|
10月前
|
机器学习/深度学习 人工智能 算法
【手写数字识别】Python+深度学习+机器学习+人工智能+TensorFlow+算法模型
手写数字识别系统,使用Python作为主要开发语言,基于深度学习TensorFlow框架,搭建卷积神经网络算法。并通过对数据集进行训练,最后得到一个识别精度较高的模型。并基于Flask框架,开发网页端操作平台,实现用户上传一张图片识别其名称。
368 0
【手写数字识别】Python+深度学习+机器学习+人工智能+TensorFlow+算法模型

热门文章

最新文章