深度学习中张量flatten处理(flatten,reshape,reduce)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Miss_yan/article/details/83542616

先看一下flatten的具体用法
1-对于一般数值,可以直接flatten

>>> a=array([[1,2],[3,4],[5,6]])
>>> a
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> a.flatten()
array([1, 2, 3, 4, 5, 6])

2-对列表变量,需要做一下处理

>>> a=array([[1,2],[3,4],[5,6]])
>>> [y for x in a for y in x]
[1, 2, 3, 4, 5, 6]

3-对mat对象

>>> a = [[1,3],[2,4],[3,5]]  
>>> a = mat(a)  
>>> y = a.flatten()  
>>> y  
matrix([[1, 3, 2, 4, 3, 5]])  
>>> y = a.flatten().A  
>>> y  
array([[1, 3, 2, 4, 3, 5]])  
>>> shape(y)  
(1, 6)  
>>> shape(y[0])  
(6,)  
>>> y = a.flatten().A[0]  
>>> y  
array([1, 3, 2, 4, 3, 5])  

4-压缩(reduce)


slopes=tf.sqrt(tf.reduce_sum(tf.square(gradients),reduction_indices=[1])

其中reduction_indices=1表示按行压缩,=0表示按列压缩
5-reshape

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

tensor是我们输入的张量,shape是我们希望输入变成什么形状,其中的shape为一个列表形式,特殊的是列表可以实现逆序的遍历,即list(-1).-1所代表的含义是我们不用亲自去指定这一维的大小,函数会自动进行计算,但是列表中只能存在一个-1。如一个6元素的数组,想要reshape成2*3时,下面三种写法得到的结果都是一样的

tf.reshape(a,[2,3])
tf.reshape(a,[2,-1])
tf.reshape(a,[-1,3])

猜你喜欢

转载自blog.csdn.net/Miss_yan/article/details/83542616
今日推荐