TensorFlow学习(六):形状相关操作

来源:互联网 发布:皇家骑士团java 编辑:程序博客网 时间:2024/05/16 14:31

tf.shape(input, name=None, out_type=tf.int32)

作用:
返回一个1维tensor表示input的形状
参数:
input: 输入的tensor
name: 可选,这个操作的名字
out_type: (可选)输出的类型(int32 or int64), 默认tf.int32

例:

# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]shape(t) ==> [2, 2, 3]

tf.shape_n(input, out_type=None, name=None)

Returns shape of tensors.

This operation returns N 1-D integer tensors representing shape of input[i]s.

Args:

input: A list of at least 1 Tensor objects of the same type.
out_type: An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32.
name: A name for the operation (optional).
Returns:

A list with the same number of Tensor objects as input of Tensor objects of type out_type.

tf.size(input, name=None, out_type=tf.int32)

作用:返回一个tensor的size,也即是input的元素数量
参数:
input: 输入的tensor
name: 操作的名字
out_type: 输出的类型 (int32 or int64),默认int32

例子:

# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]]size(t) ==> 12

tf.rank(input, name=None)

作用:返回一个tensor的rank,也可以理解为维度数
参数:
input: 输入的tensor
name: 操作名字

例子:

# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]# shape of tensor 't' is [2, 2, 3]rank(t) ==> 3

shepe的综合例子

from __future__ import print_function,divisionimport numpy as npimport tensorflow as tf#define graphgraph=tf.Graph()with graph.as_default():    c1=tf.constant([[1,2,3],[4,5,6],[7,8,9]],dtype=tf.float32,name="c1")    c2=tf.constant([1,2,3,4,5,6],dtype=tf.float32,name="c2")    c3=tf.random_normal(shape=(3,2,3))    shape_c1=tf.shape(c1)   # shape_nc1=tf.shape_n(c1)    shape_c2=tf.shape(c2)    shape_c3=tf.shape(c3)#run graphwith tf.Session(graph=graph) as sess:            _shape_c1,_shape_c2,_shape_c3,c3=sess.run([shape_c1,shape_c2,shape_c3,c3])    print ("shape of c1:",_shape_c1)   # print ("shape of n_c1:",_shape_nc1)    print ("c3:",c3)    #size test    size=sess.run(tf.size(c3))    print("size of c3:",size)    #rank test    rank=sess.run(tf.rank(c3))    print ("rank of c3:",rank)

tf.reshape(tensor, shape, name=None)

作用:
改变一个tensor的形状,按照指定的shape返回一个tensor。要是形状的某个分量是特殊值-1,那么就会计算该维度的大小,使得总大小(元素数量)保持不变,特殊的,如果传入的形状是[-1],那么意味着把整个tensor弄平为1维。必须确保变形前和变形之后的总元素个数是相同的。
参数:
tensor: tensor,待被改变形状的tensor
shape: tensor,必须是 int32, int64.决定了输出tensor的形状
name: (可选),操作的名称
如果形状的一个分量是特殊值-1,则计算该维度的大小,以使总大小保持不变。

举个例子

# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]# tensor 't' has shape [9]reshape(t, [3, 3]) ==> [[1, 2, 3],                        [4, 5, 6],                        [7, 8, 9]]# tensor 't' is [[[1, 1], [2, 2]],#                [[3, 3], [4, 4]]]# tensor 't' has shape [2, 2, 2]reshape(t, [2, 4]) ==> [[1, 1, 2, 2],                        [3, 3, 4, 4]]# tensor 't' is [[[1, 1, 1],#                 [2, 2, 2]],#                [[3, 3, 3],#                 [4, 4, 4]],#                [[5, 5, 5],#                 [6, 6, 6]]]# tensor 't' has shape [3, 2, 3]# pass '[-1]' to flatten 't'reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]# -1 can also be used to infer the shape# -1 is inferred to be 9:reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]# -1 is inferred to be 2:reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]# -1 is inferred to be 3:reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],                              [2, 2, 2],                              [3, 3, 3]],                             [[4, 4, 4],                              [5, 5, 5],                              [6, 6, 6]]]# tensor 't' is [7]# shape `[]` reshapes to a scalarreshape(t, []) ==> 7

tf.squeeze(input, squeeze_dims=None, name=None)

Removes dimensions of size 1 from the shape of a tensor.

Given a tensor input, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don’t want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying squeeze_dims.

For example:

# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]shape(squeeze(t)) ==> [2, 3]Or, to remove specific size 1 dimensions:# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]

Args:

input: A Tensor. The input to squeeze.
squeeze_dims: An optional list of ints. Defaults to []. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1.
name: A name for the operation (optional).
Returns:

A Tensor. Has the same type as input. Contains the same data as input, but has one or more dimensions of size 1 removed.

tf.expand_dims(input, dim, name=None)

Inserts a dimension of 1 into a tensor’s shape.

Given a tensor input, this operation inserts a dimension of 1 at the dimension index dim of input’s shape. The dimension index dim starts at zero; if you specify a negative number for dim it is counted backward from the end.

This operation is useful if you want to add a batch dimension to a single element. For example, if you have a single image of shape [height, width, channels], you can make it a batch of 1 image with expand_dims(image, 0), which will make the shape [1, height, width, channels].

Other examples:

# 't' is a tensor of shape [2]shape(expand_dims(t, 0)) ==> [1, 2]shape(expand_dims(t, 1)) ==> [2, 1]shape(expand_dims(t, -1)) ==> [2, 1]# 't2' is a tensor of shape [2, 3, 5]shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]

This operation requires that:

-1-input.dims() <= dim <= input.dims()

This operation is related to squeeze(), which removes dimensions of size 1.

Args:

input: A Tensor.
dim: A Tensor. Must be one of the following types: int32, int64. 0-D (scalar). Specifies the dimension index at which to expand the shape of input.
name: A name for the operation (optional).
Returns:

A Tensor. Has the same type as input. Contains the same data as input, but its shape has an additional dimension of size 1 added.

tf.meshgrid(*args, **kwargs)

Broadcasts parameters for evaluation on an N-D grid.

Given N one-dimensional coordinate arrays *args, returns a list outputs of N-D coordinate arrays for evaluating expressions on an N-D grid.

Notes:

meshgrid supports cartesian (‘xy’) and matrix (‘ij’) indexing conventions. When the indexing argument is set to ‘xy’ (the default), the broadcasting instructions for the first two dimensions are swapped.

Examples:

Calling X, Y = meshgrid(x, y) with the tensors

x = [1, 2, 3]
y = [4, 5, 6]
results in

X = [[1, 1, 1],
[2, 2, 2],
[3, 3, 3]]
Y = [[4, 5, 6],
[4, 5, 6],
[4, 5, 6]]
Args:

*args: Tensors with rank 1
indexing: Either ‘xy’ or ‘ij’ (optional, default: ‘xy’)
name: A name for the operation (optional).
Returns:

outputs: A list of N Tensors with rank N

tf.reduce_sum(input_tensor, reduction_indices=None, keep_dims=False, name=None)

作用:计算tensor的某个维度上面元素的和.在给定的reduction_indices 上面缩减input_tensor ,除非keep_dims 设为True,不然相应轴上面的维度要减少1
如果reduction_indices 没有输入(默认为None),那么所有的维度都会缩减,返回一个只带一个元素的tensor
参数:
input_tensor: 待reduce的tensor,需要数值类型
reduction_indices: 在这个维度上面reduce
keep_dims: 要是为True的话,维度不会缩减1.
name: (可选),这个操作的名称

例:

# 'x' is [[1, 1, 1]#         [1, 1, 1]]tf.reduce_sum(x) ==> 6tf.reduce_sum(x, 0) ==> [2, 2, 2]tf.reduce_sum(x, 1) ==> [3, 3]tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]tf.reduce_sum(x, [0, 1]) ==> 6

tf.reduce_prod(input_tensor, reduction_indices=None, keep_dims=False, name=None)

Computes the product of elements across dimensions of a tensor.

Reduces input_tensor along the dimensions given in reduction_indices. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If keep_dims is true, the reduced dimensions are retained with length 1.

If reduction_indices has no entries, all dimensions are reduced, and a tensor with a single element is returned.

Args:

input_tensor: The tensor to reduce. Should have numeric type.
reduction_indices: The dimensions to reduce. If None (the default), reduces all dimensions.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:

The reduced tensor.

tf.reduce_min(input_tensor, reduction_indices=None, keep_dims=False, name=None)

Computes the minimum of elements across dimensions of a tensor.

Reduces input_tensor along the dimensions given in reduction_indices. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If keep_dims is true, the reduced dimensions are retained with length 1.

If reduction_indices has no entries, all dimensions are reduced, and a tensor with a single element is returned.

Args:

input_tensor: The tensor to reduce. Should have numeric type.
reduction_indices: The dimensions to reduce. If None (the default), reduces all dimensions.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:

The reduced tensor.

tf.reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None)

Computes the maximum of elements across dimensions of a tensor.

Reduces input_tensor along the dimensions given in reduction_indices. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If keep_dims is true, the reduced dimensions are retained with length 1.

If reduction_indices has no entries, all dimensions are reduced, and a tensor with a single element is returned.

Args:

input_tensor: The tensor to reduce. Should have numeric type.
reduction_indices: The dimensions to reduce. If None (the default), reduces all dimensions.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:

The reduced tensor.

tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)

作用:计算tensor上面某个维度的平均值,在给定的reduction_indices 上面缩减input_tensor ,除非keep_dims 设为True,不然相应轴上面的维度要减少1,如果reduction_indices 没有输入(默认为None),那么所有的维度都会缩减,返回一个只带一个元素的tensor
参数:
input_tensor: 待reduce的tensor,需要数值类型
reduction_indices: 在这个维度上面reduce
keep_dims: 要是为True的话,维度不会缩减1.
name: (可选),这个操作的名称
例:

# 'x' is [[1., 1.]#         [2., 2.]]tf.reduce_mean(x) ==> 1.5tf.reduce_mean(x, 0) ==> [1.5, 1.5]tf.reduce_mean(x, 1) ==> [1.,  2.]

tf.reduce_all(input_tensor, reduction_indices=None, keep_dims=False, name=None)

Computes the “logical and” of elements across dimensions of a tensor.

Reduces input_tensor along the dimensions given in reduction_indices. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If keep_dims is true, the reduced dimensions are retained with length 1.

If reduction_indices has no entries, all dimensions are reduced, and a tensor with a single element is returned.

For example:

# 'x' is [[True,  True]#         [False, False]]tf.reduce_all(x) ==> Falsetf.reduce_all(x, 0) ==> [False, False]tf.reduce_all(x, 1) ==> [True, False]

Args:

input_tensor: The boolean tensor to reduce.
reduction_indices: The dimensions to reduce. If None (the default), reduces all dimensions.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:

The reduced tensor.

tf.reduce_any(input_tensor, reduction_indices=None, keep_dims=False, name=None)

Computes the “logical or” of elements across dimensions of a tensor.

Reduces input_tensor along the dimensions given in reduction_indices. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If keep_dims is true, the reduced dimensions are retained with length 1.

If reduction_indices has no entries, all dimensions are reduced, and a tensor with a single element is returned.

For example:

# 'x' is [[True,  True]#         [False, False]]tf.reduce_any(x) ==> Truetf.reduce_any(x, 0) ==> [True, True]tf.reduce_any(x, 1) ==> [True, False]

Args:

input_tensor: The boolean tensor to reduce.
reduction_indices: The dimensions to reduce. If None (the default), reduces all dimensions.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:

The reduced tensor.

tf.reduce_logsumexp(input_tensor, reduction_indices=None, keep_dims=False, name=None)

Computes log(sum(exp(elements across dimensions of a tensor))).

Reduces input_tensor along the dimensions given in reduction_indices. Unless keep_dims is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices. If keep_dims is true, the reduced dimensions are retained with length 1.

If reduction_indices has no entries, all dimensions are reduced, and a tensor with a single element is returned.

This funciton is more numerically stable than log(sum(exp(input))). It avoids overflows caused by taking the exp of large inputs and underflows caused by taking the log of small inputs.

For example:

# 'x' is [[0, 0, 0]]#         [0, 0, 0]]tf.reduce_logsumexp(x) ==> log(6)tf.reduce_logsumexp(x, 0) ==> [log(2), log(2), log(2)]tf.reduce_logsumexp(x, 1) ==> [log(3), log(3)]tf.reduce_logsumexp(x, 1, keep_dims=True) ==> [[log(3)], [log(3)]]tf.reduce_logsumexp(x, [0, 1]) ==> log(6)

Args:

input_tensor: The tensor to reduce. Should have numeric type.
reduction_indices: The dimensions to reduce. If None (the defaut), reduces all dimensions.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:

The reduced tensor.

tf.accumulate_n(inputs, shape=None, tensor_dtype=None, name=None)

Returns the element-wise sum of a list of tensors.

Optionally, pass shape and tensor_dtype for shape and type checking, otherwise, these are inferred.

NOTE: This operation is not differentiable and cannot be used if inputs depend on trainable variables. Please use tf.add_n for such cases.

For example:

# tensor 'a' is [[1, 2], [3, 4]]# tensor `b` is [[5, 0], [0, 6]]tf.accumulate_n([a, b, a]) ==> [[7, 4], [6, 14]]# Explicitly pass shape and typetf.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.int32)  ==> [[7, 4], [6, 14]]

Args:

inputs: A list of Tensor objects, each with same shape and type.
shape: Shape of elements of inputs.
tensor_dtype: The type of inputs.
name: A name for the operation (optional).
Returns:

A Tensor of same shape and type as the elements of inputs.

Raises:

ValueError: If inputs don’t all have same shape and dtype or the shape cannot be inferred.
tf.einsum(axes, *inputs)

A generalized contraction between tensors of arbitrary dimension.

Like numpy.einsum.

0 0