python 矩阵的拼接操作

版权声明:聂CC~ https://blog.csdn.net/ncc1995/article/details/88073441

 怎么将矩阵拼接在一起,有很多种方法,但是记得又不系统,在这里先简单记录一下几个方法。

1、将相同shape的矩阵放在列表中,然后将列表转化为矩阵。

该方法适合对图片进行操作,在对图片进行预处理的时候,分别对每张图片进行操作,再将处理后的图片append到一个列表中,把列表转化为矩阵,结果就是很多图片组成的矩阵了。

示例代码如下:

a
Out[29]: 
array([[9, 1, 5],
       [5, 6, 5]])
------------------------------------------------
b
Out[30]: 
array([[1, 4, 1],
       [3, 5, 9]])
------------------------------------------------
c = []
c.append(a)
c.append(b)
------------------------------------------------
c
Out[34]: 
[array([[9, 1, 5],
        [5, 6, 5]]), array([[1, 4, 1],
        [3, 5, 9]])]
------------------------------------------------
d = np.array(c)
------------------------------------------------
d
Out[36]: 
array([[[9, 1, 5],
        [5, 6, 5]],
       [[1, 4, 1],
        [3, 5, 9]]])
------------------------------------------------
a.shape
Out[37]: (2, 3)
------------------------------------------------
b.shape
Out[38]: (2, 3)
------------------------------------------------
d.shape
Out[39]: (2, 2, 3)

2、np.concatenate的使用

将append完相同shape矩阵的列表进行np.concatenate操作,相当于把矩阵按行进行拼接。比如在cifar-10中,将5个训练数据拼接。

示例代码如下:

import numpy as np
a = np.random.randint(1, 10, (2, 3))
b = np.random.randint(1, 10, (2, 3))
-------------------------------------------------------
a
Out[5]: 
array([[6, 9, 1],
       [2, 8, 1]])
-------------------------------------------------------
b
Out[6]: 
array([[4, 3, 9],
       [4, 5, 2]])
-------------------------------------------------------
c = []
c.append(a)
c.append(b)
-------------------------------------------------------
d = np.concatenate(c)
-------------------------------------------------------
d.shape
Out[11]: (4, 3)

猜你喜欢

转载自blog.csdn.net/ncc1995/article/details/88073441