机器学习&全栈我爱编程

TensorFlow shape相关操作

2018-05-15  本文已影响6人  采香行处蹙连钱
参考文献:
  1. 基本形状操作函数:https://blog.csdn.net/xierhacker/article/details/53462072
基本形状操作函数
  1. tf.shape(input, name=None, out_type=tf.int32)

    作用: 返回一个1维tensor表示input的形状

    参数: input: 输入的tensor

    name: 可选,这个操作的名字

    out_type: (可选)输出的类型(int32 or int64), 默认tf.int32

    x_shape = tf.shape(x)
    y_shape = tf.shape(y)
    z_shape = tf.shape(z)
    sess = tf.Session()
    print(sess.run(x_shape))
    print(sess.run(y_shape))
    
    操作该函数时,不能使用tf.run(),因为返回的是tuple,否则返回的是string
    
  2. 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
    
  3. 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
    
  4. tf.reshape(tensor, shape, name=None)

    作用:改变一个tensor的形状,按照指定的shape返回一个tensor。

    参数: tensor: tensor,待被改变形状的tensor

    shape: tensor,必须是 int32, int64.决定了输出tensor的形状

    # 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]]
    
操作同时降维
  1. 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

    # 'x' is [[1, 1, 1]
    #         [1, 1, 1]]
    tf.reduce_sum(x) ==> 6
    tf.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
    
  2. tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)

    计算tensor上面某个维度的平均值。其他参数同1

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

上一篇下一篇

猜你喜欢

热点阅读