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

Scikit-learn逻辑回归:Pipeline内‘vect’未定义错误求助

问题原因
  • 你在Pipeline里定义的vect、tfidf、clf只是Pipeline内部步骤的名称标识,并不是全局变量。这些组件实例被封装在lr这个Pipeline对象里,没有在全局命名空间中注册,所以直接调用vect.transform()会提示未定义。
正确的解决方法

方法一:直接使用Pipeline的predict方法(推荐)

Pipeline的核心优势就是把预处理和模型打包在一起,不需要单独调用每个步骤,直接用训练好的Pipeline对象对新文本预测即可:

news = ["A phase two clinical trial found the shot combined with immunotherapy drug Merck slashed the risk of melanoma returning by 44 percent compared to using the drug alone. Preliminary findings were published in December but had not been reviewed and confirmed by other scientists."]

predicted = lr.predict(news)

for doc, category in zip(news, predicted):
    print(category)

方法二:通过Pipeline的named_steps属性访问内部组件

如果确实需要单独调用某个步骤(比如调试、查看中间结果),可以通过lr.named_steps['步骤名称']来获取对应的组件实例:

news = ["A phase two clinical trial found the shot combined with immunotherapy drug Merck slashed the risk of melanoma returning by 44 percent compared to using the drug alone. Preliminary findings were published in December but had not been reviewed and confirmed by other scientists."]

# 从Pipeline中取出各个组件
vect = lr.named_steps['vect']
tfidf = lr.named_steps['tfidf']
clf = lr.named_steps['clf']

x_new_counts = vect.transform(news)
x_new_tf = tfidf.transform(x_new_counts)
predicted = clf.predict(x_new_tf)

for doc, category in zip(news, predicted):
    print(category)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:43:15