欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 人工智能 > pytorch >内容正文

pytorch

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

发布时间:2025/4/16 pytorch 93 豆豆
生活随笔 收集整理的这篇文章主要介绍了 深度学习中张量flatten处理(flatten,reshape,reduce) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

先看一下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])

总结

以上是生活随笔为你收集整理的深度学习中张量flatten处理(flatten,reshape,reduce)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。