Skip to the content.

numpy.tile 示例


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


在复制矩阵的时候,numpy.tile是个很有用的函数, 类似的有个numpy.repeat,可参考文档。

>>> import numpy as np
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> a.shape
(2, 3)
>>> np.tile(a, 2).shape
(2, 6)
# 可以看作是
# (2, 3)
# *   2
# (2, 6)

>>> # 如果对多维操作,那么第二个参数需要使用列表[]或者是元组(),效果一样
>>> np.tile(a, (2, 4))
array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6],
       [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]])
>>> np.tile(a, (2, 4)).shape
(4, 12)
# 可以看作是
# (2, 3)
# *2, 4
# (4, 12)

# 这个函数还可以提升维度
>>> np.tile(a, (2, 4, 2))
array([[[1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6],
        [1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6],
        [1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6],
        [1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6]],

       [[1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6],
        [1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6],
        [1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6],
        [1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6]]])
>>> np.tile(a, (2, 4, 2)).shape
(2, 8, 6)
# 同样的,多出来的维度默认补1
# 1, (2, 3)
# *2, 4, 2
# (2, 8, 6)