Construct 3 dimensions array from two dimensions array using tile

空扰寡人 提交于 2021-01-29 03:15:47

问题


I have an array arr = np.array([0.0, 0.0, 1.0])

I want to contract array of following shape promo_class.shape which is (2,3,3)

I want to create repeated array of shape (2,3,3)

array([[[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]],
       [[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]]])

Any idea how to do that with np.tile function ?


回答1:


Simply use np.broadcast_to for a view -

In [142]: arr = np.array([0.0, 0.0, 1.0])

In [144]: np.broadcast_to(arr,(2,3,3))
Out[144]: 
array([[[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]],

       [[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]]])

Why should we use view?

Because being a view, it has no extra memory overhead and hence virtually free on runtime -

In [148]: arr = np.random.rand(300)

In [149]: %timeit np.broadcast_to(arr,(200,300,300))
100000 loops, best of 3: 3.13 µs per loop

If you need an output with its own memory space, append with .copy().


If you are devoted to np.tile -

In [174]: np.tile(arr,(2,3,1))
Out[174]: 
array([[[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]],

       [[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]]])


来源:https://stackoverflow.com/questions/55607273/construct-3-dimensions-array-from-two-dimensions-array-using-tile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!