在Python / numpy的线性组合 [英] linear combinations in python/numpy

查看:553
本文介绍了在Python / numpy的线性组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候,

我不知道,如果这是一个愚蠢的问题或没有。

I'm not sure if this is a dumb question or not.

可以说我有3 numpy的阵列,A1,A2,A3和3辆彩车,C1,C2,C3

Lets say I have 3 numpy arrays, A1,A2,A3, and 3 floats, c1,c2,c3

和我想探讨B = A1 * C1 + A2 * C2 + A3 * C3

and I'd like to evaluate B = A1*c1+ A2*c2+ A3*c3

将numpy的计算以此为例子,

will numpy compute this as for example,

 E1 = A1*c1
 E2 = A2*c2
 E3 = A3*c3
 D1 = E1+E2
 B = D1+E3

还是比这更聪明吗?在C ++中我做了一个巧妙的方法来抽象这种操作。

or is it more clever than that? In c++ I had a neat way to abstract this kind of operation.

我定义一系列模板函数,LC的一般LC对于像线性组合:

I defined series of general 'LC' template functions, LC for linear combination like:

template<class T,class D>
void LC( T & R,
    T & L0,D C0,
    T & L1,D C1,
    T & L2,D C2)
{
    R = L0*C0
        +L1*C1
        +L2*C2;        
}

,然后这个专业的各类

and then specialized this for various types,

因此​​,举例来说,对于一个数组code看起来像

so for instance, for an array the code looked like

for (int i=0; i<L0.length; i++)
    R.array[i] =
    L0.array[i]*C0 +
    L1.array[i]*C1 +
    L2.array[i]*C2;

从而避免不必创建新的中间阵列。

thus avoiding having to create new intermediate arrays.

这可能看起来混乱,但它的工作真的很好。

This may look messy but it worked really well.

我可以做在python类似的东西,但我不知道它nescesary。

I could do something similar in python, but I'm not sure if its nescesary.

先谢谢您的任何见解。
-nick

Thanks in advance for any insight. -nick

推荐答案

numpy的,理论上可以在任何时候随时升级它的内部执行奇妙的优化,在在present时候它不会: B = A1 * C1 + A2 * C2 + A3 * C3 确实会产生,然后丢弃中间临时阵列(消费一些辅助存储器,当然 - 没有别的)。

While numpy, in theory, could at any time always upgrade its internals to perform wondrous optimizations, at the present time it does not: B = A1*c1 + A2*c2 + A3*c3 will indeed produce and then discard intermediate temporary arrays ("spending" some auxiliary memory, of course -- nothing else).

B = A1 * C1 然后按 B + = A2 * C2; B + = A3 * C3 ,此时再次 的,因此将避免花费一些临时内存的。

B = A1 * c1 followed by B += A2 * c2; B += A3 * c3, again at this time, will therefore avoid spending some of that temporary memory.

当然,你可以告诉只是,如果你在稀缺的实际内存(其中一些辅助记忆的仅仅是虚拟的,并导致页面错误)和足够大的阵列的环境中操作的区别花的所有实际内存,然后一些。在这种极端条件下,但是,有一点重构的可以的你买一些性能。

Of course, you'll be able to tell the difference only if you're operating in an environment with scarce real memory (where some of that auxiliary memory is just virtual and leads to page faults) and for sufficiently large arrays to "spend" all real memory and then some. Under such extreme conditions, however, a little refactoring can buy you some performance.

这篇关于在Python / numpy的线性组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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