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

使用R的reticulate调用Hugging Face BERT模型遇属性错误

在R中用reticulate调用Hugging Face BERT模型报错:AttributeError: 'BertConfig' object has no attribute 'pretrained_model'

我在Python环境中能正常运行调用Wellcome/WellcomeBertMesh模型的代码,但切换到R用reticulate库调用时,无论用哪种方式都会报错AttributeError: 'BertConfig' object has no attribute 'pretrained_model'。

可正常运行的Python代码

# Load model directly
from transformers import AutoTokenizer, AutoModel

tokenizer = AutoTokenizer.from_pretrained("Wellcome/WellcomeBertMesh", trust_remote_code=True)
model = AutoModel.from_pretrained("Wellcome/WellcomeBertMesh", trust_remote_code=True)

def MeshHelp (word_list):
    labels_list = []
    for word in word_list:
        inputs = tokenizer([word], padding="max_length")
        labels = model(**inputs, return_labels=True)
        labels_list.extend(labels)
    return labels_list

我在R中尝试的三种失败调用方式

# source_python方式
source_python('script.py')

# py_run_string方式
py_run_string('from transformers import AutoTokenizer, AutoModel')
py_run_string('tokenizer = AutoTokenizer.from_pretrained("Wellcome/WellcomeBertMesh", trust_remote_code=True)')
py_run_string('model = AutoModel.from_pretrained("Wellcome/WellcomeBertMesh", trust_remote_code=True)')

# pipelines方式
transformers$pipeline("Wellcome/WellcomeBertMesh")

问题原因与解决方法

核心原因

报错本质是reticulate处理Hugging Face自定义模型的远程代码加载时,参数传递不完整,或R端封装的transformers工具对自定义模型支持存在兼容性问题。

具体解决步骤

  1. 对齐Python环境
    先检查reticulate绑定的Python环境是否和本地运行成功的环境一致:

    library(reticulate)
    py_config()
    

    若不一致,用use_python()指定正确路径:

    use_python("/path/to/your/python/env/bin/python")
    
  2. 统一加载逻辑,避免拆分调用
    不要用py_run_string拆分执行代码,把完整的模型加载、函数定义放在同一个Python脚本中,再通过source_python调用,确保trust_remote_code=True参数全程生效。

  3. 注意数据类型转换
    在R中调用Python函数时,将R的字符向量转为Python列表:

    library(reticulate)
    source_python("script.py")
    # 转换数据类型后调用函数
    result <- MeshHelp(py_list(c("example_word1", "example_word2")))
    
  4. 优先用原生Python代码调用
    R的transformers包对需要加载远程自定义代码的模型支持有限,建议直接通过reticulate调用原生Python逻辑,避免使用R端的transformers$pipeline。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:01:22