2017-04-13 2 views
1

sklearn.model_selection.permutation_test_score와 sklearn.metrics.r2_score에 의해 계산 된 r2 점수 사이에 상당한 불일치가 있습니다. permutation_test_score에 의해 계산 된 값이 올바르지 않은 것 같습니다. 아래 참조 :sklearn.model_selection.permutation_test_score에 의해 계산 된 잘못된 r2 점수

import numpy as np 
from sklearn.linear_model import LinearRegression 
from sklearn.metrics import r2_score 
from sklearn.model_selection import permutation_test_score 

x=np.arange(1,6,1) 
x=np.reshape(x,(5,1)) 
y=np.array([1.9, 3.7, 5.8, 8.0, 9.6]) 
y=np.reshape(y,(5,1)) 

# fit a line to the data 
lin_reg = LinearRegression() 
lin_reg.fit(x, y) 
print lin_reg.intercept_,lin_reg.coef_ 
# 1.97 -0.11 

# Compute the prediction values (f) from our fitted line 
f=lin_reg.predict(x) 
print f 
# [[ 1.86] 
# [ 3.83] 
# [ 5.8 ] 
# [ 7.77] 
# [ 9.74]] 

# Calculate R^2 explicitly 
yminusf2=(y-f)**2 
sserr=sum(yminusf2) 
mean=float(sum(y))/float(len(y)) 
yminusmean2=(y-mean)**2 
sstot=sum(yminusmean2) 
R2=1.-(sserr/sstot) 
print R2 
# 0.99766067 

# Use sklearn.metrics.r2_score 
print r2_score(y,f) 
# 0.99766066838 
print r2_score(y,f) == R2 
# [ True] 

# Use sklearn.model_selection.permutation_test_score 
r2_sc, perm_sc, pval = permutation_test_score(lin_reg,x,y, n_permutations = 100, scoring = 'r2', cv =None) 
print r2_sc 
# 0.621593653548 
print r2_sc ==R2 
# [False] 

답변

1

예. 전체 데이터에 대한 점수를 얻고 있습니다 (예 : x에 적합하고 동일하게 예측). 따라서 R2 및 r2_score()가 매우 높습니다. 그러나 질문에 대해서는 permutation_test_score()이 전체 데이터에 대한 점수를 계산하지는 않지만 교차 유효성 확인 기술을 사용하고 모든 폴드에 대해 얻은 평균 점수를 출력하기 때문에 다릅니다.

주목하라 permutation_test_score()도 지정되지 않거나 것도없는 경우 파라미터 cv을 가지고, 3 배의 교차 검증 디폴트 (KFold 동일 (3)) specified in the documentation로서 :

CV : INT ,

Determines the cross-validation splitting strategy. Possible inputs for cv are: 
     - None, to use the default 3-fold cross validation, 
     - integer, to specify the number of folds in a (Stratified)KFold, 
     - An object to be used as a cross-validation generator. 
     - An iterable yielding train, test splits. 

옵션 교차 검증 발생기 또는 반복자는, 그래서, permutation_test_score에 의해 반환 된 점수는 교차 검증에 의해 얻은 모든 점수의 평균입니다.

각 배의 점수를 반환 cross_val_score를 사용하여이 시나리오를 테스트 할 수 있습니다

from sklearn.model_selection import cross_val_score 
r2_sc_cv = cross_val_score(lin_reg,x,y, scoring = 'r2', cv =None) 
print r2_sc_cv 
# array([ 0.91975309, 0.94502787, 0.  ]) 

r2_sc_cv_mean = np.average(r2_sc_cv) 
print r2_sc_cv_mean 
# 0.62159365354781015 

print r2_sc_cv_mean == r2_sc 
# True 

r2_sc_cv 배열의 마지막 배의 점수를 참조하십시오. 그 0.0. 그래서 평균 점수가 내려갑니다.