【问题标题】:Multiple Linear regression and selection of columns error多元线性回归和选择列错误
【发布时间】:2018-10-10 18:40:28
【问题描述】:

我的问题是当我尝试拟合模型时出现此错误。我不知道是什么导致了这个错误,但可能自变量的选择不正确。 这是错误

ValueError: Found input variables with inconsistent numbers of samples: [104, 26]

这是我目前构建的代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

# Import Excel File
data = pd.read_excel("C:\\Users\\AchourAh\\Desktop\\Multiple_Linear_Regression\\SP Level Reasons Excels\\SP00105485_PL22_AAB_05_09_2018_Reasons.xlsx",'Sheet1') #Import Excel file

# Replace null values of the whole dataset with 0
data1 = data.fillna(0)
print(data1)

# Extraction of the independent and dependent variable
X = data1.iloc[0:len(data1),[0,1,2,3]].values.reshape(-1, 1) #Extract the column of the COPCOR SP we are going to check its impact
Y = data1.iloc[0:len(data1),4].values.reshape(-1, 1) #Extract the column of the PAUS SP
print(X)
print(Y)

# Importing
from sklearn.linear_model import LinearRegression
from sklearn import model_selection

# Fitting a Linear Model
lm = LinearRegression() #create an lm object of LinearRegression Class
lm.fit(X, Y)
plt.scatter(X, Y, color = 'red')#plots scatter graph of COP COR against PAUS for values in X_train and y_train
plt.plot(X, lm.predict(X), color = 'blue')#plots the graph of predicted PAUS against COP COR.
plt.title('SP000905974')
plt.xlabel('COP COR Quantity')
plt.ylabel('PAUS Quantity')
plt.show()#Show the graph

我的 excel 文件的第一列包含自变量,第四列包含因变量。我有另一个简单线性回归的代码可以正常工作,但是当我尝试应用多元线性回归时,我只是更改了这条线,但我没有做错什么。

  X = data1.iloc[0:len(data1),[0,1,2,3]].values.reshape(-1, 1)

请注意,我是这方面的初学者。

【问题讨论】:

  • 您为什么要使用reshape(-1, 1) 重塑X 和Y?你知道它的作用吗?
  • 是的,以后可以绘制 X 和 Y。否则会引发另一个错误:ValueError: x and y must be the same size when plotting

标签: python scikit-learn selection linear-regression


【解决方案1】:

你的问题确实是 X 的重塑。

例子:

pd.DataFrame([[1,2],[3,4],[5,6]], columns = ["a", "b"]).values

是一个 numpy 数组,看起来像

array([[1, 2],
       [3, 4],
       [5, 6]], dtype=int64)

同时

pd.DataFrame([[1,2],[3,4],[5,6]], columns = ["a", "b"]).values.reshape(-1,1)

将您的行数翻倍(因为将两列重整为一列)

array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]], dtype=int64)

因此,在您的情况下,将四列重新整形为一列后,X 中的行数是 Y 中的四倍,而 lm.fit(X, Y) 需要您在 X 和 Y 中具有相同数量的行。

【讨论】:

  • 好的,但是当我删除重塑并尝试散点图时,我收到另一个错误:ValueError: x and y must be the same size
  • 那是因为您的 X 数据有四个维度(列)并且散点图是二维的。如果你像你一样重塑你的数据,你的散点图没有任何意义。去这里的方法是四个散点图 - 每个图中有一个 X 列和你的 Y 列。
猜你喜欢
  • 2020-10-25
  • 2021-01-12
  • 2021-04-16
  • 2019-07-29
  • 2021-01-15
  • 2010-11-23
  • 2013-07-17
  • 2014-05-20
  • 1970-01-01
相关资源
最近更新 更多