Мне нравится запускать следующий рабочий процесс:
- Выбор модели для векторизации текста
- Определение списка параметров
- Применение конвейера с GridSearchCV к параметрам, используя LogisticRegression () в качестве базовой линии для поиска лучших параметров модели
- Сохранить лучшую модель (параметры)
- Загрузите лучшие параметры модели, чтобы мы могли применить ряд других классификаторов к этой определенной модели.
Вот код, который вы можете воспроизвести:
GridSearch:
%%time
import numpy as np
import pandas as pd
from sklearn.externals import joblib
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from gensim.utils import simple_preprocess
np.random.seed(0)
data = pd.read_csv('https://pastebin.com/raw/dqKFZ12m')
X_train, X_test, y_train, y_test = train_test_split([simple_preprocess(doc) for doc in data.text],
data.label, random_state=0)
# Find best Tfidf model using LR
pipeline = Pipeline([
('tfidf', TfidfVectorizer(preprocessor=' '.join, tokenizer=None)),
('clf', LogisticRegression())
])
parameters = {
'tfidf__max_df': [0.25, 0.5, 0.75, 1.0],
'tfidf__smooth_idf': (True, False),
'tfidf__norm': ('l1', 'l2', None),
}
grid = GridSearchCV(pipeline, parameters, cv=2, verbose=1)
grid.fit(X_train, y_train)
print(grid.best_params_)
# Save model
#joblib.dump(grid.best_estimator_, 'best_tfidf.pkl', compress = 1) # this unfortunately includes the LogReg
joblib.dump(grid.best_params_, 'best_tfidf.pkl', compress = 1) # Only best parameters
Подгонка 2 сгибов для каждого из 24 кандидатов, всего 48 подгонок
{'tfidf__smooth_idf': True, 'tfidf__norm': 'l2', 'tfidf__max_df': 0.25}
Загрузить модель с лучшими параметрами:
from sklearn.model_selection import GridSearchCV
# Load best parameters
tfidf_params = joblib.load('best_tfidf.pkl')
pipeline = Pipeline([
('vec', TfidfVectorizer(preprocessor=' '.join, tokenizer=None).set_params(**tfidf_params)), # here is the issue?
('clf', LogisticRegression())
])
cval = cross_val_score(pipeline, X_train, y_train, scoring='accuracy', cv=5)
print("Cross-Validation Score: %s" % (np.mean(cval)))
ValueError: Неверный параметр tfidf для оценщика
TfidfVectorizer (analyzer = 'word', binary = False, decode_error = 'strict',
dtype =, encoding = 'utf-8', input = 'content',
нижний регистр = True, max_df = 1,0, max_features = нет, min_df = 1,
ngram_range = (1, 1), norm = 'l2',
препроцессор =,
smooth_idf = True, stop_words = Нет, strip_accents = Нет,
sublinear_tf = False, token_pattern = '(? u) \ b \ w \ w + \ b',
tokenizer = Нет, use_idf = True, словарь = Нет). Проверьте список доступных параметров с помощью estimator.get_params().keys()
.
Вопрос:
Как загрузить лучшие параметры модели Tfidf?