[英]scikit-learn: How to use RandomizedSearchCV on a nested list consisting of one list?
我已經建立了一個句子邊界檢測分類器。 對於序列標記,我使用了條件隨機場。 對於超參數優化,我想使用 RandomizedSearchCV。 我的訓練數據包含 6 個帶注釋的文本。 我將所有 6 個文本合並到一個令牌列表。 對於實現,我遵循了文檔中的示例。 這是我的簡化代碼:
from sklearn_crfsuite import CRF
from sklearn_crfsuite import metrics
from sklearn.metrics import make_scorer
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import train_test_split
import scipy.stats
#my tokenlist has the length n
X_train = [feature_dict_token_1, ... , feature_dict_token_n]
# 3 types of tags, B-SEN for begin of sentence; E-SEN for end of sentence; O-Others
y_train = [tag_token_1, ..., tag_token_n]
# define fixed parameters and parameters to search
crf = sklearn_crfsuite.CRF(
algorithm='lbfgs',
max_iterations=100,
all_possible_transitions=True
)
params_space = {
'c1': scipy.stats.expon(scale=0.5),
'c2': scipy.stats.expon(scale=0.05),
}
labels = ['B-SEN', 'E-SEN', 'O']
# use F1-score for evaluation
f1_scorer = make_scorer(metrics.flat_f1_score,
average='weighted', labels=labels)
# search
rs = RandomizedSearchCV(crf, params_space,
cv=3,
verbose=1,
n_jobs=-1,
n_iter=50,
scoring=f1_scorer)
rs.fit([X_train], [y_train])
我使用rs.fit([X_train], [y_train])
而不是rs.fit(X_train, y_train)
因為 crf.train 的文檔說它需要一個列表列表:
fit(X, y, X_dev=None, y_dev=None)
Parameters:
-X (list of lists of dicts) – Feature dicts for several documents (in a python-crfsuite format).
-y (list of lists of strings) – Labels for several documents.
-X_dev ((optional) list of lists of dicts) – Feature dicts used for testing.
-y_dev ((optional) list of lists of strings) – Labels corresponding to X_dev.
但是使用列表列表我得到這個錯誤:
ValueError: Cannot have number of splits n_splits=5 greater than the number of samples: n_samples=1
我知道這是因為我分別使用 [X_train] 和 [y_train] 並且無法將 CV 應用於由一個列表組成的列表,但是使用 X_train 和 y_train crf.fit 無法應對。 我怎樣才能解決這個問題?
根據此處的官方教程,您的訓練/測試集(即X_train
、 X_test
)應該是字典列表的列表。 例如:
[[{'bias': 1.0,
'word.lower()': 'melbourne',
'word[-3:]': 'rne',
'word[-2:]': 'ne',
'word.isupper()': False,
'word.istitle()': True,
'word.isdigit()': False,
'postag': 'NP'},
{'bias': 1.0,
'word.lower()': '(',
'word[-3:]': '(',
'word[-2:]': '(',
'word.isupper()': False,
'word.istitle()': False,
'word.isdigit()': False,
'postag': 'Fpa'},
...],
[{'bias': 1.0,
'word.lower()': '-',
'word[-3:]': '-',
'word[-2:]': '-',
'word.isupper()': False,
'word.istitle()': False,
'word.isdigit()': False,
'postag': 'Fg',
'postag[:2]': 'Fg'},
{'bias': 1.0,
'word.lower()': '25',
'word[-3:]': '25',
'word[-2:]': '25',
'word.isupper()': False,
'word.istitle()': False,
'word.isdigit()': True,
'postag': 'Z'
}]]
標簽集(即y_tain
和y_test)
應該是字符串列表的列表。 例如:
[['B-LOC', 'I-LOC'], ['B-ORG', 'O']]
然后像往常一樣安裝 model:
rs.fit(X_train, y_train)
請參考上面提到的教程,看看它是如何工作的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.