Python中Float错误的文本无效

2024-06-17 11:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用sklearn并使用sklearn库在Python中执行线性回归。在

这是我用来训练和拟合模型的代码,我在运行predict函数调用时得到了错误。在

train, test = train_test_split(h1, test_size = 0.5, random_state=0)

my_features = ['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors', 'zipcode']
trainInp = train[my_features]

target = ['price']
trainOut = train[target]

regr = LinearRegression()

# Train the model using the training sets

regr.fit(trainInp, trainOut)

print('Coefficients: \n', regr.coef_)

testPred = regr.predict(test)

在拟合模型之后,当我试图使用测试数据进行预测时,它会抛出以下错误

^{pr2}$

线性回归模型的系数为

('Coefficients: \n', array([[ -5.04902429e+04,   5.23550164e+04,   2.90631319e+02,
         -1.19010351e-01,  -1.25257545e+04,   6.52414059e+02]]))

下面是测试数据集的前五行

Test dataset

误差是因为系数值太大而引起的吗?怎么解决这个问题?在


Tags: the模型testtargetmy错误train线性
1条回答
网友
1楼 · 发布于 2024-06-17 11:36:36

您的问题是,您正在将模型拟合到整个数据帧中选定的一组特性上(您可以trainInp = train[my_features]),但您试图预测完整的特性集(regr.predict(test)),包括非数字特性,如date。在

因此,与其做regr.predict(test),不如做regr.predict(test[my_features])。更一般地说,请记住,无论您对训练集应用什么样的预处理(规范化、特征选择、PCA…),您也应该应用于测试集。在

或者,在进行列车测试拆分之前,您可以缩减到感兴趣的特性集:

my_features = ['bedrooms', 'bathrooms', ...]
train, test = train_test_split(h1[my_features], test_size = 0.5, random_state=0)

相关问题 更多 >