You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Keras Normalization层invert=True反归一化功能异常问题

Keras Normalization层invert=True反归一化结果异常问题

问题复现

使用Keras 2.10.0版本的Normalization层,设置invert=True进行反归一化时,输出结果与预期不符。测试代码如下:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import layers

norm = layers.Normalization()
denorm = layers.Normalization(invert=True)
y = np.array([[10.0], 
              [20.0], 
              [30.0]])
norm.adapt(y)
denorm.adapt(y)

print(norm(20))  # 输出0,符合归一化预期
print(denorm(0)) # 输出163.29932,预期应为20

经检查,两个层的均值、方差参数一致,但反归一化计算结果错误,推测是计算顺序颠倒:实际执行了先加均值再乘标准差,而非正确的反归一化逻辑先乘标准差再加均值。

原因分析

Keras 2.10.0版本的Normalization层在invert=True时存在实现bug,颠倒了反归一化的计算步骤。

正确的反归一化公式:
$$\text{反归一化值} = x \times \text{标准差} + \text{均值}$$

该版本错误执行的公式:
$$\text{错误结果} = (x + \text{均值}) \times \text{标准差}$$

以测试数据为例,均值为20,标准差约为8.164966,错误计算为$(0+20)×8.164966≈163.29932$,与实际输出完全匹配,证实了该bug的存在。

解决办法

  1. 手动实现反归一化:绕过invert=True的bug,直接通过已适配的均值和标准差手动计算:
# 获取归一化层的均值和标准差
mean = norm.mean.numpy()[0]
std = np.sqrt(norm.variance.numpy()[0])

# 自定义反归一化函数
def denormalize(x):
    return x * std + mean

print(denormalize(0)) # 输出20.0,符合预期
  1. 升级Keras版本:该bug在Keras 2.11及后续版本中已修复,升级到最新稳定版本即可正常使用invert=True参数。

内容的提问来源于stack exchange,提问作者Vincent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:50:33