1

python (sklearn edition)에서 xgboost를 사용하여 다중 텍스트 텍스트 분류를 수행하려하지만 기능 이름에 불일치가 있음을 알리는 오류가 발생합니다. 이상한 점은 때로는 작동한다는 것입니다 (아마도 4 번 중 1 번).하지만 실제 해결책을 제시하지 않고서도 고무적인 결과를 보여주고 있지만 불확실성으로 인해 현재이 솔루션에 의존하기가 어렵습니다. 처리.다중 클래스 텍스트 분류 중 xgboost sklearn의 feature_names가 일치하지 않습니다.

나는 내가 사용하고자하는 것과 유사한 코드의 예시적인 샘플 데이터를 제공했다. 다음과 같이 내가 현재 가지고있는 코드는 다음과 같습니다

maxymoo의 제안을 반영 업데이트 코드

import xgboost as xgb 
import numpy as np 
from sklearn.cross_validation import KFold, train_test_split 
from sklearn.metrics import accuracy_score 
from sklearn.feature_extraction.text import CountVectorizer 

rng = np.random.RandomState(31337)  

y = np.array([0, 1, 2, 1, 0, 3, 1, 2, 3, 0]) 
X = np.array(['milk honey bear bear honey tigger', 
      'tom jerry cartoon mouse cat cat WB', 
      'peppa pig mommy daddy george peppa pig pig', 
      'cartoon jerry tom silly', 
      'bear honey hundred year woods', 
      'ben holly elves fairies gaston fairy fairies castle king', 
      'tom and jerry mouse WB', 
      'peppa pig daddy pig rebecca rabit', 
      'elves ben holly little kingdom king big people', 
      'pot pot pot pot jar winnie pooh disney tigger bear']) 

xgb_model = make_pipeline(CountVectorizer(), xgb.XGBClassifier()) 

kf = KFold(y.shape[0], n_folds=2, shuffle=True, random_state=rng) 
for train_index, test_index in kf: 
    xgb_model.fit(X[train_index],y[train_index]) 
    predictions = xgb_model.predict(X[test_index]) 
    actuals = y[test_index] 
    accuracy = accuracy_score(actuals, predictions) 
    print accuracy 

다음과 같이 내가하는 경향이 오류는 다음과 같습니다

Traceback (most recent call last): 
    File "main.py", line 95, in <module> 
    predictions = xgb_model.predict(X[test_index]) 
    File "//anaconda/lib/python2.7/site-packages/xgboost-0.6-py2.7.egg/xgboost/sklearn.py", line 465, in predict 
    ntree_limit=ntree_limit) 
    File "//anaconda/lib/python2.7/site-packages/xgboost-0.6-py2.7.egg/xgboost/core.py", line 939, in predict 
    self._validate_features(data) 
    File "//anaconda/lib/python2.7/site-packages/xgboost-0.6-py2.7.egg/xgboost/core.py", line 1179, in _validate_features 
    data.feature_names)) 
ValueError: feature_names mismatch: ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24', 'f25', 'f26'] ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24'] 
expected f26, f25 in input data 

모든 포인터는 정말 것 고맙다!

+0

그냥 추측하지만, 훈련 데이터가 f338 누락에 행의 일부입니다? – user1157751

+0

내 대답 정확히 여기에 같은 문제 http://stackoverflow.com/questions/38740885/xgboost-difference-in-train-and-test-features-after-converting-to-dmatrix/38887112#38887112 – abhiieor

답변

0

교육을받은 기능으로 만 모델에 점수를 매기고 있는지 확인해야합니다. 이를 수행하는 일반적인 방법은 Pipeline을 사용하여 벡터 라이저와 모델을 함께 패키징하는 것입니다. 그런 식으로 동시에 교육을 받게되며, 테스트 데이터에서 새로운 기능이 발견되면 벡터 기는이를 무시할 것입니다 (교차 모델의 각 단계에서 모델을 다시 만들 필요가 없습니다. 검증, 당신은 단지 한 번을 초기화하고 각 배에 그것을 다시 장착) :

from sklearn.pipeline import make_pipeline  

xgb_model = make_pipeline(CountVectoriser(), xgb.XGBClassifier()) 
for train_index, test_index in kf: 
    xgb_model.fit(X[train_index],y[train_index]) 
    predictions = xgb_model.predict(X[test_index]) 
    actuals = y[test_index] 
    accuracy = accuracy_score(actuals, predictions) 
    print accuracy 
+0

이것은 논리적이고 나는 그것이 효과가있을 것이라는 기대가 있었지만 어떤 이유로 그것을하지 않았습니다. 문제를 보여주는 기존 질문에 작업 예제를 추가했습니다. – koend

+0

아마도 CountVectoriser()가 희소 행렬을 반환하는 반면 XGBClassifier()는 밀도가 높은 행렬을 필요로할까요? 그러나 그것을 밀도가 높은 것으로 바꾸면 내 기억 공간을 먹는 것처럼 보입니다 ... – koend

+0

코드가 내게 오류를 던지지 않습니다 ... 아마도 sklearn의 최신 버전으로 업데이트 할 수 있습니까? 나는 파이썬 3.4, scikit 0.17.1을 사용하고있다. – maxymoo