python - 如何使用神经网络同时预测期望值和方差?
问题描述
我想使用神经网络来预测一个标量值,它是输入值的函数和随机值(我假设是高斯分布)的总和,其方差也取决于输入值。现在我想要一个有两个输出的神经网络——第一个输出应该近似确定性部分——函数,第二个输出应该近似随机部分的方差,具体取决于输入值。我需要什么损失函数来训练这样的网络?
(如果有一个用于 Tensorflow 的 Python 示例,那就太好了,但我也对一般答案感兴趣。我也不太清楚如何用 Python 代码编写类似的东西 - 到目前为止我没有找到任何示例展示如何处理损失函数的单个输出。)
解决方案
由于我发现没有什么简单的实现,我自己写了一些东西,明确地建模:这是一个自定义损失函数,它试图预测 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)
输出维度是标签维度的两倍——标签中每个值的均值和方差。损失函数由两部分组成:均方误差,其均值近似于标签值的均值,方差近似于该值与预测均值的差异。
推荐阅读
- node.js - 如何在 heroku 上部署 socket io 和 express 服务器
- python - 弃用警告:如何删除 tf.keras 警告“不推荐使用 dtype 调用 VarianceScaling.__init__ ...”
- postgresql - PostgreSQL - 如何在 Distinct On 时计数
- protractor - Protractor 动态创建 Spec 文件
- haskell - 在顶层,结果将保留在内存中
- keycloak - Keycloak OpenID 连接
- python - pytorch:来自两个网络的损失如何表现?
- reactjs - 我收到混合内容错误,如何让 node_modules 或 Laravel 允许我通过 https 进行 api 调用?
- json - MongoDB如何高效地存储数据?
- html - 如何在不使用 JS/PHP 的情况下将我的网站图标设置为出现在网站的每个页面上