首页 > 解决方案 > 数据标准化后如何使用 K-Nearest Neighbors (KNN) 模型进行预测 (Python)

问题描述

我通过使用三个变量(年龄、距离、旅行津贴)作为我的预测变量,在 Python(Module = Scikitlearn)中创建了一个 KNN 模型,目的是使用它们来预测目标变量(旅行方法)的结果。

在构建模型时,我必须对三个预测变量(年龄、距离、旅行津贴)的数据进行标准化。与不规范化数据相比,这提高了我的模型的准确性。

现在我已经构建了模型,我想做一个预测。但是,由于模型已经在标准化数据上进行了训练,我将如何输入预测变量来进行预测。

我想输入KNN.predict([[30,2000,40]])以执行年龄 = 30 的预测;距离 = 2000;Allowance = 40。但是由于数据已经标准化,我想不出如何做到这一点。我使用以下代码来规范化数据:
X = preprocessing.StandardScaler().fit(X).transform(X.astype(float))

标签: pythonscikit-learnclassificationdata-sciencenearest-neighbor

解决方案


实际上,答案隐藏在您提供的代码中!

一旦你适应了它的实例,preprocessing.StandardScaler()它就会记住如何缩放数据。尝试这个

scaler = preprocessing.StandardScaler().fit(X)
# scaler is an object that knows how to normalize data points
X_normalized = scaler.transform(X.astype(float))
# used scalar to normalize the data points in X
# Note, this is what you have done, just in two steps. 
# I just capture the scaler object 
#
# ... Train your model on X_normalized
#
# Now predict
other_data = [[30,2000,40]]
other_data_normalized = scaler.transform(other_data)
KNN.predict(other_data_normalized)

请注意,我scaler.transform以相同的方式使用了两次

请参见StandardScaler.transform


推荐阅读