Python - 绘图和线性回归 - x 和 y 必须大小相同

Python - Plotting and linear regression - x and y must be the same size

我正在使用 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()

这是指您的 x 变量具有多个维度; plot 和 scatter 仅适用于二维图,而且您的 x_test 似乎具有多个特征,而 y_testpokemon_y_pred 是一维的。

仅当您对一个 y 有更多不同的 x 值时才会出现此错误,实际上 x_test 中的列比 y_test.Thats 中的列要多得多,这就是大小问题的原因。 一个y不应该有不同的x:-基础数学基础。