线性方程的numpy语法
作者:互联网
我是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
什么是麻木的方式做到这一点?
解决方法:
如果weigth和特征是相同大小的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 * features和weights * featuresbias都是临时numpy数组,它们可以沿其第一维进行迭代,因此可以传递给求和.
定时
我在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.
标签:linear-regression,python,numpy 来源: https://codeday.me/bug/20191026/1937433.html