특이 치를 찾기 위해 IsolationForest와 함께 GridSearchCV 사용


10

IsolationForest특이 치를 찾는 데 사용하고 싶습니다 . 모델에 가장 적합한 매개 변수를 찾고 싶습니다 GridSearchCV. 문제는 항상 같은 오류가 발생한다는 것입니다.

TypeError: If no scoring is specified, the estimator passed should have a 'score' method. The estimator IsolationForest(behaviour='old', bootstrap=False, contamination='legacy',
                max_features=1.0, max_samples='auto', n_estimators=100,
                n_jobs=None, random_state=None, verbose=0, warm_start=False) does not.

방법 IsolationForest이 없기 때문에 문제가있는 것 같습니다 score. 이 문제를 해결하는 방법이 있습니까? 또한 격리 포리스트에 대한 점수를 찾는 방법이 있습니까? 이것은 내 코드입니다.

import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import GridSearchCV

df = pd.DataFrame({'first': [-112,0,1,28,5,6,3,5,4,2,7,5,1,3,2,2,5,2,42,84,13,43,13],
                   'second': [42,1,2,85,2,4,6,8,3,5,7,3,64,1,4,1,2,4,13,1,0,40,9],
                   'third': [3,4,7,74,3,8,2,4,7,1,53,6,5,5,59,0,5,12,65,4,3,4,11],
                   'result': [5,2,3,0.04,3,4,3,125,6,6,0.8,9,1,4,59,12,1,4,0,8,5,4,1]})

x = df.iloc[:,:-1]

tuned = {'n_estimators':[70,80,100,120,150,200], 'max_samples':['auto', 1,3,5,7,10],
         'contamination':['legacy', 'outo'], 'max_features':[1,2,3,4,5,6,7,8,9,10,13,15],
         'bootstrap':[True,False], 'n_jobs':[None,1,2,3,4,5,6,7,8,10,15,20,25,30], 'behaviour':['old', 'new'],
         'random_state':[None,1,5,10,42], 'verbose':[0,1,2,3,4,5,6,7,8,9,10], 'warm_start':[True,False]}

isolation_forest = GridSearchCV(IsolationForest(), tuned)

model = isolation_forest.fit(x)

list_of_val = [[1,35,3], [3,4,5], [1,4,66], [4,6,1], [135,5,0]]
df['outliers'] = model.predict(x)
df['outliers'] = df['outliers'].map({-1: 'outlier', 1: 'good'})

print(model.best_params_)
print(df)

당신 의 점수를 위해 당신의 선택은 무엇입니까 ? 정확성? MSE? 또한 보고 된 오류 이후 에 오는 모든 코드를 제거하십시오 (실행되지 않으므로 질문과 관련이 없습니다-불필요한 혼란을 유발합니다).
desertnaut 2009 년

정확성 점수를 원합니다. 질문과 관련이없는 코드를 제거했습니다.
taga

답변:


9

메소드가 내장되어 IsolationForest있지 않으므로 자체 스코어링 함수를 작성해야합니다 score. 대신에 사용할 수있는 score_samples기능 IsolationForest(프록시로 간주 될 수 있음 score)을 사용 하고 여기에 설명 된대로 자체 스코어러를 만들어에 전달할 수 GridSearchCV있습니다. 이 작업을 수행하기 위해 코드를 수정했습니다.

import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import GridSearchCV

df = pd.DataFrame({'first': [-112,0,1,28,5,6,3,5,4,2,7,5,1,3,2,2,5,2,42,84,13,43,13],
                   'second': [42,1,2,85,2,4,6,8,3,5,7,3,64,1,4,1,2,4,13,1,0,40,9],
                   'third': [3,4,7,74,3,8,2,4,7,1,53,6,5,5,59,0,5,12,65,4,3,4,11],
                   'result': [5,2,3,0.04,3,4,3,125,6,6,0.8,9,1,4,59,12,1,4,0,8,5,4,1]})

x = df.iloc[:,:-1]

tuned = {'n_estimators':[70,80], 'max_samples':['auto'],
     'contamination':['legacy'], 'max_features':[1],
     'bootstrap':[True], 'n_jobs':[None,1,2], 'behaviour':['old'],
     'random_state':[None,1,], 'verbose':[0,1,2], 'warm_start':[True]}  

def scorer_f(estimator, X):   #your own scorer
      return np.mean(estimator.score_samples(X))

#or you could use a lambda aexpression as shown below
#scorer = lambda est, data: np.mean(est.score_samples(data)) 

isolation_forest = GridSearchCV(IsolationForest(), tuned, scoring=scorer_f)
model = isolation_forest.fit(x)

샘플 출력

print(model.best_params_)

{'behaviour': 'old',
 'bootstrap': True,
 'contamination': 'legacy',
 'max_features': 1,
 'max_samples': 'auto',
 'n_estimators': 70,
 'n_jobs': None,
 'random_state': None,
 'verbose': 1,
 'warm_start': True}

도움이 되었기를 바랍니다!


그리고없이 이것을 할 수있는 방법이 lambda있습니까?
taga

lambda위에 표시된 것처럼 표현식을 함수로 바꿀 수 있습니다.
Parthasarathy Subburaj

고마워 친구,이 질문 좀 도와 주시겠습니까? stackoverflow.com/questions/58214457/…
taga

-1

점수 매기기는 IsolationForest가 아닌 GridSearchCV 객체를 참조한다고 생각합니다.

"None"(기본값) 인 경우 추정치 점수를 사용하려고 시도합니다. GridSearchCV 오브젝트 내에서 문제점에 적합한 사용 가능한 스코어링 메트릭 중 하나를 사용하십시오.


이것을 보여주는 코드를 게시 할 수 있습니까? 현재 솔루션에이 기능이 없습니다
ConorL

문제는 내가 그래서 y_true을 넣어 방법 및 y_pred 없다, 그 절연 숲 자율 생각이다
타가는
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.