简体   繁体   English

将两个nparray相乘python

[英]multiplying two nparray together python

What is an efficient way to multliply two numpy arrays together? 将两个Numpy数组相互融合的有效方法是什么? For example, given 例如,给定

A = [1, 2, 3, 4]
B = [2, 3, 5, 7]

I want to calculate the dot product between A and B, which is 我想计算A和B之间的点积,即

  A.B/|A||B| = (1*2 + 2*3 + .. 4*7)/sqrt(1^2 + 2^2... +4^2) * sqrt(.....)

How can I do this efficiently and fast? 我如何高效快捷地做到这一点?

If you are using numpy, numpy.dot would do the Job for you 如果您使用的是numpy, numpy.dot将为您完成工作

numpy.dot(A,B)
51

The Fastest norm for a vector would be 向量的最快范数是

n = math.sqrt(numpy.dot(A,A.conj()))

and here is the comparison with other methods 这是与其他方法的比较

>>> t1=timeit.Timer("n = math.sqrt(numpy.dot(A,A.conj()))","from __main__ import A,math,numpy")
>>> t2=timeit.Timer("n = math.sqrt(sum(abs(A)**2))","from __main__ import A,math")
>>> t3=timeit.Timer("numpy.linalg.norm(A)","from __main__ import A,numpy")
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
2.82 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
13.16 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t3.timeit(number=100000)/100000)
15.68 usec/pass
>>> 

In addition to numpy.dot , there is numpy.linalg.norm which does what you are looking for: 除了numpy.dot ,还有numpy.linalg.norm您的需求:

from numpy.linalg import norm    
from numpy import dot

dot(a,b)/(norm(a)*norm(b))

I'm guessing that you want the sqrt of the sum of the squares, which is the default for norm . 我猜想您想要平方和的平方根,这是norm的默认值。 This metric is called the Frobenius norm or L2 norm. 此度量标准称为Frobenius规范或L2规范。 If you want a different metric, say the Manhattan or L1 norm, it is simply a parameter to pass in. 如果要使用其他度量标准(例如, 曼哈顿标准或L1范数),则只需传入一个参数即可。

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

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