所有自变量均为分类变量,因(目标)变量为连续变量

2024-09-28 23:37:04 发布

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

这是我需要建立模型的数据:

dataframe

  • 数据帧包含834行和4列(“大小”、“扇区”、“道路连通性”、“价格”)

  • 目的是训练一个模型来预测价格

  • “尺寸”、“扇区”和“道路连通性”是分配给X变量的3个特征

  • “价格”,即我们的目标功能分配给y变量

  • 我已经做了一个管道,其中包括一个热编码器和线性回归 代码如下:

ohc=OneHotEncoder(categories = "auto")
lr=LinearRegression(fit_intercept=True,normalize=True)
pipe=make_pipeline(ohc,lr)
from sklearn.model_selection import ShuffleSplit
from sklearn.model_selection import cross_val_score
kfolds=ShuffleSplit(n_splits=5,test_size=0.2,random_state=0)
cross_val_score(pipe,X,y,cv=kfolds).mean()

输出=0.8970496076598085

xinp=([['04M','Sec 10','C road']])
pipe.fit(X,y)
pipe.predict(xinp)

现在,当我将值传递给管道以进行预测时,它显示了一个错误:

“”“转换期间在第1列中找到未知类别['Sec 10']””

任何有助于建立模型的建议都将不胜感激


Tags: 数据from模型truemodel管道价格sklearn
1条回答
网友
1楼 · 发布于 2024-09-28 23:37:04

看起来您提供的类别(在xinp,即Sec 10值中)在训练数据中不存在,因此它不能是一个热编码的类别,因为它没有虚拟变量(没有对应的二进制列)。可能的解决方案之一是:

ohc=OneHotEncoder(categories = "auto", handle_unknown = "ignore")

来自scikit的一个热编码器documentation

handle_unknown{‘error’, ‘ignore’}, default=’error’

Whether to raise an error or ignore if an unknown categorical feature is present during transform (default is to raise). When this parameter is set to ‘ignore’ and an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None.

相关问题 更多 >