【问题标题】:How to transpose 3D array to make n feature vectors?如何转置 3D 数组以制作 n 个特征向量?
【发布时间】:2020-12-06 18:51:48
【问题描述】:

如果我有一个包含三个不同特征数组的数组(用伪代码编写但使用 numpy:

height = [6.2,5.8,5.9,5.5]
weight = [50,100,125,40]
age = [18,25,45,73]
ftrs = [height,weight,age]

我想创建 n 个特征向量,我将如何重塑和转置数组?因此,例如,第一个特征向量将包含:

[height[0],weight[0],age[0]]

谢谢!

【问题讨论】:

  • list(zip(height,weight,age))

标签: python numpy


【解决方案1】:

你可以使用numpy.c_[height,weight,age]

希望能回答您的问题。 该功能使用低级实现,应该快速安静。 这是文档https://numpy.org/doc/stable/reference/generated/numpy.c_.html

【讨论】:

    【解决方案2】:
    In [378]: height = [6.2,5.8,5.9,5.5]
         ...: weight = [50,100,125,40]
         ...: age = [18,25,45,73]
         ...: ftrs = [height,weight,age]
    In [379]: ftrs
    Out[379]: [[6.2, 5.8, 5.9, 5.5], [50, 100, 125, 40], [18, 25, 45, 73]]
    

    我们可以简单地从列表列表中创建一个数组:

    In [380]: arr = np.array(ftrs)
    In [381]: arr
    Out[381]: 
    array([[  6.2,   5.8,   5.9,   5.5],
           [ 50. , 100. , 125. ,  40. ],
           [ 18. ,  25. ,  45. ,  73. ]])
    In [382]: arr[:,0]
    Out[382]: array([ 6.2, 50. , 18. ])
    

    数组的列是您的“特征向量”,可以通过 numpy 数组索引轻松访问。

    或者你可以转置数组,使特征行:

    In [383]: arrt = arr.transpose()
    In [384]: arrt
    Out[384]: 
    array([[  6.2,  50. ,  18. ],
           [  5.8, 100. ,  25. ],
           [  5.9, 125. ,  45. ],
           [  5.5,  40. ,  73. ]])
    In [385]: arrt[0]
    Out[385]: array([ 6.2, 50. , 18. ])
    

    等效地,您可以列堆叠列表(np.c_ 这样做):

    In [386]: np.stack(ftrs, axis=1)
    Out[386]: 
    array([[  6.2,  50. ,  18. ],
           [  5.8, 100. ,  25. ],
           [  5.9, 125. ,  45. ],
           [  5.5,  40. ,  73. ]])
    

    评论中提到的list(zip 是众所周知的“转置”列表列表的方式。如果您不需要 numpy,这是一个很好的了解工具。

    在 [387] 中:列表(zip(*ftrs)) 输出[387]:[(6.2, 50, 18), (5.8, 100, 25), (5.9, 125, 45), (5.5, 40, 73)]

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2013-05-04
      • 1970-01-01
      • 2017-10-18
      • 2020-09-19
      • 1970-01-01
      • 2017-05-08
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多