python中的多随机回归模型

在 X_train 集和 Y_train 标签上构建多个随机森林回归器,其中 max_depth 参数值从 3 变为 5,并将 n_estimators 设置为 50、100、200 值之一。


在测试数据集上评估每个模型的准确性。


提示:使用 for 循环以最高精度打印模型的 max_depth 和 n_estimators 值。


注意:以元组(a,b)的形式打印参数值。a 指的是 max_depth 值,b 指的是 n_estimators


到目前为止,这是我尝试过的:


boston= datasets.load_boston()

X_train, X_test, Y_train, Y_test = train_test_split(boston.data, boston.target, random_state=30)

for m in range(3,6) :

    rf_reg = RandomForestRegressor(n_estimators =100, max_depth=m)

    rf_reg = rf_reg.fit(X_train, Y_train) 

    print(rf_reg.score(X_test,Y_test))

这给了我 3 个模型的准确度分数,但我无法单独获取最高精度的参数。我可以使用rf_reg.get_params(),但它给了我所有的参数。我只想要max_depth和n_estimators最高分的一个


缥缈止盈
浏览 164回答 4
4回答

狐的传说

max_reg = None&nbsp; #<--- add this to represent the regressor with maximum scoremax_score = 0&nbsp; &nbsp;#<--- add this to represent maximum scoret=() # <--- add this to tuple declarationc_estimators = 100&nbsp;for m in range(3,6) :&nbsp; &nbsp; rf_reg = RandomForestRegressor(n_estimators =c_estimators , max_depth=m)&nbsp; &nbsp; rf_reg = rf_reg.fit(X_train, Y_train)&nbsp;&nbsp; &nbsp; rf_reg_score = rf_reg.score(X_test,Y_test)&nbsp; &nbsp; t = (m,c_estimators,rf_reg.score) # tuple assignment&nbsp; &nbsp; rf_reg_score = t[2]&nbsp; &nbsp; print (t)&nbsp; &nbsp; if rf_reg_score > max_score :&nbsp; &nbsp; &nbsp; &nbsp; max_score = rf_reg_score&nbsp; &nbsp; &nbsp; &nbsp; max_reg = rf_reg&nbsp; &nbsp; &nbsp; &nbsp; t = (m,c_estimators) # tuple assignmentprint (t)

千巷猫影

您将获得 (5, 100) 组合的 max_score。根据问题,他们要求执行总共 9 种组合。3×3。

www说

如何以元组 (a, b) 的形式打印参数值。a 指的是 max_depth 值,b 指的是 n_estimators

冉冉说

import sklearn.datasets as datasetsimport sklearn.model_selection as model_selectionimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressornp.random.seed(100)boston=datasets.load_boston()X_train,X_test,Y_train,Y_test=train_test_split(boston.data,boston.target,random_state=30)print(X_train.shape)print(X_test.shape)rf_reg = RandomForestRegressor()rf_reg = rf_reg.fit(X_train, Y_train)print(rf_reg.score(X_train,Y_train))print(rf_reg.score(X_test,Y_test))print(rf_reg.predict(X_test[0:2]))li=[]nestimators=100for maxdepth in range(3,6) :&nbsp; &nbsp; rf_reg1 = RandomForestRegressor(max_depth=maxdepth,n_estimators=nestimators)&nbsp; &nbsp; rf_reg1 = rf_reg1.fit(X_train, Y_train)&nbsp;&nbsp;&nbsp; &nbsp; li.append(rf_reg1.score(X_test,Y_test))maxValue=max(li)maxIndex=li.index(maxValue)a=(maxIndex+3,nestimators)print(a)#This code 100% works ,i tested and got exact output and cleared HandsOn
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python