python - 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)
解决方案
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)
推荐阅读
- asp.net-mvc - 发布时无法运行 MVC Core 项目
- java - ProgressDialog 始终不确定,即使最初将样式设置为 STYLE_HORIZONTAL
- javascript - 使用 Firebase 云功能推送通知
- javascript - 如何在导航栏中右对齐文本 - HTML
- android - “预览”屏幕中的Android空白屏幕
- c++ - c++如何评估赋值运算符(if语句)
- python - 带有日期时间索引的 Pandas Pivot
- javascript - 如何在Javascript中过滤对象数组
- javascript - 通过右键单击、Applescript 和/或 Javascript 访问浏览器中的链接?
- jquery - 如何设置 jquery addClass/removeClass