首页 > 解决方案 > 如何使用神经网络同时预测期望值和方差?

问题描述

我想使用神经网络来预测一个标量值,它是输入值的函数和随机值(我假设是高斯分布)的总和,其方差也取决于输入值。现在我想要一个有两个输出的神经网络——第一个输出应该近似确定性部分——函数,第二个输出应该近似随机部分的方差,具体取决于输入值。我需要什么损失函数来训练这样的网络?

(如果有一个用于 Tensorflow 的 Python 示例,那就太好了,但我也对一般答案感兴趣。我也不太清楚如何用 Python 代码编写类似的东西 - 到目前为止我没有找到任何示例展示如何处理损失函数的单个输出。)

标签: pythontensorflowneural-networkdeep-learningloss-function

解决方案


由于我发现没有什么简单的实现,我自己写了一些东西,明确地建模:这是一个自定义损失函数,它试图预测 mean 和 variance。它似乎有效,但我不太确定它在实践中的效果如何,我会很感激反馈。这是我的损失函数:

def meanAndVariance(y_true: tf.Tensor , y_pred: tf.Tensor) -> tf.Tensor :
  """Loss function that has the values of the last axis in y_true 
  approximate the mean and variance of each value in the last axis of y_pred."""
  y_pred = tf.convert_to_tensor(y_pred)
  y_true = math_ops.cast(y_true, y_pred.dtype)
  mean = y_pred[..., 0::2]
  variance = y_pred[..., 1::2]
  res = K.square(mean - y_true) + K.square(variance - K.square(mean - y_true))
  return K.mean(res, axis=-1)

输出维度是标签维度的两倍——标签中每个值的均值和方差。损失函数由两部分组成:均方误差,其均值近似于标签值的均值,方差近似于该值与预测均值的差异。


推荐阅读