【问题标题】:Plot Decision Tree train/test accuracy against max depth针对最大深度绘制决策树训练/测试精度
【发布时间】:2020-05-19 18:41:05
【问题描述】:

我试图从决策树模型中绘制我的训练集和测试集的准确性。由于我是使用 python 的新手,我不确定应该使用哪种类型的图形包。我使用了一个简单的 for 循环来获取打印结果,但不确定如何绘制它。

谢谢!

我的代码:

for x in max_depth_list :

  dtc =DecisionTreeClassifier(max_depth=x)
  dtc.fit(train_x,train_y)

  train_z = dtc.predict(train_x)
  train_z_prob = dtc.predict_proba(train_x)[:,1]

  test_z = dtc.predict(test_x)
  test_z_prob = dtc.predict_proba(test_x)[:,1]

  print("split: {}".format(x))
  print("model accuracy: {}".format(accuracy_score(test_y, test_z)))

所需的图表 enter image description here

【问题讨论】:

  • 您的问题到底是什么?你只是问你应该使用哪个绘图库?如果是这样,那显然是题外话。请参阅:help center

标签: python plot decision-tree


【解决方案1】:

您发布的图片中的情节很可能是使用matplotlib.pyplot 模块创建的。假设您已导入其他必要的依赖项,您可能可以通过执行类似的操作来绘制类似的图表:

import numpy as np
import matplotlib.pyplot as plt

max_depth_list = [1,2,3,4]

train_errors = [] # Log training errors for each model
test_errors = [] # Log testing errors for each model

for x in max_depth_list:
    dtc = DecisionTreeClassifier(max_depth=x) 
    dtc.fit(train_x,train_y)
    train_z = dtc.predict(train_x)
    test_z = dtc.predict(test_x)
    train_errors.append(accuracy_score(train_x, train_z))
    test_errors.append(accuracy_score(test_y, test_z))

x = np.arange(len(max_depth_list)) + 1 # Create domain for plot
plt.plot(x, train_errors, label='Training Error') # Plot training error over domain
plt.plot(x, test_errors, label='Testing Error') # Plot testing error over domain
plt.xlabel('Maximum Depth') # Label x-axis
plt.ylabel('Total Error') # Label y-axis
plt.legend() # Show plot labels as legend
plt.show() # Show graph

我也是这个社区的新手,所以我无法向其他用户提供建议。但是,格式化源代码以获得更好的可读性和演示效果可能是一个好主意。请注意。

我希望这会有所帮助。如果有任何不清楚的地方,请告诉我。

【讨论】:

  • 谢谢!这真的很有帮助。我试图只是复制我的代码然后意识到我可以将其格式化为代码,但除了将三个单引号作为开头和结尾之外,我没有想出任何东西。下次试试。
  • 很高兴它有帮助!是的,堆栈溢出的系统是基于 Markdown 的,它允许使用代码和方程式进行多种格式设置。它非常容易学习:我建议您查看here
  • 最后应该是plot.show()吗?
  • @jtessier72 是的,感谢您的关注!
猜你喜欢
  • 2016-10-18
  • 2018-12-30
  • 1970-01-01
  • 2017-03-07
  • 2020-06-04
  • 2019-10-20
  • 2020-07-08
  • 2016-10-01
  • 1970-01-01
相关资源
最近更新 更多