python - ValueError : x 和 y 的大小必须相同
问题描述
我有一个数据集,我正在尝试使用 sklearn 计算线性回归。我正在使用的数据集已经制作好了,所以应该不会有问题。我使用 train_test_split 将我的数据分成训练组和测试组。当我尝试使用 matplotlib 在我的测试组和预测组之间创建散点图时,出现下一个错误:
ValueError: x 和 y 的大小必须相同
这是我的代码:
y=data['Yearly Amount Spent']
x=data[['Avg. Session Length','Time on App','Time on Website','Length of Membership','Yearly Amount Spent']]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=101)
#training the model
from sklearn.linear_model import LinearRegression
lm=LinearRegression()
lm.fit(x_train,y_train)
lm.coef_
predictions=lm.predict(X_test)
#here the problem starts:
plt.scatter(y_test,predictions)
为什么会出现这个错误?我在这里看过以前的帖子,对此的建议是使用x.shape和y.shape但我不确定这样做的目的是什么。
谢谢
解决方案
看来您正在使用EcommerceCustomers.csv
数据集(链接在这里)
在您的原始帖子中,该列'Yearly Amount Spent'
也包含在y
以及中,x
但这是错误的。
以下应该可以正常工作:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
data = pd.read_csv("EcommerceCustomers.csv")
y = data['Yearly Amount Spent']
X = data[['Avg. Session Length', 'Time on App','Time on Website', 'Length of Membership']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
# ## Training the Model
lm = LinearRegression()
lm.fit(X_train,y_train)
# The coefficients
print('Coefficients: \n', lm.coef_)
# ## Predicting Test Data
predictions = lm.predict( X_test)
另请参阅
推荐阅读
- java - 需要有关弹性搜索自动化的信息
- java - 禁止登录 SwaggerGen
- osgi - Adobe AEM/OSGI:如何从任何类访问 OSGI 服务?
- bash - 在 macOS 上更改 .profile 中的陷阱后无法消除错误
- ios - CAGradientLayer 上均匀分布的颜色
- typescript - 如何在打字稿中将 Blob 类型转换为字节数组?
- html - 从跨域加载 vtt 的问题
- c# - Xamarin.Android 膨胀自定义视图
- javascript - 为什么索引会在 javascript 数组中自动创建?
- java - 如何将“2019-04-11T05:00:54.000+01:00”转换为 dd/MM/yyyy hh:mm 格式