[关闭]
@hanxiaoyang 2016-11-14T02:20:22.000000Z 字数 850 阅读 2896

for循环 vs 矢量化方式

机器学习


By @寒小阳

我们来看几个简单的例子,for循环和numpy矢量化运算的对比。

例子1

对于x向量的每个x[i]和y向量的每个y[j],计算x[i] * y[j],并求和

  1. # 非矢量化运算
  2. def sum_products(x, y):
  3. """
  4. >>> sum_products(np.arange(3000), np.arange(3000))
  5. 20236502250000
  6. """
  7. result = 0
  8. for i in range(len(x)):
  9. for j in range(len(y)):
  10. result += x[i] * y[j]
  11. return result
  1. #矢量化运算
  2. np.sum(x) * np.sum(y)

例子2

返回所有满足x[i] < y[j]的个数

  1. # 非矢量化运算
  2. def count_lower(x, y):
  3. """
  4. >>> count_lower(np.arange(0, 200, 2), np.arange(40, 140))
  5. 4500
  6. """
  7. result = 0
  8. for i in range(len(x)):
  9. for j in range(len(y)):
  10. if x[i] < y[j]:
  11. result += 1
  12. return result
  1. #矢量化运算
  2. np.sum(np.searchsorted(np.sort(x), y))

例子3

如果一个数组里有x[i] == missing,用value做替代,最后返回这个数组.

  1. def clean_up(x, missing=-1, value=0):
  2. """
  3. >>> clean_up(np.arange(-3, 3), value=10)
  4. ... # doctest: +NORMALIZE_WHITESPACE
  5. array([-3, -2, 10, 0, 1, 2])
  6. """
  7. result = []
  8. for i in range(len(x)):
  9. if x[i] == missing:
  10. result.append(value)
  11. else:
  12. result.append(x[i])
  13. return np.array(result)
  1. #矢量化运算
  2. np.where(x == missing, value, x)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注