【问题标题】:ValueError: Found input variables with inconsistent numbers of samples:ValueError:发现样本数量不一致的输入变量:
【发布时间】:2021-06-20 10:03:06
【问题描述】:

运行下面的代码时出现值错误,我认为这是由于 iloc 代码将数据拆分为 x 和 y,但看不到我做错了什么:

            if st.checkbox('Select Multiple Columns'):
                new_data = st.multiselect(
                    "Select the target columns. Please note, the target variable should be the last column selected",
                    df.columns)
                df1 = df[new_data]
                st.dataframe(df1)

                # dividing data into X and Y varibles
                x = df1.iloc[:, :-1]
                y = df1.iloc[:-1]

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=seed)

            clf.fit(X_train, y_train)

            y_pred = clf.predict(X_test)
            st.write('Prediction:', y_pred)

我得到的错误如下:

ValueError:发现样本数量不一致的输入变量:[196, 195] 追溯:

数据集片段:

1/1/20  X   2020    206457
1/1/20  X   2021    70571
1/1/20  X   2022    46918
1/1/20  X   2023    36492
1/1/20  X   2024    0
1/1/20  X   2025    0
1/1/20  X   2020    286616
1/1/20  X   2021    134276
1/1/20  X   2022    87674
1/1/20  X   2023    240
1/1/20  X   2024    0
1/1/20  X   2025    0

【问题讨论】:

  • x 和 y 的切片方式不同。 x 在整行上,而 y 上少一行。

标签: python pandas scikit-learn


【解决方案1】:

检查您的 2 个语句的代码:

x = df1.iloc[:, :-1]
y = df1.iloc[:-1]

x 和 y 在 df1 上以不同的方式切片。 x 在整行上,而 y 少一行。因此,样本数量不一致:[196, 195] ==> 196 for x; 195 为你

请注意iloc[]的第一个参数是对行进行切片,而第二个参数是对列进行切片。

您有 x 对所有行进行切片并减少一列(没有最后一列),而 y 仅使用一个参数进行切片并且仅在行上切片(没有最后一行)并且它通过不指定列切片来获取所有列在第二个参数上。

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 2018-12-04
    • 2021-05-31
    • 2020-08-19
    • 2021-09-12
    • 2021-08-06
    • 2020-06-07
    • 2022-01-16
    • 2022-01-11
    相关资源
    最近更新 更多