@hanxiaoyang 2016-11-14T02:20:22.000000Z 字数 850 阅读 2919

# for循环 vs 矢量化方式

机器学习

By @寒小阳

## 例子1

# 非矢量化运算def sum_products(x, y):    """    >>> sum_products(np.arange(3000), np.arange(3000))    20236502250000    """    result = 0    for i in range(len(x)):        for j in range(len(y)):            result += x[i] * y[j]    return result
#矢量化运算np.sum(x) * np.sum(y)

## 例子2

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

## 例子3

def clean_up(x, missing=-1, value=0):    """    >>> clean_up(np.arange(-3, 3), value=10)    ... # doctest: +NORMALIZE_WHITESPACE    array([-3, -2, 10, 0, 1, 2])    """    result = []    for i in range(len(x)):        if x[i] == missing:            result.append(value)        else:            result.append(x[i])    return np.array(result)
#矢量化运算np.where(x == missing, value, x)

• 私有
• 公开
• 删除