python - 在 Numpy 中乘积 block 矩阵

标签 python numpy matrix machine-learning regression

大家好我是python新手 我必须为类作业实现套索 L1 回归。这涉及求解涉及 block 矩阵的二次方程。

minimize x^t * H * x  + f^t * x 
where x > 0

其中 H 是一个 2 X 2 block 矩阵,每个元素都是一个 k 维矩阵,x 和 f 是一个 2 X 1 向量,每个元素都是一个 k 维向量。

我在考虑使用 ndarrays。

这样:

  np.shape(H) = (2, 2, k, k)
  np.shape(x) = (2, k)

但我发现 np.dot(X, H) 在这里不起作用。 有解决这个问题的简单方法吗?提前致谢。

最佳答案

首先,我相信转换为矩阵会带来更高效的计算。说明,如果你认为你的 2k x 2k 矩阵是一个 2 x 2 矩阵,那么你在向量空间的张量积中操作,并且必须使用 tensordot 而不是 dot

试一试,以 k=5 为例:

>>> import numpy as np
>>> k = 5

定义我们的矩阵a 和向量x

>>> a = np.arange(1.*2*2*k*k).reshape(2,2,k,k)
>>> x = np.arange(1.*2*k).reshape(2,k)
>>> x
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.]])

现在我们可以乘以我们的张量了。一定要选择正确的坐标轴,我没有明确测试下面的公式,可能会出错

>>> result = np.tensordot(a,x,([1,3],[0,1]))
>>> result
array([[  985.,  1210.,  1435.,  1660.,  1885.],
       [ 3235.,  3460.,  3685.,  3910.,  4135.]])
>>> np.shape(result)
(2, 5)

关于python - 在 Numpy 中乘积 block 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19740490/

相关文章:

c++ - 如何定义自定义比较函数以根据一维数组排序对矩阵进行排序

python - 将函数/计算应用于 pandas 中的多列

python - 如何对 pandas DataFrame 中的内部列表进行排序?

python - bs4.FeatureNotFound : Couldn't find a tree builder with the features you requested: html5lib

python - f2py 不喜欢子程序中的显式数组

Python openCV 2.4.3 cv2.SolvePnP 错误

c++ - Eigen c++ 中的乘法矩阵给出了错误的维度

python - Python 中的时间戳服务器 rfc3161 响应 token 生成

Python:二进制二维数组中的轮廓

c++ - 使用 Eigen 就地进行 LDLT 分解