2012-08-28 2 views
2

일부 NLP 작업을 수행하기 위해 scikit-learn 패키지에 구현 된 여러 분류자를 실험하고 있습니다. 다항식 커널로 LinearSVC와 SVC : 나는 분류를 수행하는 데 사용하는 코드는 내가 지원 벡터 기계 분류의 두 가지 구현을 테스트하고있어, 다음scikit-learn에서 다항식 커널과 함께 지원 벡터 분류 자 ​​사용

def train_classifier(self, argcands): 
     # Extract the necessary features from the argument candidates 
     train_argcands_feats = [] 
     train_argcands_target = [] 

     for argcand in argcands: 
      train_argcands_feats.append(self.extract_features(argcand)) 
      train_argcands_target.append(argcand["info"]["label"]) 

     # Transform the features to the format required by the classifier 
     self.feat_vectorizer = DictVectorizer() 
     train_argcands_feats = self.feat_vectorizer.fit_transform(train_argcands_feats) 

     # Transform the target labels to the format required by the classifier 
     self.target_names = list(set(train_argcands_target)) 
     train_argcands_target = [self.target_names.index(target) for target in train_argcands_target] 

     # Train the appropriate supervised model 
     self.classifier = LinearSVC() 
     #self.classifier = SVC(kernel="poly", degree=2) 

     self.classifier.fit(train_argcands_feats,train_argcands_target) 

     return 

def execute(self, argcands_test): 
     # Extract features 
     test_argcands_feats = [self.extract_features(argcand) for argcand in argcands_test] 

     # Transform the features to the format required by the classifier 
     test_argcands_feats = self.feat_vectorizer.transform(test_argcands_feats) 

     # Classify the candidate arguments 
     test_argcands_targets = self.classifier.predict(test_argcands_feats) 

     # Get the correct label names 
     test_argcands_labels = [self.target_names[int(label_index)] for label_index in test_argcands_targets] 

     return zip(argcands_test, test_argcands_labels) 

으로이 코드에 의해 볼 수있다. 내 "문제"에 대해. LinearSVC를 사용할 때 아무런 문제없이 분류가 나옵니다. 테스트 인스턴스에는 몇 개의 레이블이 붙어 있습니다. 그러나 다항식 SVC를 사용하면 모든 테스트 인스턴스에 SAME 레이블이 붙습니다. 한 가지 가능한 설명은 간단히 다항식 SVC가 내 작업에 사용할 적절한 분류자가 아니라는 것입니다. 나는 단지 내가 다항식 SVC를 적절히 사용하고 있는지 확인하고 싶다.

도움/조언을 주셔서 감사합니다. 답변에 주어진 권고에 따라

UPDATE , 나는 다음을 수행 분류기를 훈련 코드 변경했습니다 : 이제

# Train the appropriate supervised model 
parameters = [{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['poly'], 'degree': [2]}] 
self.classifier = GridSearchCV(SVC(C=1), parameters, score_func = f1_score) 

을 나는 다음과 같은 메시지가 얻을 :

ValueError: The least populated class in y has only 1 members, which is too few. The minimum number of labels for any class cannot be less than k=3. 

이것은 교육 데이터에 클래스 인스턴스의 균등 분포와 관련이 있습니다. 맞습니까? 아니면 프로 시저를 잘못 호출하고 있습니까?

+0

그건 그렇고, GridSearchCV에 대한 매우 유용한 매개 변수는'n_jobs'입니다 - 기본적으로'1'입니다. 그리드를 빠르게 탐색 할 수있는 CPU 수 (또는 원하는대로)를 병렬로 설정하십시오. – JDonner

답변

4

두 경우 모두 grid search을 사용하여 정규화 매개 변수 C의 값을 조정해야합니다. 그렇지 않은 경우에는 결과를 비교할 수 없으므로 다른 모델에 대한 결과가 좋지 않을 수 있습니다.

다항식 커널의 경우 학위 (예 : 2 또는 3 이상)에 대한 최적 값을 그리드 검색 할 수도 있습니다.이 경우 C와 Degree를 동시에 검색해야합니다.

편집 :

이 바로 내 훈련 데이터의 클래스의 인스턴스의 불균등 분포를 함께 할 수있는 뭔가가? 아니면 프로 시저를 잘못 호출하고 있습니까? 당신은 클래스 당 최소 3 개 샘플을

확인이 k == 3StratifiedKFold 교차 검증을 할 수 있도록 (나는이 분류에 GridSearchCV에서 사용하는 기본 CV라고 생각합니다). 당신이 덜 가지고 있다면 모델이 유용한 것을 예측할 수 있다고 기대하지 마라. 클래스 당 최소 100 개 샘플을 추천합니다 (10 개 미만의 피쳐로 장난감 문제를 해결하고 클래스 간의 의사 결정 경계에서 많은 규칙 성을 갖지 않는 한 임의의 엄지 최소 법칙으로 권장).

나는 항상 질문/버그 보고서에 전체 추적을 붙여 넣으십시오. 그렇지 않으면 올바른 원인을 진단하는 데 필요한 정보가 없을 수 있습니다.

+0

+1. 그리드 검색에서 C를 찾습니다. 2보다 높은 도수를 사용하면 NLP 설정에서 지나치게 조급하게됩니다 (또는 말한 적이 있습니다). –

+0

도움 주셔서 감사.나는 지금 일어난 일로 질문을 갱신했다. – feralvam