Python 使用计数向量器时,在新文本上使用sklearn逻辑回归-需要相同数量的稀疏矩阵特征
我使用sklearn和CountVectorizer对一些数据进行了逻辑回归训练,方法如下:Python 使用计数向量器时,在新文本上使用sklearn逻辑回归-需要相同数量的稀疏矩阵特征,python,scikit-learn,tokenize,Python,Scikit Learn,Tokenize,我使用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, pen
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
有人知道怎么避开这件事吗?我基本上需要使用与我最初使用的相同的稀疏矩阵来“矢量化”新文本
谢谢 这可以通过保存第一个矢量器的功能,然后将其用作第二个矢量器的词汇参数来实现。例如:
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)