简体   繁体   English

由 TensorFlow 计算的均方误差

[英]Mean squared error computed by TensorFlow

I am trying to figure out how the mean squared error (MSE) is calculated by tensorflow and was reading the post at https://www.tensorflow.org/api_docs/python/tf/keras/metrics/mean_squared_error .我试图弄清楚tensorflow是如何计算均方误差 (MSE) 的,并且正在阅读 https 上的帖子://www.Z2C39BC19B761AC36DC046245D1_D47FE6Z.org/api_docs/squaredpython/metrics

First of all, MSE is defined as (see https://en.wikipedia.org/wiki/Mean_squared_error ):首先,MSE 定义为(参见https://en.wikipedia.org/wiki/Mean_squared_error ):

在此处输入图像描述

Suppose I have a single output and create true and predicted values.假设我有一个 output 并创建真实值和预测值。

import numpy as np
import random

y_true = np.random.randint(0, 10, size=(2, 1))
print(y_true,"\n")
y_pred = np.random.randint(0,5,size=(2, 1))
print(y_pred)

[[7]
 [5]]

[[2]
 [2]]

When I call tf.keras.losses.mean_squared_error(y_true, y_pred) , what I expect to see is that [(7-2)^2 + (5-2)^2]/2 = 17 , however, it returns me array([25, 9]) .当我调用tf.keras.losses.mean_squared_error(y_true, y_pred)时,我期望看到的是[(7-2)^2 + (5-2)^2]/2 = 17 ,但是,它返回给我array([25, 9]) Why doesn't tensorflow compute the mean?为什么 tensorflow 不计算平均值?

Then, I increase the column numbers.然后,我增加列号。

y_true = np.random.randint(0, 10, size=(2, 3))
print(y_true,"\n")
y_pred = np.random.randint(0,5,size=(2, 3))
print(y_pred)

[[2 6 0]
 [3 3 4]] 

[[4 2 4]
 [3 4 2]]

The answer returned by tensorflow is array([12, 1]) . tensorflow返回的答案是array([12, 1]) I'm not able to understand how these values are computed.我无法理解这些值是如何计算的。 What I was expecting was [(2-4)^2+ (6-2)^2+(0-4)^2]/2 + [(3-3)^2 + (3-4)^2+ (4-2)^2]/2 .我所期待的是[(2-4)^2+ (6-2)^2+(0-4)^2]/2 + [(3-3)^2 + (3-4)^2+ (4-2)^2]/2

The second value is computed as第二个值计算为

a = np.array([2,6,0])
b = np.array([4,2,4])
((b - a)**2).mean()

Or [(2-4)^2+ (6-2)^2+(0-4)^2]/3[(2-4)^2+ (6-2)^2+(0-4)^2]/3

According to their doc it is equivalent to np.mean(np.square(y_true - y_pred), axis=-1)根据他们的文档,它相当于np.mean(np.square(y_true - y_pred), axis=-1)

So it is computing the mse row-wise.所以它正在逐行计算mse。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM