C:\Users\hp\PycharmProjects\PythonProject\.venv\Scripts\python.exe "D:\PyCharm 2025.1.1.1\PythonProject\ChineseWrite\chinese_rec.py" 2025-05-31 20:17:28.407283: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. 2025-05-31 20:17:29.081651: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. WARNING:tensorflow:From D:\PyCharm 2025.1.1.1\PythonProject\ChineseWrite\chinese_rec.py:19: The name tf.disable_v2_behavior is deprecated. Please use tf.compat.v1.disable_v2_behavior instead. WARNING:tensorflow:From C:\Users\hp\PycharmProjects\PythonProject\.venv\Lib\site-packages\tensorflow\python\compat\v2_compat.py:98: disable_resource_variables (from tensorflow.python.ops.resource_variables_toggle) is deprecated and will be removed in a future version. Instructions for updating: non-resource variables are not supported in the long term Traceback (most recent call last): File "D:\PyCharm 2025.1.1.1\PythonProject\ChineseWrite\chinese_rec.py", line 384, in <module> main(None) # 直接调用主函数 ^^^^^^^^^^ File "D:\PyCharm 2025.1.1.1\PythonProject\ChineseWrite\chinese_rec.py", line 351, in main train() File "D:\PyCharm 2025.1.1.1\PythonProject\ChineseWrite\chinese_rec.py", line 148, in train train_feeder = DataIterator(data_dir='./data/train/') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\PyCharm 2025.1.1.1\PythonProject\ChineseWrite\chinese_rec.py", line 62, in __init__ self.labels = [int(file_name[len(data_dir):].split(os.sep)[0]) for file_name in self.image_names] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: invalid literal for int() with base 10: '6.png' train Begin training ./data/train/03755 进程已结束,退出代码为 1
时间: 2025-06-01 07:19:56 浏览: 23
### 解决 TensorFlow DataIterator 中因文件名格式导致的 ValueError 错误
在 TensorFlow 数据迭代器中,`ValueError: invalid literal for int() with base 10` 的错误通常发生在尝试将文件名转换为整数标签时。这种问题可能源于文件命名规则不符合预期,或者数据预处理逻辑未正确分离文件名和标签[^2]。
以下是一个完整的解决方案,确保能够正确解析文件名并避免无效转换。
---
#### 文件名解析逻辑
假设文件名格式为 `'文字_标签.png'`,例如 `'去_9.png'`,其中 `'9'` 是标签部分。需要通过字符串操作提取标签,并将其转换为整数。
```python
import os
def extract_label(file_name):
# 假设文件名为 '文字_标签.png' 格式
try:
label_part = file_name.split('_')[-1].split('.')[0] # 提取标签部分
return int(label_part) # 转换为整数
except ValueError:
raise ValueError(f"无法从文件名 {file_name} 中提取有效的整数标签")
```
此函数通过 `split('_')` 和 `split('.')` 分离文件名中的标签部分,并尝试将其转换为整数。如果文件名格式不匹配或包含非数字字符,则会抛出异常[^3]。
---
#### 构建数据集
使用 TensorFlow 的 `tf.data.Dataset` 构建数据管道,确保文件路径和标签一一对应。
```python
import tensorflow as tf
# 定义数据目录
data_dir = './data/train/'
# 获取所有文件名
image_names = [f for f in os.listdir(data_dir) if f.endswith('.png')]
# 提取标签并构建数据集
labels = [extract_label(f) for f in image_names]
filenames = [os.path.join(data_dir, f) for f in image_names]
# 创建 TensorFlow 数据集
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
# 加载图像函数
def load_image(filename, label):
image = tf.io.read_file(filename)
image = tf.image.decode_png(image, channels=3)
image = tf.image.resize(image, [224, 224]) # 调整大小
image = image / 255.0 # 归一化
return image, label
# 映射加载函数
dataset = dataset.map(load_image)
```
在此代码中:
- `extract_label` 函数用于从文件名中提取标签。
- `tf.data.Dataset.from_tensor_slices` 将文件路径和标签组合为数据集。
- `load_image` 函数负责加载、解码和预处理图像[^4]。
---
#### 异常处理
为了增强代码的健壮性,可以在数据加载阶段添加异常处理逻辑,确保程序不会因单个文件的错误而崩溃。
```python
valid_filenames = []
valid_labels = []
for f in image_names:
try:
label = extract_label(f)
valid_filenames.append(os.path.join(data_dir, f))
valid_labels.append(label)
except ValueError:
print(f"警告:文件 {f} 的标签格式无效,已跳过")
# 使用有效数据构建数据集
dataset = tf.data.Dataset.from_tensor_slices((valid_filenames, valid_labels))
```
此代码段会过滤掉所有无法正确解析标签的文件,并打印警告信息[^5]。
---
#### 总结
通过上述方法,可以有效解决 `ValueError: invalid literal for int() with base 10` 的问题。关键在于:
1. 确保文件名格式符合预期。
2. 在数据预处理阶段正确分离文件名和标签。
3. 添加异常处理逻辑以增强代码的鲁棒性。
---
阅读全文
相关推荐















