# tensorflow.python.framework.errors_impl.InvalidArgumentError: 损失为 inf 或 nan: 张量包含 NaN 值

- **ID:** `tensorflow/optimizer-nan-loss`
- **领域:** tensorflow
- **类别:** runtime_error
- **错误码:** `NAN_LOSS`
- **验证级别:** ai_generated
- **修复率:** 75%

## 根因

损失函数产生了 NaN 值，通常是由于梯度爆炸、除以零或损失计算中对零取对数。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| tensorflow 2.8.0 | active | — | — |
| tensorflow 2.9.0 | active | — | — |
| tensorflow 2.10.0 | active | — | — |

## 解决方案

1. ```
   Add gradient clipping in the optimizer: `optimizer = tf.keras.optimizers.Adam(clipnorm=1.0)` or use `tf.clip_by_global_norm`. Also check for log(0) by adding a small epsilon: `loss = -tf.reduce_sum(y_true * tf.math.log(y_pred + 1e-10))`.
   ```

## 无效尝试

- **** — This may delay NaN but does not fix the root cause; the loss can still explode later. (90% 失败率)
- **** — SGD is also susceptible to exploding gradients without clipping. (85% 失败率)
