对于Spark中的MinMaxScaler等缩放器,是否没有“ inverse_transform”方法?

Lev*_*ang 5 machine-learning normalization apache-spark apache-spark-mllib inverse-transform

训练模型(例如线性回归)时,我们可以像火车上的MinMaxScaler一样对测试数据集进行归一化处理。

得到训练有素的模型并使用它进行预测之后,将预测缩减为原始表示。

在python中,有“ inverse_transform”方法。例如:

from sklearn.preprocessing import MinMaxScaler
scalerModel.inverse_transform

from sklearn.preprocessing import MinMaxScaler

data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]

scaler = MinMaxScaler()
MinMaxScaler(copy=True, feature_range=(0, 1))
print(data)

dataScaled = scaler.fit(data).transform(data)
print(dataScaled)

scaler.inverse_transform(dataScaled)
Run Code Online (Sandbox Code Playgroud)

在火花中有类似的方法吗?

我在Google上搜索了很多,但没有找到答案。谁能给我一些建议?非常感谢你!

Sim*_*ndi 3

在我们公司,为了解决 StandardScaler 上的相同问题,我们使用以下内容扩展了 Spark.ml(除其他外):

package org.apache.spark.ml

import org.apache.spark.ml.linalg.DenseVector
import org.apache.spark.ml.util.Identifiable

package object feature {

    implicit class RichStandardScalerModel(model: StandardScalerModel) {

        private def invertedStdDev(sigma: Double): Double = 1 / sigma

        private def invertedMean(mu: Double, sigma: Double): Double = -mu / sigma

        def inverse(newOutputCol: String): StandardScalerModel = {
            val sigma: linalg.Vector = model.std
            val mu: linalg.Vector = model.mean
            val newSigma: linalg.Vector = new DenseVector(sigma.toArray.map(invertedStdDev))
            val newMu: linalg.Vector = new DenseVector(mu.toArray.zip(sigma.toArray).map { case (m, s) => invertedMean(m, s) })
            val inverted: StandardScalerModel = new StandardScalerModel(Identifiable.randomUID("stdScal"), newSigma, newMu)
                .setInputCol(model.getOutputCol)
                .setOutputCol(newOutputCol)

            inverted
                .set(inverted.withMean, model.getWithMean)
                .set(inverted.withStd, model.getWithStd)
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

修改它或针对您的具体情况执行类似的操作应该相当容易。

请记住,由于 JVM 的双重实现,您通常会在这些操作中丢失精度,因此您将无法恢复转换前的确切原始值​​(例如:您可能会得到类似 1.9999999999999998 而不是 2.0 的值)。