# OutOfRangeError：序列结束 [Op:IteratorGetNext]

- **ID:** `tensorflow/iterator-get-next-out-of-range`
- **领域:** tensorflow
- **类别:** runtime_error
- **错误码:** `EOS`
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

tf.data 迭代器已耗尽，因为数据集中没有更多元素，但训练循环尝试再次获取。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| tensorflow 2.15 | active | — | — |
| tensorflow 2.16 | active | — | — |
| tensorflow 2.17 | active | — | — |

## 解决方案

1. ```
   Wrap the training loop with `for batch in dataset.take(num_batches):` instead of using a manual iterator, ensuring the loop terminates when data runs out. Example: `for batch in train_dataset.take(steps_per_epoch): model.train_on_batch(batch)`.
   ```
2. ```
   Use `dataset.repeat()` before iterating to allow multiple epochs, but ensure `steps_per_epoch` is set correctly to avoid infinite training.
   ```

## 无效尝试

- **** — Increasing the dataset size via repeat() without proper cardinality handling can mask the issue but leads to infinite loops. (70% 失败率)
- **** — Manually catching the error with try/except in eager mode works but does not fix the root cause of the loop logic. (50% 失败率)
