目录
前言
transpose这个函数在数据处理、深度学习机器学习等方面都有很大的使用
今天专门研究下这个函数
- transpose函数
主要的功能时将其维度转换
源码中的函数为:
@overload
def transpose(self: _ArraySelf, axes: None | _ShapeLike, /) -> _ArraySelf: ...
@overload
def transpose(self: _ArraySelf, *axes: SupportsIndex) -> _ArraySelf: ...
参数如下:
- 参数为ArraySelf,自身数组
- axes为维度尺度
具体有如下两种定义的方式:
import numpy as np
x = np.arange(15).reshape(3,5)
y = np.transpose(x,(1,0))
print(y)
或者
import numpy as np
x = np.arange(15).reshape(3,5)
y = x.transpose(1,0)
print(y)
不可有这样的代码(因为原本的x改变了没被存储到)
import numpy as np
x = np.arange(15).reshape(3,5)
x.transpose(1,0)
print(x)
如下的参数不可取
- 数据只能限定在维度的尺寸内
不然会出现如下错误:numpy.AxisError: axis 3 is out of bounds for array of dimension 2
截图如下:
- 维度不可重复,毕竟没有同纬度且少一个维度的数据
不然会出现如下错误:ValueError: repeated axis in transpose
截图如下:
-
维度不可少,毕竟不能输出残缺的数组维度
不然会出现如下错误:ValueError: axes don't match array
截图如下: -
实例
通过实例代码可以更深入的了解
二位数组中就是将其x与y(横竖)进行转换
对应代码如下:
import numpy as np
if __name__ == '__main__':
x = np.arange(15).reshape(3,5)
print(x)
y = x.transpose(1,0)
print(y)
截图如下:
如果中间的核心代码修改如下
- 通过
y = x.transpose(0,1)
还是本身 - 通过
y = x.transpose()
等同于y = x.transpose(1,0)
以上都是二维中的变换
如果是三维中进行转换
就是x,y,z轴,将其轴进行交换,维度不变,数组内容变了而已
数学层面的理解通过维度转换如下:
import numpy as np
if __name__ == '__main__':
x = np.arange(16).reshape((2,2,4))
print(x)
输出如下:
B:\test1\Scripts\python.exe B:/pycharm_test_code/test1/test.py
[[[ 0 1 2 3]
[ 4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]]
截图如下:
如果对应的轴进行变化,通过维度输出查看:(对应进行交换)
第一个【】0维
第二个【】1维
第三个【】2维
import numpy as np
if __name__ == '__main__':
x = np.arange(16).reshape((2,2,4))
y = x.transpose((1,0,2))
print(y[0][0][0] , y[0][0][1] ,y[0][0][2] ,y[0][0][3])
print(y[0][1][0], y[0][1][1], y[0][1][2], y[0][1][3])
print(y[1][0][0] , y[1][0][1] ,y[1][0][2] ,y[1][0][3])
print(y[1][1][0], y[1][1][1], y[1][1][2], y[1][1][3])
输出如下:
B:\test1\Scripts\python.exe B:/pycharm_test_code/test1/test.py
0 1 2 3
8 9 10 11
4 5 6 7
12 13 14 15
截图如下:
Original: https://blog.csdn.net/weixin_47872288/article/details/127010872
Author: 码农研究僧
Title: Python关于numpy.transpose函数详细解析附代码
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/762096/
转载文章受原作者版权保护。转载请注明原作者出处!