-1

我知道这是一个非常经典的问题,可以在这个论坛中多次回答,但是我找不到任何明确的答案,从头开始清楚地解释这个问题。构建一个随机森林回归器,从头开始进行交叉验证

首先,我的数据集名为my_data有4个变量,如 my_data =变量1,变量2,variable3 imgine,target_variable

那么,让我们来我的问题。我会解释我的所有步骤,并要求你对我一直停留在那里帮助:

# STEP1 : split my_data into [predictors] and [targets] 

predictors = my_data[[ 
'variable1', 
'variable2', 
'variable3' 
]] 


targets = my_data.target_variable 

# STEP2 : import the required libraries 

from sklearn import cross_validation 
from sklearn.ensemble import RandomForestRegressor 

#STEP3 : define a simple Random Forest model attirbutes 

model = RandomForestClassifier(n_estimators=100) 


#STEP4 : Simple K-Fold cross validation. 3 folds. 

cv = cross_validation.KFold(len(my_data), n_folds=3, random_state=30) 

# STEP 5 

在这一步,我想基于训练数据集,以适应我的模型,然后 使用的测试模型数据集并预测测试目标。我也想计算所需的统计数据,如MSE,R2等,以了解我的模型的性能。

如果有人帮助我提供Step5的一些基本代码行,我将不胜感激。

感谢&问候,

Cagdas

回答

0

首先,你正在使用scikit库的过时包cross-validation。新包名为model_selection。所以我在这个答案中使用了它。

其次,您正在导入RandomForestRegressor,但在代码中定义了RandomForestClassifier。我在这里采取RandomForestRegressor,因为你想要的度量(MSE,R2等)只是为回归问题定义的,而不是分类。

有多种方法可以做你想做的。我假设,因为您试图在此处使用KFold交叉验证,所以您希望使用每个折叠的剩余数据作为测试折叠。要做到这一点,我们可以这样做:

predictors = my_data[[ 
'variable1', 
'variable2', 
'variable3' 
]] 


targets = my_data.target_variable 

from sklearn import model_selection 
from sklearn.ensemble import RandomForestRegressor 
from sklearn import metrics 

model = RandomForestClassifier(n_estimators=100) 

cv = model_selection.KFold(n_splits=3) 

for train_index, test_index in kf.split(X): 
    print("TRAIN:", train_index, "TEST:", test_index) 
    X_train, X_test = predictors[train_index], predictors[test_index] 
    y_train, y_test = targets[train_index], targets[test_index] 

    # For training, fit() is used 
    model.fit(X_train, y_train) 

    # Default metric is R2 for regression, which can be accessed by score() 
    model.score(X_test, y_test) 

    # For other metrics, we need the predictions of the model 
    y_pred = model.predict(X_test) 

    metrics.mean_squared_error(y_test, y_pred) 
    metrics.r2_score(y_test, y_pred) 

对于所有这些,文档是您最好的朋友。 scikit学习文档是我见过的最好的之一。以下链接可以帮助你了解他们更多: