【问题标题】:For loop that creates a dictionary创建字典的 for 循环
【发布时间】:2016-06-20 14:28:55
【问题描述】:

我正在尝试将培训和测试错误与相应的test_size 存储在字典中,因为我想创建一个测试/培训错误图。不幸的是 for 循环不起作用。有谁知道我做错了什么? (而不是将它们存储在 pandas df 中的字典也可以)。

array = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
dicto = {}

for i in array: 
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = i)
    clf.fit(X_train,y_train)   
    test = clf.score(X_test, y_test) 
    train = clf.score(X_train, y_train)
    dicto[i, test, train]

print(dicto)

我收到以下错误:

KeyError: (0.1, 0.89473684210526316, 0.91176470588235292)

【问题讨论】:

  • 你希望你的键和值是什么?
  • 我想我得到了一个键错误,因为我请求了一个不在字典中的字典对象..
  • 发布我们可以使用预期输入和输出运行的最小脚本。您正在查找一个不存在的密钥。
  • 我想要一个键,即我的 test_size,值是测试和训练变量(这些是我的测试和训练错误)
  • 你是对的 Bahrom。我想将它们添加到字典中.. 但它不是这样工作的

标签: python dictionary pandas scikit-learn


【解决方案1】:

您永远不会在字典中分配值:

dicto[i, test, train] # This is trying to lookup a key of (i, test, train), which doesn't exist yet.

试试这个:

dicto[i] = (test, train) # map test and train variables to test_size, which is i

【讨论】:

  • 在阅读字典时,您应该根据测试大小进行查找,因此类似于dicto[test_size]
  • 感谢 Bahrom!这对我有用 :) 你帮了我很多
【解决方案2】:

这是你想要的吗?

dicto[i] = test, train

【讨论】:

  • 我想是的!你用你写的那一行往字典里加点东西吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2019-03-29
  • 2022-01-03
  • 2019-09-30
相关资源
最近更新 更多