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

类U-Net架构图像分割mask生成失效,Jupyter Notebook运行报错

解决方案

故障根因

你调整的两个参数直接导致内存占用飙升:原示例num_classes仅为3,修改为256后单张预测张量的内存占用直接提升85倍,叠加输入尺寸调整后,一次性加载全量验证集的预测结果val_preds会直接耗尽系统内存,触发Jupyter内核过载崩溃。

修复方案

  • 不要一次性预测整个验证集,仅针对需要查看的单张样本做预测,避免无效内存占用,修改后可运行代码如下:
import gc
# 指定需要查看的验证样本序号
i = 10
# 加载并预处理单张输入图像
img = keras.preprocessing.image.load_img(val_input_img_paths[i], target_size=img_size)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0
# 仅预测单张样本,关闭冗余日志
single_pred = model.predict(img_array, verbose=0)
# 显示输入图像
display(Image(filename=val_input_img_paths[i]))
# 显示真值掩码
img = PIL.ImageOps.autocontrast(load_img(val_target_img_paths[i]))
display(img)
# 生成并显示预测掩码
mask = np.argmax(single_pred[0], axis=-1)
mask = np.expand_dims(mask, axis=-1)
pred_img = PIL.ImageOps.autocontrast(keras.preprocessing.image.array_to_img(mask))
display(pred_img)
# 主动回收无用内存,避免累积占用
del single_pred, img_array
gc.collect()
  • 如果需要批量查看验证样本,将batch_size调低到2~4,每次预测1个batch后立刻处理显示、释放内存,不要存储全量预测结果。
  • 确认全链路参数一致性,检查OxfordPets数据生成类、模型定义处的输入尺寸参数是否和你修改的256×25完全匹配,避免张量形状异常导致的额外内存占用;如果你写的256×25是笔误、实际为256×256,需要进一步调低单次预测的样本数量。

内容的提问来源于stack exchange,提问作者Inès BEAUMONT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:24:04