Skip to main content
 首页 » 编程设计

python之学习 |线性回归 |合身

2024年10月01日9luoye11

我在使用 Scikit Learn 中的线性回归算法时遇到了一些问题 - 我在论坛中进行了搜索并在 Google 上进行了大量搜索,但出于某种原因,我未能成功绕过该错误。我正在使用 Python 3.5

以下是我尝试过的方法,但一直出现值错误:“找到样本数量不一致的输入变量:[403, 174]”

X = df[["Impressions", "Clicks", "Eligible_Impressions", "Measureable_Impressions", "Viewable_Impressions"]].values 
 
y = df["Total_Conversions"].values.reshape(-1,1) 
 
print ("The shape of X is {}".format(X.shape)) 
print ("The shape of y is {}".format(y.shape)) 
 
The shape of X is (577, 5) 
The shape of y is (577, 1) 
 
X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=0.3, random_state = 42) 
linreg = LinearRegression() 
linreg.fit(X_train, y_train) 
y_pred = linreg.predict(X_test) 
print (y_pred) 
 
print ("The shape of X_train is {}".format(X_train.shape)) 
print ("The shape of y_train is {}".format(y_train.shape)) 
print ("The shape of X_test is {}".format(X_test.shape)) 
print ("The shape of y_test is {}".format(y_test.shape)) 
 
The shape of X_train is (403, 5) 
The shape of y_train is (174, 5) 
The shape of X_test is (403, 1) 
The shape of y_test is (174, 1) 

我是否遗漏了一些明显的东西?

如有任何帮助,我们将不胜感激。

亲切的问候, 阿德里安

请您参考如下方法:

看起来您的训练和测试包含不同数量的 X 和 y 行。这是因为您以错误的顺序存储 train_test_split() 的返回值

改变这个

X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=0.3, random_state = 42) 

为此

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 42)