gpt4 book ai didi

python - 为什么我的 Python RandomForestRegressor 不能准确预测训练集数据?

转载 作者:行者123 更新时间:2023-11-28 19:17:16 25 4
gpt4 key购买 nike

我正在学习机器学习,我想使用 scikit-learn 的 RandomForestRegressor() 在相当复杂的数据集上。不过,为了首先掌握它的窍门,我正在尝试完成一个基本示例,如下所示:

import sklearn.ensemble as se
import numpy as np
forest = se.RandomForestRegressor(n_estimators=1000)
traindata = np.arange(1000).reshape(200,5)
forest = forest.fit(traindata[0::,1::],traindata[0::,0])

此时,我认为我所做的是:我创建了一个 200 行矩阵,每行 5 个值,格式为 [ x, x+1, x+2, x+3, x+4 ]其中 x是 5 的倍数(例如 [0,1,2,3,4][5,6,7,8,9] 等)。

我已经告诉我的森林适合这些特征 [ x+1, x+2, x+3, x+4 ]预测 x 。以下是我预测时会发生的情况:

forest.predict([1,2,3,4])
>> array([2.785])

这对我来说真的很不直观。考虑 [1,2,3,4] 的特征值在 x = 0 的训练数据中,我的森林难道不能比 2.785 更准确地预测它吗?

我更进一步看到特征重要性如下:

forest.feature_importances_
>> array([0.26349716, 0.23664264, 0.23360533, 0.26625487])

对我来说,这并不意味着我所看到的方式存在重大偏差。我在这里错过了什么?

最佳答案

为什么预测不准确?

简短版本:由于聪明的 Breiman 提出的方法的性质。

更长的版本:

随机森林是非常有趣的学习器。

但是,您需要一点耐心才能调整它们。

forest.setp_param( oob_score    = True,   # set True to be able to read
# # oob-samples score
random_state = 2015 # set so as to keep retesting
# # possible / meaniningfull on
# # an otherwise randomised
# # learner construction
)

原则上,任何尝试使用 .fit() 方法在幕后做了很多工作来构建一组随机的决策树,使其成为适用于您的数据集的 RandomForest。

的“质量.fit() 表示在 .oob_score_ 这显示了已经使用的 oob 的(准确)程度。 -samples(Breiman 方法的真实部分)在针对给定的 完成训练后 RandomForest 。这有助于您估计您受过训练的 RandomForest 如何“”或“”在可用数据集上执行。

然而,更重要的是(或应该是)学习者的概括能力——即,一旦处理了一个看不见的例子,它的预测能力与现实的吻合程度如何。

这个可以通过 .score()测试 训练有素的方法 RandomForest -实例。

RandomForest 是一个“多数投票”预测器,要感受这一点,请尝试显示随机树大军的内部状态:

def printLDF( aPopulationSET ):
LDF_example, LDF_counts = np.unique( aPopulationSET, return_counts = True )
GDF_sum_scaler = float( LDF_counts.sum() )
for i in xrange( LDF_example.shape[0] ):
print "{0: > 6d}: {1: > 6d} x {2: > 15.2f} {3: > 15.4f} % {4: > 15.1f} %".format( i, LDF_counts[i], LDF_example[i], 100 * LDF_counts[i] / GDF_sum_scaler, 100 * LDF_counts[:i].sum() / GDF_sum_scaler )
return

>>> printLDF( forest.estimators_[:].predict( anExample ) )

这将向您显示单个树的预测,用于整个基于森林的预测的多数票计算。

这意味着,除此之外, RandomForest 原则上永远不会预测训练中存在的“访问”值范围“之外”的值(不能通过设计“推断”)。

如何让它变得更好?

嗯,特征工程是关键。如果您知道 RandomForest 是您案例的可行学习器,并且您觉得它观察到的预测能力很差,那么首先要归咎于特征选择。

检查森林

检查学习者的内部状态——检查森林中的树木做了什么:

您可能会通过以下方式更深入地了解模型:

def prediction_up_dn_intervals( aPredictorMODEL,                        # >>> http://blog.datadive.net/prediction-intervals-for-random-forests/
X_, # aStateVECTOR: X_sampled
aPredictorOutputIDX = 0, # (4,2,2) -> singleQUAD ( LONG.TP/SL, SHORT.TP/SL ) <-- idxMAP( 'LONG', 'TP', 1 )
aRequiredPercentile = 95
):
err_dn = []
err_up = []
#-----------------------------------------------------------------------------------------------
if len( X_.shape ) == 1: # for a single X_example run
preds = []
for pred in aPredictorMODEL.estimators_:
preds.append( pred.predict( X_ )[0,aPredictorOutputIDX] ) # de-array-ification

err_dn.append( np.percentile( preds, ( 100 - aRequiredPercentile ) / 2. ) )
err_up.append( np.percentile( preds, 100 - ( 100 - aRequiredPercentile ) / 2. ) )
else:
#------------------------------------------------------------------------------------------
for x in xrange( len( X_ ) ): # for a multi X_example run
preds = []
for pred in aPredictorMODEL.estimators_:
preds.append( pred.predict( X_[x] )[0,aPredictorOutputIDX] ) # de-array-ification

err_dn.append( np.percentile( preds, ( 100 - aRequiredPercentile ) / 2. ) )
err_up.append( np.percentile( preds, 100 - ( 100 - aRequiredPercentile ) / 2. ) )
#-----------------------------------------------------------------------------------------------
return err_up, err_dn

#numba.jit( 'f8(<<OBJECT>>,f8[:,:],f8[:,:],i8,f8)' ) # <<OBJECT>> prevents JIT
def getPredictionsOnINTERVAL( aPredictorENGINE, # a MULTI-OBJECTIVE PREDICTOR -> a singleQUAD or a full 4-QUAD (16,0) <-(4,2,2)
X_,
y_GndTRUTH, # (4,2,2) -> (16,0) a MULTI-OBJECTIVE PREDICTOR
aPredictionIDX = 0, # (4,2,2) -> singleQUAD ( LONG.TP/SL, SHORT.TP/SL ) <-- idxMAP( 'LONG', 'TP', 1 )
percentile = 75
):
"""
|>>> getPredictionsOnINTERVAL( loc_PREDICTOR, X_sampled, y_sampled, idxMAP( "LONG", "TP", 1 ), 75 ) 1.0 +0:01:29.375000
|>>> getPredictionsOnINTERVAL( loc_PREDICTOR, X_sampled, y_sampled, idxMAP( "LONG", "TP", 1 ), 55 ) 0.9992532724237898 +0:03:59.922000
|>>> getPredictionsOnINTERVAL( loc_PREDICTOR, X_sampled, y_sampled, idxMAP( "LONG", "TP", 1 ), 50 ) 0.997100939998243 +0:09:16.328000
|>>> getPredictionsOnINTERVAL( loc_PREDICTOR, X_sampled, y_sampled, idxMAP( "LONG", "TP", 1 ), 5 ) 0.31375735746288325 +0:01:16.422000
"""
correct_on_interval = 0 # correct = 0. ____________________- faster to keep asINTEGER ... +=1 and only finally make DIV on FLOAT(s) in RET
#ruth = y_ # Y[idx[trainsize:]]
err_up, err_dn = prediction_up_dn_intervals( aPredictorENGINE, # ( rf,
X_, # X[idx[trainsize:]],
aPredictionIDX, # idxMAP( "LONG", "TP", 1 ),
percentile # percentile = 90
) # )

#-------------------------------------------------------------------# for a single X_ run
if ( len( X_.shape ) == 1 ):
if ( err_dn[0] <= y_GndTRUTH[aPredictionIDX] <= err_up[0] ):
return 1.
else:
return 0.
#-------------------------------------------------------------------# for a multi X_ run
for i, val in enumerate( y_GndTRUTH[:,aPredictionIDX] ): # enumerate( truth )
if err_dn[i] <= val <= err_up[i]:
correct_on_interval += 1
#-------------------------------------------------------------------
return correct_on_interval / float( y_GndTRUTH.shape[0] ) # print correct / len( truth )

def mapPredictionsOnINTERVAL( aPredictorENGINE, #
X_,
y_GndTRUTH,
aPredictionIDX = 0,
aPercentilleSTEP = 5
):
for aPercentille in xrange( aPercentilleSTEP, 100, aPercentilleSTEP ):
Quotient = getPredictionsOnINTERVAL( aPredictorENGINE, X_, y_GndTRUTH, aPredictionIDX, aPercentille )
print "{0: > 3d}-percentil {1: > 6.3f} %".format( aPercentille, 100 * Quotient )
"""
5% 0.313757
10% 0.420847
15% 0.510191
20% 0.628481
25% 0.719758
30% 0.839058
35% 0.909646
40% 0.963454
45% 0.986603
50% 0.997101
55% 0.999253
60% 0.999912
65% 1.000000 >>> RET/JIT
70% 1.000000 xxxxxxxxxxxxxx
75% 1.000000 xxxxxxxxxxxxxx ???? .fit( X_, y_[:,8:12] ) # .fit() on HORIZON-T0+3???? ... y_GndTRUTH.shape[1] v/s .predict().shape[1]
"""
if ( Quotient == 1 ):
return

关于python - 为什么我的 Python RandomForestRegressor 不能准确预测训练集数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com