【问题标题】:How to perform Numpy optimisation for this code?如何为此代码执行 Numpy 优化?
【发布时间】:2015-07-12 22:26:25
【问题描述】:

我有以下代码sn-p:

def func1(self, X, y):
    #X.shape = (455,13)
    #y.shape = (455)

    num_examples, num_features = np.shape(X)
    self.weights = np.random.uniform(-1 / (2 * num_examples), 1 / (2 * num_examples), num_features)

    while condition:
        new_weights = np.zeros(num_features)
        K = (np.dot(X, self.weights) - y)

        for j in range(num_features):
            summ = 0

            for i in range(num_examples):
                summ += K[i] * X[i][j]

            new_weights[j] = self.weights[j] - ((self.alpha / num_examples) * summ)

        self.weights = new_weights

此代码运行速度太慢。有什么优化,我可以做吗?

【问题讨论】:

  • 什么是condition
  • @unutbu, count of iteration > 0.
  • while-loop 是无限的吗?
  • @unutbu,没有。我只是从示例中删除 counter
  • 您真的要重置summ=0 内部 for j 循环吗?这样一来,您就丢弃了 for j 循环的每次迭代完成的所有工作,除了 j 等于 num_features-1 的最后一次迭代。

标签: python arrays performance numpy optimization


【解决方案1】:

您可以有效地使用np.einsum()。请参阅下面的测试版本:

def func2(X, y):
    num_examples, num_features = np.shape(X)
    weights = np.random.uniform(-1./(2*num_examples), 1./(2*num_examples), num_features)

    K = (np.dot(X, weights) - y)

    return weights - alpha/num_examples*np.einsum('i,ij->j', K, X)

【讨论】:

    【解决方案2】:

    您可以直接使用matrix-multiplicationnp.dot 来获取new_weights,就像这样-

    new_weights = self.weights- ((self.alpha / num_examples) * np.dot(K[None],X))
    

    【讨论】:

    • 感谢您的帮助!看来您的代码运行正常,但比Saullo Castro 慢一点。
    • @Denis 是的,einsum 似乎是优化解决方案的最佳选择!
    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 2021-12-15
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多