Binarización, discretización y codificación

Ingeniería de características con PySpark

John Hogue

Lead Data Scientist

Binarización

FIREPLACES pasa a Has_Fireplace
1 1
3 1
1 1
2 1
0 0
Ingeniería de características con PySpark

Binarización

from pyspark.ml.feature import Binarizer

# Convertir el tipo a double df = df.withColumn('FIREPLACES', df['FIREPLACES'].cast('double'))
# Crear el transformador de binarización bin = Binarizer(threshold=0.0, inputCol='FIREPLACES', outputCol='FireplaceT') # Aplicarlo df = bin.transform(df)
# Ver resultados df[['FIREPLACES','FireplaceT']].show(3)
+----------+-------------+
|FIREPLACES|   FireplaceT|
+----------+-------------+
|       0.0|          0.0|
|       1.0|          1.0|
|       2.0|          1.0|
+----------+-------------+
only showing top 3 rows
Ingeniería de características con PySpark

Discretización (Bucketing)

from pyspark.ml.feature import Bucketizer

# Definir los cortes splits = [0, 1, 2, 3, 4, float('Inf')]
# Crear el transformador de discretización buck = Bucketizer(splits=splits, inputCol='BATHSTOTAL', outputCol='baths') # Aplicarlo df = buck.transform(df)
# Ver resultados df[['BATHSTOTAL', 'baths']].show(4)
+----------+-----------------+
|BATHSTOTAL|baths            |
+----------+-----------------+
|         2|              2.0|
|         3|              3.0|
|         1|              1.0|
|         5|              4.0|
+----------+-----------------+
only showing top 4 rows

Ingeniería de características con PySpark

One-Hot Encoding

CITY pasa a LELM MAPW OAKD STP WB
LELM - Lake Elmo 1 0 0 0 0
MAPW - Maplewood 0 1 0 0 0
OAKD - Oakdale 0 0 1 0 0
STP - Saint Paul 0 0 0 1 0
WB - Woodbury 0 0 0 0 1
Ingeniería de características con PySpark

One-Hot Encoding en PySpark

from pyspark.ml.feature import OneHotEncoder, StringIndexer
# Crear el transformador indexador
stringIndexer = StringIndexer(inputCol='CITY', outputCol='City_Index')
# Ajustar el transformador
model = stringIndexer.fit(df)
# Aplicarlo
indexed = model.transform(df)
Ingeniería de características con PySpark

One-Hot Encoding en PySpark

# Crear el transformador encoder
encoder = OneHotEncoder(inputCol='City_Index', outputCol='City_Vec)
# Aplicar el encoder
encoded_df = encoder.transform(indexed)
# Ver resultados
encoded_df[['City_Vec']].show(4)
+-------------+
|     City_Vec|
+-------------+
|    (4,[],[])|
|    (4,[],[])|
|(4,[2],[1.0])|
|(4,[2],[1.0])|
+-------------+
only showing top 4 rows
Ingeniería de características con PySpark

¡A transformar!

Ingeniería de características con PySpark

Preparing Video For Download...