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

FastAI调用unet_learner报错TypeError: 'str'对象不可调用求助

问题分析

报错核心为 TypeError: 'str' object is not callable,追踪到fastai的create_unet_model函数中执行model = arch(pretrained)时触发。这说明你从yaml配置中读取的training.architecture是字符串类型(例如'resnet34'),但unet_learner要求传入的是可调用的模型架构函数,而非字符串。

解决办法

方法1:使用字典映射字符串到架构函数(推荐,更安全)

先定义字符串与对应模型架构函数的映射关系,再将配置中的字符串转换为可调用对象:

import numpy as np
from fastai.vision.all import *

# 定义架构映射字典,根据你的需求添加需要的模型
arch_map = {
    'resnet18': resnet18,
    'resnet34': resnet34,
    'resnet50': resnet50,
    'efficientnet_b0': efficientnet_b0
}

def train(dls, file_path, training):
    labels = np.loadtxt(file_path.labels, dtype=str)
    weights = torch.tensor(eval(training.weights))

    print('#################')
    print(weights)
    print(type(weights))
    print('#################')

    # 将字符串架构转换为可调用函数
    arch = arch_map[training.architecture]
    learner = unet_learner(dls, arch, loss_func=CrossEntropyLossFlat(
        axis=1,
        weight=weights)
    )

    return learner.load(file_path.weights)

方法2:使用eval()直接转换字符串(需注意安全风险)

如果yaml配置中的架构名称与导入的函数名完全一致,可直接用eval()转换,但此方式在配置内容不可控时存在安全隐患:

import numpy as np
from fastai.vision.all import *

def train(dls, file_path, training):
    labels = np.loadtxt(file_path.labels, dtype=str)
    weights = torch.tensor(eval(training.weights))

    print('#################')
    print(weights)
    print(type(weights))
    print('#################')

    # 直接将字符串转换为架构函数
    arch = eval(training.architecture)
    learner = unet_learner(dls, arch, loss_func=CrossEntropyLossFlat(
        axis=1,
        weight=weights)
    )

    return learner.load(file_path.weights)

关键注意点

  • 确保yaml中architecture的取值与fastai.vision.all中导入的模型函数名完全匹配(例如'resnet34'对应resnet34函数)
  • 优先选择方法1,避免eval()带来的潜在安全风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:36:33