python - 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()
解决方案
这是指您的 x 变量具有多个维度的事实;plot 和 scatter 仅适用于 2D 绘图,并且您似乎x_test
具有多个特征,而y_test
并且pokemon_y_pred
是一维的。
推荐阅读
- python - 获取python中日期范围之间的所有奇数天
- javascript - google.script.run 返回未定义的数组
- angular - Angular Material=> Mat-chip- Autocomplete(input) 通过空格键选择下拉菜单
- python - Python Numpy 初学者:获取形状为 ((M,N),(M,N)) 的数组
- reactjs - 在 ReactJS 中没有渲染方法的渲染组件
- regex - 带有条件和后缀的正则表达式
- javascript - JS:使用字典比遍历数组更快吗?
- android - 当应用程序的多个页面在 Kotlin 中具有相同的 Activity 名称时,如何启动 Android Activity?
- etl - Source 和 Source Qualifier 之间的字段顺序需要相同吗?
- c# - 连接多个表并返回表 2 中的最后一条记录