StandardScaler
class pyspark.ml.feature.StandardScaler(withMean=False, withStd=True, inputCol=None, outputCol=None)
通过使用训练集中样本的列汇总统计数据去除均值并缩放到单位方差来标准化特征(归一化)
“单位标准差”是使用校正后的样本标准差计算的,该标准差计算为无偏样本方差的平方根
withMean = Param(parent=‘undefined’, name=‘withMean’, doc=‘以平均值为中心的数据’)*
withStd= Param(parent=‘undefined’, name=‘withStd’, doc=‘缩放到单位标准差’)*
01.创建数据
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("SQLTransformer").master("local[*]").getOrCreate()
from pyspark.ml.linalg import Vectors
df = spark.createDataFrame([(Vectors.dense([0.0]),), (Vectors.dense([2.0]),)], ["a"])
df.show()
df.printSchema()
输出结果:
+-----+
| a|
+-----+
|[0.0]|
|[2.0]|
+-----+
root
|-- a: vector (nullable = true)
02.使用StandardScaler标准化
from pyspark.ml.feature import StandardScaler
standardScaler = StandardScaler(inputCol="a", outputCol="scaled")
model = standardScaler.fit(df)
model.transform(df).show()
model.mean
输出结果:
+-----+-------------------+
| a| scaled|
+-----+-------------------+
|[0.0]| [0.0]|
|[2.0]|[1.414213562373095]|
+-----+-------------------+
DenseVector([1.0])