从行向量创建块矩阵的最佳方法是什么?

时间:2017-10-01 06:11:31

标签: python numpy matrix convolution

我有以下numpy行矩阵。

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="col-md-3">
      <p>An idea that started several years ago, CIMI (Carrera Internacional de la Mujer Iniciativa) is an initiative for and about women. It started as a dream of the founder, Aracely Areas, to help people like her - women with a vision for their future,
        to build confidence and motivation through running, accomplishment and in turn benefiting from the health and exercise.</p>

      <p>With the generous support of our donors, the purpose of CIMI is to foster programs and partnerships with schools and athletic associations to promote health, education, self-esteem and inspiration for women of all ages. Our goal is to sponsor yearly
        special events, providing training and educational programs, supporting health and exercise opportunities for girls and women with an emphasis on running activities and providing related training and equipment. With our younger participants, confidence
        established at an early age can be applied to all aspects of their lives, particularly in schools for bright futures. All this is offered free of any charge to our participants.</p>

      <p>We became an official Non Profit in 2015 an official 501c3 Charity. Establishing a board of directors who meet quarterly to set goals and continue to move this cause forward.</p>
    </div>

    <div class="col-md-6">
      <div class="card mb-5">
        <img class="card-img-top" src="images/washingtonDCrace.jpg" alt="Card image cap">
        <div class="card-body">
          <h4 class="card-title">Mission Statement</h4>
          <p class="card-text">Focusing on women (and their family) of all ages to build confidence, promote health and motivation through accomplishment. We teach basic running skills, strength exercises, and mentoring. Through this community and confidence is built. We
            believe strongly that all people have many different abilities and strengths that when nurtured can create beautiful things.</p>
        </div>
      </div>
    </div>


    <div class="col-md-3">
      <h4>CIMI Core Values</h4>
      <div class="card mb-5">
        <ul class="list-group list-group-flush">
          <li class="list-group-item">Inclusion</li>
          <li class="list-group-item">Integrity</li>
          <li class="list-group-item">Determination</li>
          <li class="list-group-item">Patience</li>
        </ul>
      </div>
    </div>
  </div>

我想创建一个块矩阵,如下所示:

X = np.array([1,2,3])

我怎么能用numpy做到这一点?

3 个答案:

答案 0 :(得分:2)

如果您从上到下读取所需的输出矩阵,那么左右,您会看到模式1,2,3,0,0,0,1,2,3,0,0,0,1,2 ,3。您可以使用该模式轻松创建线性数组,然后将其重新整形为二维形式:

import numpy as np
X = np.array([1,2,3])
N = len(X)
zeros = np.zeros_like(X)
m = np.hstack((np.tile(np.hstack((X,zeros)),N-1),X)).reshape(N,-1).T
print m

给出

[[1 0 0]
 [2 1 0]
 [3 2 1]
 [0 3 2]
 [0 0 3]]

答案 1 :(得分:1)

方法#1:使用np.lib.stride_tricks.as_strided -

from numpy.lib.stride_tricks import as_strided as strided

def zeropad_arr_v1(X):
    n = len(X)
    z = np.zeros(len(X)-1,dtype=X.dtype)
    X_ext = np.concatenate(( z, X, z))

    s = X_ext.strides[0]
    return strided(X_ext[n-1:], (2*n-1,n), (s,-s), writeable=False)

请注意,这会创建read-only输出。如果您稍后需要写信,只需在最后添加.copy()即可制作副本。

方法#2:使用与零连接,然后剪切/切片 -

def zeropad_arr_v2(X):
    n = len(X)
    X_ext = np.concatenate((X, np.zeros(n,dtype=X.dtype)))
    return np.tile(X_ext, n)[:-n].reshape(-1,n,order='F')

作为基于步幅的方法的方法#1应该在性能上非常有效。

样品运行 -

In [559]: X = np.array([1,2,3])

In [560]: zeropad_arr_v1(X)
Out[560]: 
array([[1, 0, 0],
       [2, 1, 0],
       [3, 2, 1],
       [0, 3, 2],
       [0, 0, 3]])

In [561]: zeropad_arr_v2(X)
Out[561]: 
array([[1, 0, 0],
       [2, 1, 0],
       [3, 2, 1],
       [0, 3, 2],
       [0, 0, 3]])

运行时测试

In [611]: X = np.random.randint(0,9,(1000))

# Approach #1 (read-only)
In [612]: %timeit zeropad_arr_v1(X)
100000 loops, best of 3: 8.74 µs per loop

# Approach #1 (writable)
In [613]: %timeit zeropad_arr_v1(X).copy()
1000 loops, best of 3: 1.05 ms per loop

# Approach #2
In [614]: %timeit zeropad_arr_v2(X)
1000 loops, best of 3: 705 µs per loop

# @user8153's solution
In [615]: %timeit hstack_app(X)
100 loops, best of 3: 2.26 ms per loop

答案 2 :(得分:1)

另一个可写的解决方案:

def block(X):
   n=X.size
   zeros=np.zeros((2*n-1,n),X.dtype)
   zeros[::2]=X
   return zeros.reshape(n,-1).T

尝试:

In [2]: %timeit block(X)
600 µs ± 33 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
相关问题