使用列表填充数据框以获取最低平均绝对误差的max_leaf_nodes

我创建了一个简单的DecisionTreeRegressor,并希望找到最佳的max_leaf_nodes值。

代码:

from sklearn.metrics import mean_absolute_error as MAEfrom sklearn.model_selection import train_test_split as TTS#将数据分为两部分:训练数据和验证数据train_X, val_X, train_y, val_y = TTS(X, y, random_state=0)#定义并使用训练数据拟合模型model = DecisionTreeRegressor(random_state=1)model.fit(train_X, train_y)#预测val_prediction = model.predict(val_X)#检查预测print(MAE(val_prediction, val_y))#定义get_mae函数def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)    model.fit(train_X, train_y)    preds_val = model.predict(val_X)    mae = mean_absolute_error(val_y, preds_val)    return(mae)#数据框和列表df_mae = pd.DataFrame(columns = ["MAE"])li = []#根据max_leaf_nodes值收集maefor max_leaf_nodes in range(2, 10000, 2):    mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)    li.append(mae)    

我如何将li的值添加到df_mae的”MAE”列中?

有没有更好的方法来找到好的max_leaf_nodes?(我的笔记本电脑运行这个for循环花了25分钟)


回答:

你可以直接在数据框中添加一行,而不是先创建一个列表。

df_mae = df_mae.append({'MAE': mae}, ignore_index = True)

然而,如果你更喜欢添加列表而不是单个值(在for循环之外):

df_mae = df_mae.append(pd.DataFrame({'MAE': li}), ignore_index = True)

请注意,你需要同时存储max_leaf_nodes,否则你的结果数据框将没有意义。

df_mae = pd.DataFrame(columns = ["MAE", "max_leaf_nodes"])li = []max_leaf_nodes_list = []for max_leaf_nodes in range(2, 10000, 2):    mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)    li.append(mae)    max_leaf_nodes_list.append(max_leaf_nodes)df_mae = df_mae.append(pd.DataFrame({'MAE': li, 'max_leaf_nodes': max_leaf_nodes_list}), ignore_index = True)

或者,直接将值添加到数据框中:

df_mae = pd.DataFrame(columns = ["MAE", "max_leaf_nodes"])for max_leaf_nodes in range(2, 10000, 2):    mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)    df_mae = df_mae.append({'MAE': mae, 'max_leaf_nodes': max_leaf_nodes}, ignore_index = True)

为了减少这种方法的执行时间,我建议将range函数中的步长从2增加到一个更大的数字。一旦你找到了产生最佳值的区间,你可以限制区间来找到更好的指标。换句话说,搜索整个超参数网格并不是最佳方法。

或者,你可以使用其他方法,如HyperoptHyperopt-sklearn

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注