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

实现模型时遭遇TypeError:期望`trainable`参数为布尔值却得到bert的问题排查求助

解决TypeError: Expected trainable argument to be a boolean, but got: bert

这个错误的根源其实很直接——你在加载BERT的hub.KerasLayer时,位置参数的使用搞混了!

hub.KerasLayer的第二个位置参数是trainable(只接受布尔值或None),而你直接把字符串"bert"放在了第二个参数的位置,这就相当于把这个字符串传给了trainable参数,而不是你想设置的name参数。这就触发了类型错误,因为trainable根本不接受字符串类型的输入。

修正后的文本编码器构建函数

只需把BERT层的加载代码改成显式指定name关键字参数就能解决问题:

def create_text_encoder( num_projection_layers, projection_dims, dropout_rate, trainable=False ):
    # Load the BERT preprocessing module.
    preprocess = hub.KerasLayer( "https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2", name="text_preprocessing", )
    # Load the pre-trained BERT model to be used as the base encoder.
    bert = hub.KerasLayer( 
        "https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-512_A-8/1", 
        name="bert",  # 明确指定name参数,避免和trainable位置混淆
        trainable=trainable  # 可选:直接在这里设置trainable,不用后续单独赋值
    )
    # 如果你更习惯原有写法,也可以保留下面这行,和上面的trainable参数二选一即可
    # bert.trainable = trainable
    # Receive the text as inputs.
    inputs = layers.Input(shape=(), dtype=tf.string, name="text_input")
    # Preprocess the text.
    bert_inputs = preprocess(inputs)
    # Generate embeddings for the preprocessed text using the BERT model.
    embeddings = bert(bert_inputs)["pooled_output"]
    # Project the embeddings produced by the model.
    outputs = project_embeddings( embeddings, num_projection_layers, projection_dims, dropout_rate )
    # Create the text encoder model.
    return keras.Model(inputs, outputs, name="text_encoder")

补充说明

原代码中bert = hub.KerasLayer("xxx", "bert")的写法,会让Python把第二个字符串参数解析为trainable的取值,完全偏离了你设置层名称的初衷。通过显式用name="bert"指定参数,就能让Keras正确识别你的配置意图,同时也能让代码可读性更强。

修正之后,再调用create_text_encoder时就不会再触发这个类型错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:47:46