首页 > 解决方案 > Python SKLearn:预测序列时出现“输入形状错误”错误

问题描述

我有一个 Excel 文件,它在每一列中存储一个序列(从顶部单元格到底部单元格读取),并且序列的趋势与上一列相似。所以我想预测这个数据集中第 n 列的序列。

我的数据集样本:

样本数据

看到每一列都有一组值/序列,当我们向右移动时它们会有所进展,所以我想预测例如 Z 列中的值。

到目前为止,这是我的代码:

import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# Read the Excel file in rows
df = pd.read_excel(open('vec_sol2.xlsx', 'rb'),
                header=None, sheet_name='Sheet1')
print(type(df))
length = len(df.columns)
# Get the sequence for each row

x_train, x_test, y_train, y_test = train_test_split(
    np.reshape(range(0, length - 1), (-1, 1)), df, test_size=0.25, random_state=0)

print("y_train shape: ", y_train.shape)

pred_model = LogisticRegression()
pred_model.fit(x_train, y_train)
print(pred_model)

我将尽可能地解释逻辑:

我在调试时设法获得了每个 var 的形状,它们是:

但是现在,运行程序给了我这个错误:

ValueError: bad input shape (37, 51)

我的错误是什么?

标签: pythonpandasscikit-learnpredictionvalueerror

解决方案


我不明白你为什么要使用这个:

x_train, x_test, y_train, y_test = train_test_split(
np.reshape(range(0, length - 1), (-1, 1)), df, test_size=0.25, random_state=0)

您在此处有数据df。从中提取X和然后将其拆分以进行训练和测试。y

尝试这个:

X = df.iloc[:,:-1]
y = df.iloc[:, -1:]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=0)

否则,您共享的统计数据显示您正在尝试从一个功能中获得 51 个列输出,如果您考虑一下,这很奇怪。


推荐阅读