首页 > 解决方案 > For循环不断让jupyter卡住

问题描述

我是数据分析和python的新手,在课堂上,我们正在制作一个for循环来检查随机森林中的不同无树并找出最准确的树,我们的老师给我们分配了一个for循环来实现这一点,但是我写的代码使笔记本卡住并且没有输出,有人可以告诉我我的代码有什么问题吗?就像,我终于得到了答案,但经过很长时间,谁能告诉我如何在不改变范围的情况下更有效地做同样的事情?

accuracy_scores = []
for i in range(50,500,10):
    model_random = RandomForestClassifier(n_estimators=i,criterion="entropy",max_features=10,min_samples_leaf=50)
    model_random.fit(X_train,Y_train)
    Y_pred=model_random.predict(X_test)
    accuracy=round(accuracy_score(Y_pred, Y_test)*100,2)
    accuracy_scores.append(accuracy)
print(max(accuracy_scores))
y=accuracy_scores.index(max(accuracy_scores))*10+50
print(y)

标签: pythonfor-looprandom-forest

解决方案


for 循环是正确的。我假设您的 RandomForestClassifier 函数需要一些时间来计算。

我的建议是添加一些打印/记录器语句,以查看花费最多时间的位置和内容。

from time import per_counter

for i in range(50, 500, 10):
    start = perf_counter()
    model_random = RandomForestClassifier(n_estimators=i,criterion="entropy",max_features=10,min_samples_leaf=50)
    calc_time = perf_counter() - start
    print(f"RandomForestClassifier took {calc_time:.2f}")
    Y_pred=model_random.predict(X_test)
    accuracy=round(accuracy_score(Y_pred, Y_test)*100,2)
    accuracy_scores.append(accuracy)

print(max(accuracy_scores))
y=accuracy_scores.index(max(accuracy_scores))*10+50
print(y)

推荐阅读