【问题标题】:Vectorization of a function dependent on 2 arrays in numpy依赖于 numpy 中 2 个数组的函数的矢量化
【发布时间】:2018-10-06 13:32:59
【问题描述】:

我正在尝试对包含循环的函数进行矢量化。

原来的函数是:

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

如何向量化函数?

【问题讨论】:

  • 你能发布X,Y,m,c的最小例子吗?
  • X 和 Y 是 numpy 数组,例如 X = np.array([x for x in range(20)])。 m 和 c 是线性方程 m*x+c 的系数

标签: python python-3.x numpy machine-learning vectorization


【解决方案1】:

这是一种方法,假设 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)

【讨论】:

    【解决方案2】:

    为了补充@jpp 的答案(假设XY 都具有(20, ...) 的形状),这是您的error 函数的完全等价物:

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

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2018-08-08
      • 2017-01-20
      • 2016-07-15
      • 1970-01-01
      相关资源
      最近更新 更多