Skip to main content
 首页 » 编程设计

python之使用 CountVectorizer 时对新文本使用 sklearn 逻辑回归之需要相同数量的稀疏矩阵特征

2025年05月04日9duanxz

我有一个逻辑回归,我已经通过以下方式使用 sklearn 和 CountVectorizer 对一些数据进行了训练:

vect= CountVectorizer(ngram_range=(1,3), binary =True, min_df=250, stop_words = 'english') 
X = vect.fit_transform(data['text'].values) 
y = data['label'] 
 
logreg = linear_model.LogisticRegression(C=1, penalty='l1') 
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2, random_state=0) 
 
model = logreg.fit(X_train, y_train) 
joblib.dump(model, 'log_reg_model.pkl')  

我想用来将相同的模型加载到另一个 python 文件中,并用它来评估在不同上下文中找到的文本。但是,当我尝试在第二个上下文中使用 CountVectorizer 时,因为我对一组不同的文本进行矢量化,所以创建的稀疏矩阵具有不同数量的特征。

model = joblib.load('log_reg_model.pkl')  
 
if DEBUG: 
    sys.stdin = open('test.tsv', 'r') 
 
data = DataFrame(columns = ['text']) 
 
for line in sys.stdin: 
    fields = line.split('\t') 
    data.loc[len(data)+1]=[fields[0]] 
 
vect= CountVectorizer(ngram_range=(1,3), binary =True, stop_words = 'english') 
text = vect.fit_transform(data['text'].values) 
prediction = model.predict(text) 
 
ValueError: X has 131690 features per sample; expecting 4128 

有谁知道如何解决这个问题?我基本上需要使用与我最初使用的相同的稀疏矩阵来“矢量化”新文本。

谢谢!

请您参考如下方法:

这可以通过保存第一个 Vectorizer 的特征,然后将它们用作第二个 Vectorizer 的词汇参数来实现。例如,

feature_list = vect.get_feature_names() 
joblib.dump(feature_list, 'vocabulary.pkl') 

然后

vocabulary = joblib.load('vocabulary.pkl')  
vect= CountVectorizer(ngram_range=(1,3), binary =True, stop_words = 'english', vocabulary = vocabulary)