我正在尝试将一个包含循环的函数进行向量化处理。
原始函数如下:
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(X, Y, m, c): errorVector = np.array([(y-(m*x+c))**2 for (x,y) in (X,Y)]) total = errorVector.sum() return total
如何对这个函数进行向量化处理呢?
回答:
为了补充@jpp的回答(假设X
和Y
的形状都是(20, ...)
),这里是你的error
函数的精确等价物:
def error(X, Y, m, c): return np.sum((Y[:20] - (m * X[:20] + c)) ** 2)