使用自定义架构构建矩阵的最快方法 [英] Fastest way to build a Matrix with a custom architecture

查看:69
本文介绍了使用自定义架构构建矩阵的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在numpy或pandas中以这种形式构建矩阵的最快方法是什么:

What's the fastest way in numpy or pandas to build a matrix that has this form:

1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

既保留了奇数架构又保留了偶数架构?

That preserves both odd and even architectures?

推荐答案

使用 NumPy brodacasting

In [289]: a = np.array([1,2,3,2,1])

In [290]: np.minimum(a[:,None],a)
Out[290]: 
array([[1, 1, 1, 1, 1],
       [1, 2, 2, 2, 1],
       [1, 2, 3, 2, 1],
       [1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1]])

要构建范围数组,我们可以执行以下操作-

To build the range array, we can do something like this -

In [303]: N = 3

In [304]: np.concatenate((np.arange(1,N+1),np.arange(N-1,0,-1)))
Out[304]: array([1, 2, 3, 2, 1])

添加一些偏见

假设我们要向上或向下移动最高数字/峰值.我们需要创建另一个 biasing 数组,并使用与broadcasting相同的策略,就像这样-

Let's say we want to move the highest number/peak up or down. We need to create another biasing array and use the same strategy of broadcasting, like so -

In [394]: a = np.array([1,2,3,2,1])

In [395]: b = np.array([2,3,2,1,0]) # Biasing array

In [396]: np.minimum(b[:,None],a)
Out[396]: 
array([[1, 2, 2, 2, 1],
       [1, 2, 3, 2, 1],
       [1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1],
       [0, 0, 0, 0, 0]])

类似地,要使偏向左或向右移动,请修改a,就像这样-

Similarly, to have the bias shifted left or right, modify a, like so -

In [397]: a = np.array([2,3,2,1,0]) # Biasing array

In [398]: b = np.array([1,2,3,2,1])

In [399]: np.minimum(b[:,None],a)
Out[399]: 
array([[1, 1, 1, 1, 0],
       [2, 2, 2, 1, 0],
       [2, 3, 2, 1, 0],
       [2, 2, 2, 1, 0],
       [1, 1, 1, 1, 0]])

这篇关于使用自定义架构构建矩阵的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆