簡體   English   中英

Python:使用 map 寫外積並減少

[英]Python: write outer product using map and reduce

假設我有一個矩陣

import numpy as np
from functools import reduce
np.random.seed(123)
X = np.random.normal(size=(5, 2))

我想計算 X^t X 而不使用 numpy 函數並使用mapreducelambda函數。 由於我們可以將 X^t X 寫為外積之和,因此我的目標是:

def outer_product(x):
    """Computes outer product of a vector with itself"""
    pass

map(outer_product, X)

但是,我似乎找不到一種有效的方法來使用 map reduce 來編寫所有這些內容。

我的嘗試

def outer(x):
    xxx = np.repeat(x, len(x))
    yyy = np.array(list(x) * len(x))
    return np.reshape(list(map(lambda x, y: x*y, xxx, yyy)), (len(x), len(x)))

以便

outer(X[0, ])

然后我寫了協方差矩陣如下

def cov(X):
    return np.array(reduce(lambda x, y: x + y, list(map(outer, X)))) / np.size(X, 0)

要回答您的問題,外部產品可以定義為嵌套 map,例如

outer = lambda V: np.array(list(map(lambda x: list(map(lambda y: x*y, V)), V)))

X = np.random.normal(size=(5, 2))
>>> outer(X[1])
array([[ 0.08007683, -0.42624902], [-0.42624902,  2.26892377]])

其實用list comprehension更簡單

outer = lambda V: np.array([[x*x1 for a in V] for x1 in V])

會給你同樣的結果。 然后你可以 map 到你的矩陣

>>> list(map(outer, X))
[array([[ 1.17859381, -1.08274874],
       [-1.08274874,  0.99469794]]), array([[ 0.08007683, -0.42624902],
       [-0.42624902,  2.26892377]]), array([[ 0.33477825, -0.9555216 ],
       [-0.9555216 ,  2.72724264]]), array([[5.88877215, 1.04083337],
       [1.04083337, 0.18396604]]), array([[ 1.60259461, -1.0972381 ],
       [-1.0972381 ,  0.75123892]])]

順便說一句,您的 reduce 部分非常簡潔明了。 我認為該部分不需要任何進一步的重構。

In [40]: X = np.arange(10).reshape(5,2)   

使用接受的答案中的outer和列表/地圖:

In [41]: outer = lambda V: np.array([[x*x1 for x in V] for x1 in V])                     
In [43]: list(map(outer, X))                                                             
Out[43]: 
[array([[0, 0],
        [0, 1]]),
 array([[4, 6],
        [6, 9]]),
 array([[16, 20],
        [20, 25]]),
 array([[36, 42],
        [42, 49]]),
 array([[64, 72],
        [72, 81]])]

使用numpy廣播:

In [44]: X[:,:,None]*X[:,None,:]                                                         
Out[44]: 
array([[[ 0,  0],
        [ 0,  1]],

       [[ 4,  6],
        [ 6,  9]],

       [[16, 20],
        [20, 25]],

       [[36, 42],
        [42, 49]],

       [[64, 72],
        [72, 81]]])

對於 (5,2) X ,結果是 (5,2,2) 數組。

一些小的時間測試:

In [55]: timeit list(map(outer, X))                                                      
51.8 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [57]: timeit [outer(i) for i in X]                                                    
49.8 µs ± 65.9 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [58]: timeit X[:,:,None]*X[:,None,:]                                                  
5.37 µs ± 11.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

list/map與列表理解的速度大致相同。 一般來說,我發現列表理解更清晰。 但是廣播 numpy 操作通常要快得多。

如果您要迭代,請考慮使用列表; 它通常更快:

In [61]: timeit [outer(i) for i in X.tolist()]                                           
24.3 µs ± 63.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [62]: outer0 = lambda V: [[x*x1 for x in V] for x1 in V] 
In [64]: timeit [outer0(i) for i in X.tolist()]                                          
7.33 µs ± 16 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM