我试图将RandomForest
方法应用于数据集,但出现以下错误:
ValueError: Input contains NaN, infinity or a value too large for dtype ('float32')
有人能告诉我,为了让代码正常工作,我可以在函数中修改哪些内容:
def ranks_RF(x_train, y_train, features_train, RESULT_PATH='Results'):
"""Get ranks from Random Forest"""
print("\nMétodo_Random_Forest")
random_forest = RandomForestRegressor(n_estimators=10)
np.nan_to_num(x_train)
np.nan_to_num(y_train)
random_forest.fit(x_train, y_train)
# Get rank by doing two times a sort.
imp_array = np.array(random_forest.feature_importances_)
imp_order = imp_array.argsort()
ranks = imp_order.argsort()
# Plot Random Forest
imp = pd.Series(random_forest.feature_importances_, index=x_train.columns)
imp = imp.sort_values()
imp.plot(kind="barh")
plt.xlabel("Importance")
plt.ylabel("Features")
plt.title("Feature importance using Random Forest")
# plt.show()
plt.savefig(RESULT_PATH + '/ranks_RF.png', bbox_inches='tight')
return ranks
替换nan时没有覆盖这些值,因此它会给您带来错误
我们尝试一个示例数据集:
我们有一个类似于你的函数,我删除了绘图部分,因为这完全是另一个问题:
我们运行它:
相关问题 更多 >
编程相关推荐