2017-12-19 7 views
1

나는이 단순화 될 수있다 Dataframe 있습니다여러 데이터 프레임 열에 대한 파이프 라인을 만드는 방법은 무엇입니까?

import pandas as pd 

df = pd.DataFrame([{ 
'title': 'batman', 
'text': 'man bat man bat', 
'url': 'batman.com', 
'label':1}, 
{'title': 'spiderman', 
'text': 'spiderman man spider', 
'url': 'spiderman.com', 
'label':1}, 
{'title': 'doctor evil', 
'text': 'a super evil doctor', 
'url': 'evilempyre.com', 
'label':0},]) 

을 그리고 다른 특징 추출 방법을 시도하려는 : 등 TFIDF, 다른 N- 그램 설정을 word2vec, Coutvectorizer을, 그러나 나는 다른 조합을 시도 할 : 하나의 기능 세트는 TFIDF로 변환 된 '텍스트'데이터를 포함 할 것이며, 'url'은 Countvectoriser로, 두 번째는 텍스트 데이터를 w2v로 변환하고, 'url'은 TFIDF로 변환합니다. 결국, 나는 다양한 전처리 전략을 비교하고 최선의 전략을 선택하기를 원한다.

  1. 파이프 라인 같은 표준 sklearn 도구를 사용하여 같은 일을 할 수있는 방법이 있나요 :

    그리고 여기이 질문입니까?

  2. 내 아이디어에는 상식이 있습니까? 어쩌면 내가 누락 된 데이터 프레임의 여러 열을 사용하여 텍스트 데이터를 처리하는 좋은 아이디어가 있을까요?

많은 감사!

답변

1

@elphz 대답은 FeatureUnionFunctionTransformer을 어떻게 사용했는지에 대한 좋은 소개입니다.하지만 조금 더 자세하게 설명해 드리겠습니다.

먼저 입력 데이터를 올바르게 처리하고 처리 할 수 ​​있도록 FunctionTransformer 함수를 정의해야한다고 말합니다. 이 경우에는 DataFrame을 전달하기를 원하지만, 다운 스트림에 사용할 수 있도록 제대로 배열 된 배열을 반환해야합니다. 따라서 DataFrame 만 전달하고 열 이름으로 액세스 할 것을 제안합니다. 이와 같이 :

def text(X): 
    return X.text.values 

def title(X): 
    return X.title.values 

pipe_text = Pipeline([('col_text', FunctionTransformer(text, validate=False))]) 

pipe_title = Pipeline([('col_title', FunctionTransformer(title, validate=False))]) 

이제 변압기와 분류기의 변형을 테스트 해보십시오. 저는 변압기 목록과 분류기 목록을 사용하여 그리드 검색과 마찬가지로 간단하게 반복 할 것을 제안합니다.

tfidf = TfidfVectorizer() 
cv = CountVectorizer() 
lr = LogisticRegression() 
rc = RidgeClassifier() 

transformers = [('tfidf', tfidf), ('cv', cv)] 
clfs = [lr, rc] 

best_clf = None 
best_score = 0 
for tran1 in transformers: 
    for tran2 in transformers: 
     pipe1 = Pipeline(pipe_text.steps + [tran1]) 
     pipe2 = Pipeline(pipe_title.steps + [tran2]) 
     union = FeatureUnion([('text', pipe1), ('title', pipe2)]) 
     X = union.fit_transform(df) 
     X_train, X_test, y_train, y_test = train_test_split(X, df.label) 
     for clf in clfs: 
      clf.fit(X_train, y_train) 
      score = clf.score(X_test, y_test) 
      if score > best_score: 
       best_score = score 
       best_est = clf 

이것은 간단한 예이지만이 방법으로 다양한 변형과 ​​분류기를 어떻게 플러그인 할 수 있는지 확인할 수 있습니다.

1

FunctionTransformer를 조합하여 특정 열만 선택한 다음 FeatureUnion을 사용하여 각 열에 TFIDF, 단어 수 등의 기능을 결합했습니다. 약간 더 깔끔한 방법이있을 수 있지만, 필자는 어떤 종류의 FeatureUnion과 Pipeline 중첩을 고려해도 상관 없다고 생각합니다.

from sklearn.preprocessing import FunctionTransformer 
from sklearn.pipeline import FeatureUnion, Pipeline 
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer 

def first_column(X): 
    return X.iloc[:, 0] 

def second_column(X): 
    return X.iloc[:, 1] 

# pipeline to get all tfidf and word count for first column 
pipeline_one = Pipeline([ 
    ('column_selection', FunctionTransformer(first_column, validate=False)), 
    ('feature-extractors', FeatureUnion([('tfidf', TfidfVectorizer()), 
             ('counts', CountVectorizer()) 

    ])) 
]) 

# Then a second pipeline to do the same for the second column 
pipeline_two = Pipeline([ 
    ('column_selection', FunctionTransformer(second_column, validate=False)), 
    ('feature-extractors', FeatureUnion([('tfidf', TfidfVectorizer()), 
             ('counts', CountVectorizer()) 

    ])) 
]) 


# Then you would again feature union these pipelines 
# to get different feature selection for each column 
final_transformer = FeatureUnion([('first-column-features', pipeline_one), 
            ('second-column-feature', pipeline_two)]) 

# Your dataframe has your target as the first column, so make sure to drop first 
y = df['label'] 
df = df.drop('label', axis=1) 

# Now fit transform should work 
final_transformer.fit_transform(df) 

각 열 (TFIDF 및 카운트 둘 가능성이 유용하지 않을 것이다) 당신이 한 단계 중첩을 줄일 수있는 여러 변압기를 적용하지 않는 경우

.

+0

답변 해 주셔서 감사합니다. 그러나 텍스트 데이터에서는 작동하지 않는 것으로 보입니다. 값 오류 : 문자열을 부동으로 변환 할 수 없습니다. 예제 데이터 세트로 시도해 볼 수 있습니까? –

+1

네, FunctionTransformer에'validate = False'를 추가하여 숫자 데이터를 확인하지 않아야 할 것 같습니다. 대상 변수를 삭제하고 열 선택 기능을 데이터 프레임과 함께 작동하도록 변경해야했지만 데이터 세트로 테스트 한 결과 현재 작동하고 있다고 생각합니다. 위의 모든 수정 사항으로 업데이트했습니다. – elphz