假设我有一个矩阵
import numpy as np
from functools import reduce
np.random.seed(123)
X = np.random.normal(size=(5, 2))
并且我想在不使用numpy函数且不使用map
,reduce
和lambda
函数的情况下计算X ^ tX。因为我们可以将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)
为了回答您的问题,外部产品可以定义为嵌套地图,例如
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]])
实际上,使用列表理解更为简单
outer = lambda V: np.array([[x*x1 for a in V] for x1 in V])
将给您相同的结果。然后您可以映射到矩阵,例如
>>> 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]])]
顺便说一下,您的缩小部分非常简洁。我认为这部分不需要任何进一步的重构。
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]]])