线性方程的 Numpy 语法

Numpy syntax for linear equation

我是 numpy 的新手,但不是 python。对执行此操作的 numpy 方法有疑问,请考虑:

编辑 : 更正函数**

def _my_function(weights, features, bias):
    # the pure python way
    value = 0.
    for i in range(len(weights)):
         value += (weights[i]*features[i])

    return value+bias

执行此操作的 numpy 方法是什么?

方法 #1: 使用 dot-productnp.dot -

weights.dot(features) + bias*len(weights)

方法 #2: 引入 np.einsum 来执行 sum-reduction -

np.einsum('i,i->',weights,features) + bias*len(weights)

我认为方法 1 会更好。

如果weigthsfeatures是相同大小的numpy数组,你可以做逐元素乘法:

values = np.sum(weights * features + bias)

如果你想避免给产品数组的每个元素添加偏差,你可以这样做

values = np.sum(weights * features) + bias * weights.size

您甚至可以使用 Python 的内置 sum 函数:

values = sum(weights * features + bias)

values = sum(weights * features) + bias * weights.size

这样做的原因是表达式 weights * featuresweights * features + bias 都是临时的 numpy 数组,它们可以沿着它们的第一个维度迭代,因此可以传递给 sum

时机

我运行在IPython中进行了以下计时测试:

%timeit weights.dot(features)
The slowest run took 145.86 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 649 ns per loop

%timeit np.sum(weights * features)
The slowest run took 17.09 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.83 µs per loop

在产品上使用 ndarray.dot 比使用 np.sum 快五倍。但是,警告表明您第一次 运行 代码时这可能不是真的。 0.649µs * 145.86 = 94.66µs,而 2.83µs * 17.09 = 48.36µs。