如何在旧的MinMaxScale上重新缩放新的数据库?

2024-09-30 01:19:59 发布

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

现在我遇到了扩展新数据的问题。在我的方案中,我对模型进行了训练和测试,所有的x\u训练和x\u测试都用sklearn.MinMaxScaler文件(). 然后,应用到实时过程中,如何在相同的训练和测试数据规模下缩放新的输入。 步骤如下

featuresData = df[features].values # Array of all features with the length of thousands
sc = MinMaxScaler(feature_range=(-1,1), copy=False)
featuresData = sc.fit_transform(featuresData)

#Running model to make the final model
model.fit(X,Y)
model.predict(X_test)

#Saving to abcxyz.h5

然后用新数据实现

#load the model abcxyz.h5
#catching new data 
#Scaling new data to put into the loaded model << I'm stucking in this step
#...

那么如何对新的数据进行缩放预测,然后进行反变换得到最终的结果呢?根据我的逻辑,在训练模型之前,它需要以与旧定标器相同的方式进行缩放

请帮帮我!你知道吗


Tags: oftheto数据newdatamodel方案
3条回答

考虑以下示例:

data1 = np.array([0, 1, 2, 3, 4, 5])
data2 = np.array([0, 2, 4, 6, 8, 10])

sc = MinMaxScaler()
sc.fit_transform(data1.reshape(-1, 1))

输出:

array([[0. ],
       [0.2],
       [0.4],
       [0.6],
       [0.8],
       [1. ]])

第二个数据集将在缩放后提供相同的值:

sc.fit_transform(data2.reshape(-1, 1))

输出:

array([[0. ],
       [0.2],
       [0.4],
       [0.6],
       [0.8],
       [1. ]])

让我们对第一个数据集进行拟合,并对第二个数据集使用相同的定标器:

sc.fit(data1.reshape(-1, 1))
sc.transform(data2.reshape(-1, 1)) 

输出:

array([[0. ],
       [0.4],
       [0.8],
       [1.2],
       [1.6],
       [2. ]])

您应该使用fit()transform()进行以下操作:

# Lets say you read real times data as new_data

featuresData = df[features].values
sc = MinMaxScaler(feature_range=(-1,1), copy=False)
featuresData = sc.fit_transform(featuresData)
new_data = sc.transform(new_data)

sc.transform将在新的数据上应用与在featuresData上应用相同的比例。你知道吗

从您使用scikit的方式了解,您需要保存变压器:

import joblib
# ...
sc = MinMaxScaler(feature_range=(-1,1), copy=False)
featuresData = sc.fit_transform(featuresData)

joblib.dump(sc, 'sc.joblib') 

# with new data
sc = joblib.load('sc.joblib')
transformData = sc.transform(newData)
# ...

使用scikit learn的最佳方法是将转换与模型合并。这样,只保存包含转换管道的模型。你知道吗

from sklearn import svm
from sklearn.preprocessing import MinMaxScaler
from sklearn.pipeline import Pipeline


clf = svm.SVC(kernel='linear')
sc = MinMaxScaler(feature_range=(-1,1), copy=False)

model = Pipeline([('scaler', sc), ('svc', clf)])

#...

当您执行model.fit时,首先模型将为引擎盖下的定标器执行fit_transform。使用model.predict,您的定标器的transform将参与其中。你知道吗

相关问题 更多 >

    热门问题