- 我已经训练了一个机器学习模型,并将其存储在Pickle文件中。
- 在我的新脚本中,我正在读取新的“真实世界数据”,并希望进行预测。
但是,我遇到了困难。我有一列(包含字符串值),如下:
Sex
Male
Female
# This is just as example, in real it is having much more unique values
现在出现了问题。我收到了一个新的(独特的)值,现在我不能再做预测了(例如添加了'Neutral'
)。
由于我正在将'Sex'
列转换为虚拟变量,所以我的模型不再接受输入,
模型的特征数量必须与输入相匹配。模型n_features为2,输入n_features为3
因此我的问题是:是否有一种方法可以使我的模型更加健壮,并忽略这个类?但是进行预测,没有具体信息?
我尝试过的:
df = pd.read_csv('dataset_that_i_want_to_predict.csv')
model = pickle.load(open("model_trained.sav", 'rb'))
# I have an 'example_df' containing just 1 row of training data (this is exactly what the model needs)
example_df = pd.read_csv('reading_one_row_of_trainings_data.csv')
# Checking for missing columns, and adding that to the new dataset
missing_cols = set(example_df.columns) - set(df.columns)
for column in missing_cols:
df[column] = 0 #adding the missing columns, with 0 values (Which is ok. since everything is dummy)
# make sure that we have the same order
df = df[example_df.columns]
# The prediction will lead to an error!
results = model.predict(df)
# ValueError: Number of features of the model must match the input. Model n_features is X and n_features is Y
注意,我搜索了但是没有找到任何有用的解决方案(不是这里,这里或者这里) 更新 还发现了这篇文章。但是同样的问题在这里...我们可以使用与训练集相同的列来创建测试集...但是对于新的真实世界数据(例如新值“中性”)怎么办?