numpy 矩阵平方和

问题描述 投票:0回答:3

我确实有一个矩阵,其中观察结果为行(不同 pH 值下的测量值),数据点为列(浓度随时间变化)。因此,一行包含一种 pH 值的不同数据点。

我确实想对数据进行常微分方程拟合。所以我定义了一个成本函数,并想计算所有观测值的平方和。对该矩阵求平方和应该像这样:

res = y - yhat                        # calculate residuals
ssq = np.diag(np.dot(res.T,res))      # sum over the diagonal

正确吗?

python numpy
3个回答
46
投票

如果你取最后一个数组的总和,那就是正确的。 但它也不必要地复杂(因为非对角线元素也是用 np.dot 计算的) 更快的是:

ssq = np.sum(res**2)

如果您想要每个实验都使用 SSD,您可以执行以下操作:

ssq = np.sum(res**2, axis=1)

4
投票

性能比较后续,我发现最快的方法就是直接算数:

res[:, 0]**2 + res[:, 1]**2 + res[:, 2]**2

enter image description here

import numpy as np
import perfplot

perfplot.live(
    setup=lambda n: np.random.randn(n, 3),
    kernels=[
        lambda a: a[:, 0]**2 + a[:, 1]**2 + a[:, 2]**2,
        lambda a: np.sum(a**2, axis=1),
        lambda a: np.sum(np.square(a), axis=1),
    ],
    labels=["a[:, 0]**2 + a[:, 1]**2 + a[:, 2]**2",
            "np.sum(a**2, axis=1)",
            "np.sum(np.square(a), axis=1)"],
    n_range=[2 ** k for k in range(25)],
    xlabel="len(a)",
)

大声喊出https://github.com/nschloe/perfplot


0
投票

我来晚了一点,但这被称为矩阵的 Frobenius 范数,这正是 np.linalg.norm(res) 使用其默认参数所做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.