Binarização, Agrupamento e Codificação

Feature Engineering com PySpark

John Hogue

Lead Data Scientist

Binarização

FIREPLACES vira Has_Fireplace
1 ⇨ 1
3 ⇨ 1
1 ⇨ 1
2 ⇨ 1
0 ⇨ 0
Feature Engineering com PySpark

Binarização

from pyspark.ml.feature import Binarizer

# Converter o tipo de dado para double df = df.withColumn('FIREPLACES', df['FIREPLACES'].cast('double'))
# Criar o transformador de binarização bin = Binarizer(threshold=0.0, inputCol='FIREPLACES', outputCol='FireplaceT') # Aplicar o transformador df = bin.transform(df)
# Inspecionar os 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
Feature Engineering com PySpark

Agrupamento

from pyspark.ml.feature import Bucketizer

# Definir como dividir os dados splits = [0, 1, 2, 3, 4, float('Inf')]
# Criar o transformador de agrupamento buck = Bucketizer(splits=splits, inputCol='BATHSTOTAL', outputCol='baths') # Aplicar o transformador df = buck.transform(df)
# Inspecionar os 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

Feature Engineering com PySpark

One-Hot Encoding

CITY vira 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
Feature Engineering com PySpark

One-Hot Encoding no PySpark

from pyspark.ml.feature import OneHotEncoder, StringIndexer
# Criar o transformador indexador
stringIndexer = StringIndexer(inputCol='CITY', outputCol='City_Index')
# Ajustar o transformador
model = stringIndexer.fit(df)
# Aplicar o transformador
indexed = model.transform(df)
Feature Engineering com PySpark

One-Hot Encoding no PySpark

# Criar o transformador de codificação
encoder = OneHotEncoder(inputCol='City_Index', outputCol='City_Vec)
# Aplicar o transformador de codificação
encoded_df = encoder.transform(indexed)
# Inspecionar os resultados
encoded_df[['City_Vec']].show(4)
+-------------+
|     City_Vec|
+-------------+
|    (4,[],[])|
|    (4,[],[])|
|(4,[2],[1.0])|
|(4,[2],[1.0])|
+-------------+
only showing top 4 rows
Feature Engineering com PySpark

Hora de transformar!

Feature Engineering com PySpark

Preparing Video For Download...