【问题标题】:Is there a more efficient method to iterate over a matrix and perform calculations on specific columns?是否有更有效的方法来迭代矩阵并在特定列上执行计算?
【发布时间】:2019-09-16 02:24:10
【问题描述】:

我有一个有 2 列的矩阵(矩阵“X”有两个特征 - 特征 0 和特征 1)和可变行数。对于每个样本(矩阵中的行),我想计算一个扩展行,使得每一行都是 [feature0, feature1, feature0^2, feature1^2, feature0*feature1, 1]。

我已经写了下面的函数来完成这项工作。

def expand(X):

    X_expanded = np.zeros((X.shape[0], 6))

    for i in range(X_expanded.shape[0]):
        for j in range(X_expanded.shape[1]):

            if j <= 1:
                X_expanded[i, j] = X[i, j]
            elif j == 2:
                X_expanded[i, j] = X[i, 0]*X[i, 0]
            elif j == 3:
                X_expanded[i, j] = X[i, 1]*X[i, 1]
            elif j == 4:
                X_expanded[i, j] = X[i, 0]*X[i, 1]            
            elif j == 5:
                X_expanded[i, j] = 1



    return X_expanded

我的问题是,是否有更有效或“更好的方法”来执行此计算?对我来说似乎很麻烦,所以欢迎任何建议。提前致谢。

【问题讨论】:

    标签: python loops if-statement iteration matrix-multiplication


    【解决方案1】:

    尝试制作一个简单的函数并将它们堆叠起来:

    import numpy as np
    
    def expanded(arr_2d):
        c1, c2 = arr.T
        return np.hstack([arr_2d, np.vstack([c1 ** 2, c2 ** 2, c1 * c2, np.ones(c1.shape[0])]).T])
    

    大约快 145 倍:

    arr = np.random.randint(0, 100, (10000, 2))
    
    %timeit expand(arr)
    
    # 41 ms ± 3.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    %timeit expanded(arr)
    
    # 282 µs ± 10.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    验证检查:

    np.all(expand(arr) == expanded(arr))
    # True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多