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

Python类方法参数无法修改类变量self.t的问题排查

问题描述

我有一个Python类(TextClust),其中self.t初始化为None,self.real_time_fading设为True。期望通过learn_one方法的参数t覆盖self.t,但无论传入什么值,self.t始终为None。

相关类代码片段:

self.t = None
self.real_time_fading = True

def learn_one(self, x, t=None, sample_weight=None):
        
        # check if realtime fading is on or not. specify current time accordingly
        if self.real_time_fading:
            self.t = t
        else:
            self.t = self.n

调用代码:

from river import compose
from river import feature_extraction
from river import metrics
from river import cluster
from river import stream
from nltk.corpus import stopwords

excluded_words = stopwords.words('english')

metric = metrics.AdjustedRand()

model = compose.Pipeline(
    feature_extraction.BagOfWords(lowercase=True, ngram_range=(1, 2), stop_words=excluded_words),
    cluster.TextClust(real_time_fading=True, fading_factor=0.0001, tgap=100, auto_r=True,
    radius=0.9)
    )

data = stream.iter_csv('tweets.csv')

i = 0

for x,_ in data:
    if i < 2000:
        prediction = model.learn_one(x['tweet'], t=x['timestamp'])
        i += 1
    else:
        break

clusters = model['TextClust'].showclusters(topn=10, num=10, type="micro")
print(clusters)
问题原因分析

问题出在Pipeline的参数传递机制上:

  • 调用model.learn_one(x['tweet'], t=x['timestamp'])时,Pipeline会尝试将t参数传递给所有步骤的learn_one方法,但第一个步骤BagOfWords的learn_one仅支持x和sample_weight参数,不接受t。
  • 在新版River中,这种情况会直接抛出TypeError;旧版River则会忽略不被支持的参数,导致t无法传递到下游的TextClust实例。
  • 由于TextClust.learn_one未收到传入的t值,参数t保持默认的None,结合self.real_time_fading=True的逻辑,self.t最终被赋值为None。

正确的调用方式是使用River的上下文传递机制,仅将t参数传递给需要它的步骤:

# 修改后的调用逻辑
for x,_ in data:
    if i < 2000:
        with model.context(t=x['timestamp']):
            prediction = model.learn_one(x['tweet'])
        i += 1
    else:
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:09:51