首页 > 解决方案 > Python - 绘图和线性回归 - x 和 y 必须相同大小

问题描述

我正在用 python 和 scikit 教自己一些技巧,并且我正在尝试绘制一个线性回归模型。我的代码如下所示。但是我的程序和控制台给出了以下错误:x and y must be the same size. 此外,我的程序完成了我的代码,但没有绘制任何内容。

为了解决大小错误,首先想到的是用类似的东西来测试 x 和 y 的长度len(x) == len(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()

标签: pythonplotscikit-learnlinear-regressionprediction

解决方案


这是指您的 x 变量具有多个维度的事实;plot 和 scatter 仅适用于 2D 绘图,并且您似乎x_test具有多个特征,而y_test并且pokemon_y_pred是一维的。


推荐阅读