File "<string>", line 1, in <module> File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 122, in spawn_main exitcode = _main(fd, parent_sentinel) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 131, in _main prepare(preparation_data) File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 246, in prepare _fixup_main_from_path(data['init_main_from_path']) File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 297, in _fixup_main_from_path main_content = runpy.run_path(main_path, ^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen runpy>", line 291, in run_path File "<frozen runpy>", line 98, in _run_module_code File "<frozen runpy>", line 88, in _run_code File "c:\Users\starship3136\Desktop\10\main.py", line 323, in <module> train_loss, train_acc = train_one_epoch( ^^^^^^^^^^^^^^^^ File "c:\Users\starship3136\Desktop\10\main.py", line 235, in train_one_epoch for inputs, labels in pbar: File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\site-packages\tqdm\std.py", line 1181, in __iter__ for obj in iterable: File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\site-packages\torch\utils\data\dataloader.py", line 491, in __iter__ return self._get_iterator() ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\site-packages\torch\utils\data\dataloader.py", line 422, in _get_iterator return _MultiProcessingDataLoaderIter(self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\site-packages\torch\utils\data\dataloader.py", line 1146, in __init__ w.start() File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\process.py", line 121, in start self._popen = self._Popen(self) ^^^^^^^^^^^^^^^^^ File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\context.py", line 336, in _Popen return Popen(process_obj) ^^^^^^^^^^^^^^^^^^ File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__ prep_data = spawn.get_preparation_data(process_obj._name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 164, in get_preparation_data _check_not_importing_main() File "C:\Users\starship3136\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 140, in _check_not_importing_main raise RuntimeError(''' RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable. To fix this issue, refer to the "Safe importing of main module" section in https://docs.python.org/3/library/multiprocessing.html 出现以上报错的原因以及解决方案
时间: 2025-05-13 19:32:11 浏览: 20
### 错误原因分析
该错误是由 `multiprocessing` 模块在 Windows 上启动新进程时发生的。具体来说,它发生在尝试启动新的子进程之前,当前主进程尚未完成其引导阶段(bootstrapping phase)。这通常是由于代码没有正确地使用 Python 的 `if __name__ == "__main__":` 守卫语句来保护主模块中的多进程代码。
在 Windows 平台上,Python 使用 `spawn` 启动方法创建子进程,默认情况下不会像 Unix/Linux 那样使用 `fork` 方法。因此,在导入或执行任何涉及多线程或多进程操作的代码前,必须确保这些代码被放置在一个条件语句中以防止它们在子进程中重复运行。
此外,如果程序将来会被打包成可执行文件,则需要调用 `freeze_support()` 函数来支持冻结后的执行环境。
### 解决方案
为了修复这个问题,请按照以下步骤修改您的代码:
#### 1. 修改主脚本入口点
将所有与多进程相关的初始化和调用放在一个 `if __name__ == "__main__":` 块内。例如:
```python
if __name__ == "__main__":
# 设置随机种子等预处理部分可以放在这里
set_seed()
# 初始化设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")
# 创建结果保存文件夹
os.makedirs('results', exist_ok=True)
# 探索数据集结构并展示样本图像
data_path = "C:/Users/starship3136/Desktop/10/Fruits and Vegetables Image Recognition Dataset"
explore_data(data_path)
# 数据增强及模型定义等相关代码...
# 训练配置
config = OptimizedConfig()
# 构建训练集和验证集的数据加载器
train_dataset = FruitVegDataset(data_path, 'train', train_transform)
val_dataset = FruitVegDataset(data_path, 'validation', val_transform)
train_loader = DataLoader(train_dataset,
batch_size=config.batch_size,
shuffle=True,
num_workers=4,
pin_memory=True)
val_loader = DataLoader(val_dataset,
batch_size=config.batch_size,
shuffle=False,
num_workers=4,
pin_memory=True)
# 初始化优化后的模型并进行训练
model = OptimizedCNN(num_classes=len(train_dataset.classes)).to(device)
history = train_with_optimization(model, train_loader, val_loader, config)
# 绘制训练结果图
plot_optimized_results(history)
# 加载最优模型并预测示例图片
model = load_model()
predict_image('https://pngimg.com/uploads/watermelon/watermelon_PNG2640.png', model)
```
#### 2. 添加 `freeze_support()`
如果您计划将此应用程序打包为独立的可执行文件(例如通过 PyInstaller),则应在 `if __name__ == "__main__":` 内的第一行添加对 `freeze_support()` 的调用:
```python
if __name__ == "__main__":
multiprocessing.freeze_support()
...
```
这样做的目的是确保当应用程序被打包后,在某些平台上仍然能够正常工作。
### 总结
通过上述更改,您可以避免因不当使用多进程而导致的异常情况,并且确保了程序在未来可能的打包过程中也能稳定运行。希望这对您有所帮助!如果有其他疑问或者需要进一步的帮助,请随时告知。
阅读全文
相关推荐














