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

创建PyTorch分割模型时遇AttributeError:无'to'属性问题求助

问题排查与解决

错误原因

你的segmentationmodels类没有继承PyTorch核心的nn.Module基类,因此无法调用to()这类PyTorch模型专属的方法,导致抛出AttributeError。

修复代码

只需让你的类继承nn.Module即可,修改后的完整代码如下:

from torch import nn
import segmentation_models_pytorch as smp
from segmentation_models_pytorch.losses import DiceLoss 

# 继承nn.Module基类
class segmentationmodels(nn.Module):
  def __init__(self):
    super(segmentationmodels,self).__init__()
    # 需提前定义ENCODER和weights变量,例如ENCODER='resnet34',weights='imagenet'
    self.arc=smp.Unet(
        encoder_name=ENCODER,
        encoder_weights=weights,
        in_channels=3,
        classes=1,
        activation=None
    )
  def forward(self,images,mask=None):
    logits=self.arc(images)
    if mask is not None:  # 推荐用is not None替代!=None,符合Python规范
      loss1=DiceLoss(mode='binary')(logits,mask)
      loss2=nn.BCEWithLogitsLoss()(logits,mask)
      return logits,loss1+loss2
    return logits

# 需提前定义DEVICE,例如DEVICE='cuda' if torch.cuda.is_available() else 'cpu'
model=segmentationmodels()
model.to(DEVICE)

额外注意事项

  • 必须提前定义ENCODER、weights和DEVICE变量,否则会触发新的未定义错误。
  • 判断变量非空时,mask is not None是更规范的Python写法,建议替换原代码中的mask != None。

内容的提问来源于stack exchange,提问作者Aryan Tyagi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:00:15