TensorFlow教程之API DOC 6.3.3. CONSTANT OP

简介:

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


Constants, Sequences, and Random Values

Note: Functions taking Tensor arguments can also take anything accepted by tf.convert_to_tensor.

Contents

Constants, Sequences, and Random Values

Constant Value Tensors

TensorFlow provides several operations that you can use to generate constants.


tf.zeros(shape, dtype=tf.float32, name=None)

Creates a tensor with all elements set to zero.

This operation returns a tensor of type dtype with shape shape and all elements set to zero.

For example:

tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Args:
  • shape: Either a list of integers, or a 1-D Tensor of type int32.
  • dtype: The type of an element in the resulting Tensor.
  • name: A name for the operation (optional).
Returns:

Tensor with all elements set to zero.


tf.zeros_like(tensor, dtype=None, name=None)

Creates a tensor with all elements set to zero.

Given a single tensor (tensor), this operation returns a tensor of the same type and shape as tensorwith all elements set to zero. Optionally, you can use dtype to specify a new type for the returned tensor.

For example:

# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]]
Args:
  • tensor: A Tensor.
  • dtype: A type for the returned Tensor. Must be float32float64int8int16int32int64uint8, or complex64.

  • name: A name for the operation (optional).

Returns:

Tensor with all elements set to zero.


tf.ones(shape, dtype=tf.float32, name=None)

Creates a tensor with all elements set to 1.

This operation returns a tensor of type dtype with shape shape and all elements set to 1.

For example:

tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]
Args:
  • shape: Either a list of integers, or a 1-D Tensor of type int32.
  • dtype: The type of an element in the resulting Tensor.
  • name: A name for the operation (optional).
Returns:

Tensor with all elements set to 1.


tf.ones_like(tensor, dtype=None, name=None)

Creates a tensor with all elements set to 1.

Given a single tensor (tensor), this operation returns a tensor of the same type and shape as tensorwith all elements set to 1. Optionally, you can specify a new type (dtype) for the returned tensor.

For example:

# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.ones_like(tensor) ==> [[1, 1, 1], [1, 1, 1]]
Args:
  • tensor: A Tensor.
  • dtype: A type for the returned Tensor. Must be float32float64int8int16int32int64uint8, or complex64.

  • name: A name for the operation (optional).

Returns:

Tensor with all elements set to 1.


tf.fill(dims, value, name=None)

Creates a tensor filled with a scalar value.

This operation creates a tensor of shape dims and fills it with value.

For example:

# output tensor shape needs to be [2, 3]
# so 'dims' is [2, 3]
fill(dims, 9) ==> [[9, 9, 9]
                   [9, 9, 9]]
Args:
  • dims: A Tensor of type int32. 1-D. Represents the shape of the output tensor.
  • value: A Tensor. 0-D (scalar). Value to fill the returned tensor.
  • name: A name for the operation (optional).
Returns:

Tensor. Has the same type as value.


tf.constant(value, dtype=None, shape=None, name='Const')

Creates a constant tensor.

The resulting tensor is populated with values of type dtype, as specified by arguments value and (optionally) shape (see examples below).

The argument value can be a constant value, or a list of values of type dtype. If value is a list, then the length of the list must be less than or equal to the number of elements implied by the shapeargument (if specified). In the case where the list length is less than the number of elements specified by shape, the last element in the list will be used to fill the remaining entries.

The argument shape is optional. If present, it specifies the dimensions of the resulting tensor. If not present, then the tensor is a scalar (0-D) if value is a scalar, or 1-D otherwise.

If the argument dtype is not specified, then the type is inferred from the type of value.

For example:

 # Constant 1-D Tensor populated with value list.
 tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]

 # Constant 2-D tensor populated with scalar value -1.
 tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
                                              [-1. -1. -1.]]
Args:
  • value: A constant value (or list) of output type dtype.
  • dtype: The type of the elements of the resulting tensor.
  • shape: Optional dimensions of resulting tensor.
  • name: Optional name for the tensor.
Returns:

A Constant Tensor.

Sequences


tf.linspace(start, stop, num, name=None)

Generates values in an interval.

A sequence of num evenly-spaced values are generated beginning at start. If num > 1, the values in the sequence increase by stop - start / num - 1, so that the last one is exactly stop.

For example:

tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0  11.0  12.0]
Args:
  • start: A Tensor. Must be one of the following types: float32float64. First entry in the range.
  • stop: A Tensor. Must have the same type as start. Last entry in the range.
  • num: A Tensor of type int32. Number of values to generate.
  • name: A name for the operation (optional).
Returns:

Tensor. Has the same type as start. 1-D. The generated values.


tf.range(start, limit, delta=1, name='range')

Creates a sequence of integers.

This operation creates a sequence of integers that begins at start and extends by increments of delta up to but not including limit.

For example:

# 'start' is 3
# 'limit' is 18
# 'delta' is 3
tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]
Args:
  • start: A 0-D (scalar) of type int32. First entry in sequence.
  • limit: A 0-D (scalar) of type int32. Upper limit of sequence, exclusive.
  • delta: A 0-D Tensor (scalar) of type int32. Optional. Default is 1. Number that increments start.
  • name: A name for the operation (optional).
Returns:

An 1-D int32 Tensor.

Random Tensors

TensorFlow has several ops that create random tensors with different distributions. The random ops are stateful, and create new random values each time they are evaluated.

The seed keyword argument in these functions acts in conjunction with the graph-level random seed. Changing either the graph-level seed using set_random_seed or the op-level seed will change the underlying seed of these operations. Setting neither graph-level nor op-level seed, results in a random seed for all operations. See set_random_seed for details on the interaction between operation-level and graph-level random seeds.

Examples:

# Create a tensor of shape [2, 3] consisting of random normal values, with mean
# -1 and standard deviation 4.
norm = tf.random_normal([2, 3], mean=-1, stddev=4)

# Shuffle the first dimension of a tensor
c = tf.constant([[1, 2], [3, 4], [5, 6]])
shuff = tf.random_shuffle(c)

# Each time we run these ops, different results are generated
sess = tf.Session()
print sess.run(norm)
print sess.run(norm)

# Set an op-level seed to generate repeatable sequences across sessions.
c = tf.constant([[1, 2], [3, 4], [5, 6]])
sess = tf.Session()
norm = tf.random_normal(c, seed=1234)
print sess.run(norm)
print sess.run(norm)

Another common use of random values is the intialization of variables. Also see the Variables How To.

# Use random uniform values in [0, 1) as the initializer for a variable of shape
# [2, 3]. The default type is float32.
var = tf.Variable(tf.random_uniform([2, 3]), name="var")
init = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init)
print sess.run(var)

tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

Outputs random values from a normal distribution.

Args:
  • shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
  • mean: A 0-D Tensor or Python value of type dtype. The mean of the normal distribution.
  • stddev: A 0-D Tensor or Python value of type dtype. The standard deviation of the normal distribution.
  • dtype: The type of the output.
  • seed: A Python integer. Used to create a random seed for the distribution. See set_random_seed for behavior.
  • name: A name for the operation (optional).
Returns:

A tensor of the specified shape filled with random normal values.


tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

Outputs random values from a truncated normal distribution.

The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked.

Args:
  • shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
  • mean: A 0-D Tensor or Python value of type dtype. The mean of the truncated normal distribution.
  • stddev: A 0-D Tensor or Python value of type dtype. The standard deviation of the truncated normal distribution.
  • dtype: The type of the output.
  • seed: A Python integer. Used to create a random seed for the distribution. See set_random_seed for behavior.
  • name: A name for the operation (optional).
Returns:

A tensor of the specified shape filled with random truncated normal values.


tf.random_uniform(shape, minval=0.0, maxval=1.0, dtype=tf.float32, seed=None, name=None)

Outputs random values from a uniform distribution.

The generated values follow a uniform distribution in the range [minval, maxval). The lower bound minval is included in the range, while the upper bound maxval is excluded.

Args:
  • shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
  • minval: A 0-D Tensor or Python value of type dtype. The lower bound on the range of random values to generate.
  • maxval: A 0-D Tensor or Python value of type dtype. The upper bound on the range of random values to generate.
  • dtype: The type of the output.
  • seed: A Python integer. Used to create a random seed for the distribution. See set_random_seed for behavior.
  • name: A name for the operation (optional).
Returns:

A tensor of the specified shape filled with random uniform values.


tf.random_shuffle(value, seed=None, name=None)

Randomly shuffles a tensor along its first dimension.

The tensor is shuffled along dimension 0, such that each value[j] is mapped to one and only one output[i]. For example, a mapping that might occur for a 3x2 tensor is:

[[1, 2],       [[5, 6],
 [3, 4],  ==>   [1, 2],
 [5, 6]]        [3, 4]]
Args:
  • value: A Tensor to be shuffled.
  • seed: A Python integer. Used to create a random seed for the distribution. See set_random_seed for behavior.
  • name: A name for the operation (optional).
Returns:

A tensor of same shape and type as value, shuffled along its first dimension.


tf.set_random_seed(seed)

Sets the graph-level random seed.

Operations that rely on a random seed actually derive it from two seeds: the graph-level and operation-level seeds. This sets the graph-level seed.

Its interactions with operation-level seeds is as follows:

  1. If neither the graph-level nor the operation seed is set: A random seed is used for this op.
  2. If the graph-level seed is set, but the operation seed is not: The system deterministically picks an operation seed in conjunction with the graph-level seed so that it gets a unique random sequence.
  3. If the graph-level seed is not set, but the operation seed is set: A default graph-level seed and the specified operation seed are used to determine the random sequence.
  4. If both the graph-level and the operation seed are set: Both seeds are used in conjunction to determine the random sequence.

To illustrate the user-visible effects, consider these examples:

To generate different sequences across sessions, set neither graph-level nor op-level seeds:

a = tf.random_uniform([1])
b = tf.random_normal([1])

print "Session 1"
with tf.Session() as sess1:
  print sess1.run(a)  # generates 'A1'
  print sess1.run(a)  # generates 'A2'
  print sess1.run(b)  # generates 'B1'
  print sess1.run(b)  # generates 'B2'

print "Session 2"
with tf.Session() as sess2:
  print sess2.run(a)  # generates 'A3'
  print sess2.run(a)  # generates 'A4'
  print sess2.run(b)  # generates 'B3'
  print sess2.run(b)  # generates 'B4'

To generate the same repeatable sequence for an op across sessions, set the seed for the op:

a = tf.random_uniform([1], seed=1)
b = tf.random_normal([1])

# Repeatedly running this block with the same graph will generate the same
# sequence of values for 'a', but different sequences of values for 'b'.
print "Session 1"
with tf.Session() as sess1:
  print sess1.run(a)  # generates 'A1'
  print sess1.run(a)  # generates 'A2'
  print sess1.run(b)  # generates 'B1'
  print sess1.run(b)  # generates 'B2'

print "Session 2"
with tf.Session() as sess2:
  print sess2.run(a)  # generates 'A1'
  print sess2.run(a)  # generates 'A2'
  print sess2.run(b)  # generates 'B3'
  print sess2.run(b)  # generates 'B4'

To make the random sequences generated by all ops be repeatable across sessions, set a graph-level seed:

tf.set_random_seed(1234)
a = tf.random_uniform([1])
b = tf.random_normal([1])

# Repeatedly running this block with the same graph will generate different
# sequences of 'a' and 'b'.
print "Session 1"
with tf.Session() as sess1:
  print sess1.run(a)  # generates 'A1'
  print sess1.run(a)  # generates 'A2'
  print sess1.run(b)  # generates 'B1'
  print sess1.run(b)  # generates 'B2'

print "Session 2"
with tf.Session() as sess2:
  print sess2.run(a)  # generates 'A1'
  print sess2.run(a)  # generates 'A2'
  print sess2.run(b)  # generates 'B1'
  print sess2.run(b)  # generates 'B2'
Args:
  • seed: integer.
相关文章
|
4月前
|
人工智能 数据可视化 测试技术
Postman 性能测试教程:快速上手 API 压测
本文介绍API上线后因高频调用导致服务器告警,通过Postman与Apifox进行压力测试排查性能瓶颈。对比两款工具在批量请求、断言验证、可视化报告等方面的优劣,探讨API性能优化策略及行业未来发展方向。
Postman 性能测试教程:快速上手 API 压测
|
6月前
|
JSON API 网络安全
通用邮箱邮件获取API教程:支持IMAP/POP3协议
本文介绍如何通过接口盒子的免费API获取邮箱邮件,支持IMAP/POP3协议,适用于QQ邮箱、网易邮箱等主流服务。内容包括接口基本信息、请求参数、返回参数、调用示例及注意事项,帮助开发者快速实现邮件读取功能。
843 7
|
6月前
|
JSON 监控 API
在线网络PING接口检测服务器连通状态免费API教程
接口盒子提供免费PING检测API,可测试域名或IP的连通性与响应速度,支持指定地域节点,适用于服务器运维和网络监控。
698 0
|
6月前
|
JSON API PHP
通用图片搜索API:百度源免费接口教程
本文介绍一款基于百度图片搜索的免费API接口,由接口盒子提供。支持关键词搜索,具备详细请求与返回参数说明,并提供PHP及Python调用示例。开发者可快速集成实现图片搜索功能,适用于内容聚合、素材库建设等场景。
917 0
|
6月前
|
JSON 机器人 API
随机昵称网名API接口教程:轻松获取百万创意昵称库
接口盒子提供随机昵称网名API,拥有百万级中文昵称库,支持聊天机器人、游戏角色等场景的昵称生成。提供详细调用指南及多语言示例代码,助力开发者高效集成。
619 0
|
4月前
|
人工智能 API 开发者
图文教程:阿里云百炼API-KEY获取方法,亲测全流程
本文详细介绍了如何获取阿里云百炼API-KEY,包含完整流程与截图指引。需先开通百炼平台及大模型服务,再通过控制台创建并复制API-KEY。目前平台提供千万tokens免费额度,适合开发者快速上手使用。
3639 5
|
6月前
|
JSON API PHP
天气预报免费API接口【地址查询版】使用教程
本文介绍了如何使用中国气象局官方数据提供的免费天气预报API接口,通过省份和地点查询指定地区当日天气信息。该接口由接口盒子支持,提供JSON格式数据、GET/POST请求方式,并需注册获取用户ID和KEY进行身份验证。
3792 2
|
6月前
|
JSON Shell API
查手机号归属地免费API接口教程
本接口提供手机号码归属地查询功能,支持获取号段、归属地省份/城市、运营商、区号、邮编等信息。请求地址为 `https://cn.apihz.cn/api/ip/shouji.php`,支持 POST 或 GET 方式调用,需提供 `id`、`key` 和 `phone` 参数。返回包含归属地信息及运营商等数据,适用于手机号归属查询场景。
1133 6
|
6月前
|
JSON API PHP
ICP备案查询免费API接口使用教程
本文介绍如何通过接口盒子提供的免费API接口查询域名ICP备案信息,包含请求地址、参数说明及PHP和Python调用示例,适用于开发者快速集成备案查询功能。
523 1