【发布时间】:2018-12-14 05:26:06
【问题描述】:
我正在用 python 和 scikit 自学一些技巧,并且我正在尝试绘制一个线性回归模型。我的代码如下所示。但是我的程序和控制台给出了以下错误:x and y must be the same size。此外,我的程序完成了我的代码,但没有绘制任何内容。
要修复大小错误,首先想到的是使用 len(x) == len(y) 之类的东西来测试 x 和 y 的长度。但据我所知,我的数据似乎是相同的长度。也许错误指的是长度以外的东西(如果是这样,我不确定是什么)。非常感谢任何帮助。
from sklearn import cross_validation
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn import linear_model
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Create linear regression object
regr = linear_model.LinearRegression()
#load csv file with pandas
df = pd.read_csv("pokemon.csv")
#remove all string columns
df = df.drop(['Name','Type_1','Type_2','isLegendary','Color','Pr_Male','hasGender','Egg_Group_1','Egg_Group_2','hasMegaEvolution','Body_Style'], axis=1)
y= df.Catch_Rate
x_train, x_test, y_train, y_test = cross_validation.train_test_split(df, y, test_size=0.25, random_state=0)
# Train the model using the training sets
regr.fit(x_train, y_train)
# Make predictions using the testing set
pokemon_y_pred = regr.predict(x_test)
print (pokemon_y_pred)
# Plot outputs
plt.title("Linear Regression Model of Catch Rate")
plt.scatter(x_test, y_test, color='black')
plt.plot(x_test, pokemon_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
【问题讨论】:
-
你试过用
print(len(x))和print(len(y))检查x和y的长度吗?在你的代码中简单地写len(x) == len(y)不会做任何事情(也许你在想assert len(x) == len(y),如果x 和y 的长度不同,它会引发一个AssertionError)。 -
cross_validation.train_test_split到底是什么?? -
@Joel 我应该更具体一点——我确实打印了长度,我只是在测试我的测试,看看两组是否相等。它与一维数组和二维数组有什么关系吗?
-
看起来您将完整的数据框
df作为第一个参数传递给train_test_split。第一个参数应该只是df的x(自变量)部分。 -
@GarrettMcClure 如果您正在执行单变量回归,这意味着您有一个变量
x,它是一个自变量,您希望在该变量上预测其他变量y。您选择的x变量是您必须自己选择的——不是 scikit-learn 会自动为您选择的。如果您正在执行多线性回归,则x将成为一组变量,但您必须自己选择这些变量。您不应将包括y在内的整个数据集传递给train_test_split的第一个参数。
标签: python plot scikit-learn linear-regression prediction