【问题标题】:How do I prevent KeyErrors in python?如何防止python中的KeyErrors?
【发布时间】:2021-03-06 03:43:42
【问题描述】:

我在机器学习项目中使用 MinMaxScaler 时遇到 KeyError 问题。这是我的相关代码:

df = pd.read_csv(io.BytesIO(uploaded['Root_Work_Sample.csv']))
print(df.shape)
print(df.columns)
display(df.head(5))
print(df.dtypes)
train_cols = ["feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9, feature10, feature11, feature12, feature13, feature14, y"]
df_train, df_test = train_test_split(df, train_size=1000, test_size=876, shuffle=False)
print("Train--Test size", len(df_train), len(df_test))
print(df_train)
print(df_test)
 
# scale the feature MinMax, build array
x = df_train.loc[:,train_cols].values  #THE ERROR IS ON THIS LINE
min_max_scaler = MinMaxScaler()
x_train = min_max_scaler.fit_transform(x)
x_test = min_max_scaler.transform(df_test.loc[:,train_cols])

这是我得到的错误:

KeyError: "None of [Index(['feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9, feature10, feature11, feature12, feature13, feature14, y'], dtype='object')] are in the [columns]"

对于如何解决这个问题以及像我这样的新手如何避免此类错误的一般做法有什么建议吗?

【问题讨论】:

    标签: python pandas dataframe scikit-learn keyerror


    【解决方案1】:

    df_train 不是数据框,它是一个 2D numpy 数组,所以你不能在上面使用loc 方法。 我猜你以错误的方式使用train_test_split 函数。 而且您还错误地指定了train_cols,您应该将每个功能用引号括起来,如下所示:

    train_cols = ["feature", "feature2",....]
    

    试试这个:

    X, y = df[train_cols], df["y"]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=876, shuffle=False)
    
    scaler = MinMaxScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    

    【讨论】:

    • 这太棒了!我对这个解决方案只有一个问题。据我了解,数据框在一个变量中同时包含 x 和 y 测试/训练文件,而这个似乎是分开的?这会不会让事情变得复杂?
    • 这是您为验证最佳模型所要做的。通过分离它们,您现在可以在特征空间上应用您想要的任何转换。例如:在您的编码中,您使用MinMaxScaler 缩放了x 和y。这是错误的。您只需转换特征列或x numpy 数组。
    • 如果此解决方案有帮助,请考虑给它一个赞成票,并将其选为您的有效答案。祝你好运!
    • 我还没有获得点赞的声望等级,但我会为您回复!我想我可以理解!所以这会训练所有 cols 进行 y 预测!非常感谢您的帮助?
    • 没问题!我很高兴你发现它有帮助。祝您在 ML 道路上好运。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多