Python 矩阵的 numpy 平方和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24806854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
numpy sum of squares for matrix
提问by Moritz
I do have a matrix with observations in rows (measurements at differnt pH) with data points as columns (concentration over time). So one row consists of differnt data points for one pH.
我确实有一个矩阵,在行中观察(在不同 pH 下的测量),数据点作为列(随时间变化的浓度)。因此,一行由一个 pH 值的不同数据点组成。
I do want to fit an ODE to the data. So i defined a cost function and would like to calculate the sum of squares for all observatoins. Taking the sum of sqares for this matrix should work like:
我确实想将 ODE 拟合到数据中。所以我定义了一个成本函数,并想计算所有观测的平方和。取这个矩阵的平方和应该像这样:
res = y - yhat # calculate residuals
ssq = np.diag(np.dot(res.T,res)) # sum over the diagonal
is that correct ?
那是对的吗 ?
采纳答案by Dave
If you would take the sum of the last array it would be correct. But it's also unnecessarily complex (because the off-diagonal elements are also calculated with np.dot) Faster is:
如果您取最后一个数组的总和,那将是正确的。但它也不必要地复杂(因为非对角线元素也是用 np.dot 计算的) Faster 是:
ssq = np.sum(res**2)
If you want the ssd for each experiment, you can do:
如果你想要每个实验的 ssd,你可以这样做:
ssq = np.sum(res**2, axis=1)