Ori*_*ber 1 python memory math numpy matrix
作为我正在研究的项目的一部分,我需要计算2m
向量之间的均方误差.
基本上我两个矩阵x
和xhat
,两者都是大小m
通过n
与我感兴趣的载体是这些矢量的行.
我用这段代码计算了MSE
def cost(x, xhat): #mean squared error between x the data and xhat the output of the machine
return (1.0/(2 * m)) * np.trace(np.dot(x-xhat,(x-xhat).T))
Run Code Online (Sandbox Code Playgroud)
它工作正常,这个公式是正确的.
问题是,在我的具体情况下,我m
和n
非常大.特别是m = 60000
和n = 785
.因此,当我运行我的代码并进入此函数时,我收到内存错误.
有没有更好的方法来计算MSE?我宁愿避免循环,而是我倾向于矩阵乘法,但矩阵乘法似乎非常浪费.也许是numpy我不知道的东西?
该表达式np.dot(x-xhat,(x-xhat).T)
创建一个形状为(m,m)的数组.你说m是60000,所以这个数组几乎是29千兆字节.
您可以获取数组的跟踪,这只是对角线元素的总和,因此大部分巨大的数组都未使用.如果仔细观察np.trace(np.dot(x-xhat,(x-xhat).T))
,你会发现它只是所有元素的平方和x - xhat
.因此,一种更简单的计算方法np.trace(np.dot(x-xhat,(x-xhat).T))
不需要巨大的中间数组((x - xhat)**2).sum()
.例如,
In [44]: x
Out[44]:
array([[ 0.87167186, 0.96838389, 0.72545457],
[ 0.05803253, 0.57355625, 0.12732163],
[ 0.00874702, 0.01555692, 0.76742386],
[ 0.4130838 , 0.89307633, 0.49532327],
[ 0.15929044, 0.27025289, 0.75999848]])
In [45]: xhat
Out[45]:
array([[ 0.20825392, 0.63991699, 0.28896932],
[ 0.67658621, 0.64919721, 0.31624655],
[ 0.39460861, 0.33057769, 0.24542263],
[ 0.10694332, 0.28030777, 0.53177585],
[ 0.21066692, 0.53096774, 0.65551612]])
In [46]: np.trace(np.dot(x-xhat,(x-xhat).T))
Out[46]: 2.2352330441581061
In [47]: ((x - xhat)**2).sum()
Out[47]: 2.2352330441581061
Run Code Online (Sandbox Code Playgroud)
有关计算MSE的更多想法,请参阅注释中user1984065提供的链接.
归档时间: |
|
查看次数: |
1247 次 |
最近记录: |