简体   繁体   English

在numpy中依赖于2个数组的函数的向量化

[英]Vectorization of a function dependent on 2 arrays in numpy

I'm trying to vectorize a function that consist of a loop. 我正在尝试对包含循环的函数进行向量化。

The original function is: 原来的功能是:

def error(X, Y, m, c):
    total = 0
    for i in range(20):
        total += (Y[i]-(m*X[i]+c))**2
    return total 

I've tried the following but It doesn't work: 我尝试了以下但它不起作用:

def error(X, Y, m, c):
    errorVector = np.array([(y-(m*x+c))**2 for (x,y) in (X,Y)])
    total = errorVector.sum()
    return total

How can I vectorize the function? 如何对函数进行矢量化?

This is one way, assuming X and Y have first dimension of length 20. 这是一种方式,假设XY具有长度为20的第一维。

def error(X, Y, m, c):
    total = 0
    for i in range(20):
        total += (Y[i]-(m*X[i]+c))**2
    return total 

def error_vec(X, Y, m, c):
    return np.sum((Y - (m*X + c))**2)

m, c = 3, 4
X = np.arange(20)
Y = np.arange(20)

assert error(X, Y, m, c) == error_vec(X, Y, m, c)

To complement @jpp's answer (which assumes that X and Y both have the shape (20, ...) ), here's an exact equivalent of your error function: 为了补充@jpp的答案(假设XY都具有形状(20, ...) ),这里的error函数完全相同:

def error(X, Y, m, c):
  return np.sum((Y[:20] - (m * X[:20] + c)) ** 2)

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

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