在numpy中附加2x2协方差矩阵

时间:2019-01-28 01:45:29

标签: python numpy

我有一个numpy数组,例如:

gmm.sigma =

[[[ 4.64 -1.93]
  [-1.93  6.5 ]]
 [[ 3.65  2.89]
  [ 2.89 -1.26]]]

我想添加另一个2x2矩阵,例如:

gauss.sigma =

[[ -1.24  2.34]
 [  2.34  4.76]]

获得:

gmm.sigma =

[[[ 4.64 -1.93]
  [-1.93  6.5 ]]
 [[ 3.65  2.89]
  [ 2.89 -1.26]]
 [[-1.24  2.34]
  [ 2.34  4.76]]]

我尝试过:gmm.sigma = np.append(gmm.sigma, gauss.sigma, axis = 0), 但出现此错误:

Traceback (most recent call last):
  File "test1.py", line 40, in <module>
    gmm.sigma = np.append(gmm.sigma, gauss.sigma, axis = 0)
  File "/home/rowan/anaconda2/lib/python2.7/site-packages/numpy/lib/function_base.py", line 4528, in append
    return concatenate((arr, values), axis=axis)
ValueError: all the input arrays must have same number of dimensions

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

您可以使用dstack来按顺序沿深度方向(沿第三个轴)堆叠数组,然后进行转置。要获得所需的输出,您将必须堆叠gmm.Tgauss

gmm = np.array([[[4.64, -1.93],
                [-1.93, 6.5 ]],
                [[3.65, 2.89],
                 [2.89, -1.26]]])

gauss = np.array([[ -1.24, 2.34],
                  [2.34, 4.76]])


result = np.dstack((gmm.T, gauss)).T
print (result)
print (result.shape)
# (3, 2, 2)

输出

array([[[ 4.64, -1.93],
    [-1.93,  6.5 ]],

   [[ 3.65,  2.89],
    [ 2.89, -1.26]],

   [[-1.24,  2.34],
    [ 2.34,  4.76]]])

或者,您还可以通过适当地将第二个数组重塑为

来使用串联
gmm = np.array([[[4.64, -1.93],
                [-1.93, 6.5 ]],
                [[3.65, 2.89],
                 [2.89, -1.26]]])

gauss = np.array([[ -1.24, 2.34],
                  [2.34, 4.76]]).reshape(1,2,2)

result = np.concatenate((gmm, gauss), axis=0)

答案 1 :(得分:2)

看起来您想在第一个轴上连接2个数组-除了第二个只有2d。它需要一个附加的维度:

rm path/to/submodule -rf
rm .git/modules/path/to/module -rf

In [233]: arr = np.arange(8).reshape(2,2,2) In [234]: arr1 = np.arange(10,14).reshape(2,2) In [235]: np.concatenate((arr, arr1[None,:,:]), axis=0) Out[235]: array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[10, 11], [12, 13]]]) dstack的变体,将所有内容扩展到3d,并在最后一个轴上连接。要使用它,我们必须转置所有内容:

concatenate

In [236]: np.dstack((arr.T,arr1.T)).T Out[236]: array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[10, 11], [12, 13]]]) 添加了一些类,这些类在尺寸上具有相似的技巧:

index_tricks

如果您想从In [241]: np.r_['0,3', arr, arr1] Out[241]: array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[10, 11], [12, 13]]]) 的文档中获得最大的收获,但是如果您必须调整多个数组的尺寸,则可能值得使用。 np.r_

答案 2 :(得分:1)

如错误消息所述,gmmgauss_sigma的尺寸不相同,您应在附加前重塑gauss_sigma的形状。

gmm_sigma = np.array([[[4.64, -1.93], [-1.93, 6.5]], [[3.65, 2.89], [ 2.89, -1.26]]])
gauss_sigma = np.array([[-1.24, 2.34], [2.34, 4.76]])

print(np.append(gmm_sigma, gauss_sigma.reshape(1, 2, 2), axis=0))
# array([[[ 4.64, -1.93],
#         [-1.93,  6.5 ]],
# 
#        [[ 3.65,  2.89],
#         [ 2.89, -1.26]],
# 
#        [[-1.24,  2.34],
#         [ 2.34,  4.76]]])
相关问题