简体   繁体   English

用向量的倍数创建numpy矩阵的最快方法

[英]Fastest way to create a numpy matrix with multiples of a vector

Let x,y be two numpy arrays of N elements. 令x,y为N个元素的两个numpy数组。 I want to create a numpy matrix whose columns are scaled-shifted versions of x. 我想创建一个numpy矩阵,其列是x的缩放移位版本。 For instance, say 例如说

m=[0.2, 0.4, 1.2]

Then I want the matrix 然后我想要矩阵

X = [0.2x+y, 0.4x+y, 1.2x+y]

What's the fastest (easiest as well, easiest being second priority) way to do this. 什么是最快(同时也是最容易的,最容易成为第二优先级)的方式。

Currently I am doing something like this. 目前,我正在做这样的事情。

ListVec = [m[i]*x+y for i in numpy.arange(len(m))]
X = numpy.array(ListVec).T
import numpy as np 
m = np.array([0.2, 0.4, 1.2])
x = 5
y = 3
X = m*x+y

This is called broadcasting in numpy (both easy and fast ;)) 这被称为numpy 广播 (既简便又快速;)

use Einstein Summation for case when X and Y are arrays 当X和Y是数组时使用爱因斯坦求和

In [70]: Y
Out[76]: array([5, 6, 7, 8, 9])

In [71]: X
Out[71]: array([0, 1, 2, 3, 4])

In [72]: m
Out[72]: [0.2, 0.4, 1.2]

In [73]: np.einsum('i,j', X, m)
Out[73]: 
array([[0. , 0. , 0. ],
       [0.2, 0.4, 1.2],
       [0.4, 0.8, 2.4],
       [0.6, 1.2, 3.6],
       [0.8, 1.6, 4.8]])

In [74]: Y[...,np.newaxis] + np.einsum('i,j', X, m)
Out[74]: 
array([[ 5. ,  5. ,  5. ],
       [ 6.2,  6.4,  7.2],
       [ 7.4,  7.8,  9.4],
       [ 8.6,  9.2, 11.6],
       [ 9.8, 10.6, 13.8]])

It would have helped if you'd given example x and y as well as m , but: 如果您给出示例xy以及m会有所帮助,但是:

In [435]: x,y = np.array([1,2,3,4]), np.array([.1,.2,.3,.4])
In [436]: m = [.2,.4,1.2]

So the result is (3,N): 因此结果是(3,N):

In [437]: np.array([i*x+y for i in m])
Out[437]: 
array([[0.3, 0.6, 0.9, 1.2],
       [0.5, 1. , 1.5, 2. ],
       [1.3, 2.6, 3.9, 5.2]])

broadcasting with m : m广播:

In [438]: np.array(m)[:,None]*x + y
Out[438]: 
array([[0.3, 0.6, 0.9, 1.2],
       [0.5, 1. , 1.5, 2. ],
       [1.3, 2.6, 3.9, 5.2]])

oops, I missed your transpose, 哎呀,我想念你的换位

In [440]: np.array(m)*x[:,None] + y[:,None]
Out[440]: 
array([[0.3, 0.5, 1.3],
       [0.6, 1. , 2.6],
       [0.9, 1.5, 3.9],
       [1.2, 2. , 5.2]])

I'd go ahead a apply the transpose to [438] 我会继续将移调应用于[438]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM