Binarizzazione, raggruppamento e codifica

Feature Engineering con PySpark

John Hogue

Lead Data Scientist

Binarizzazione

FIREPLACES diventa Has_Fireplace
1 1
3 1
1 1
2 1
0 0
Feature Engineering con PySpark

Binarizzazione

from pyspark.ml.feature import Binarizer

# Converte il tipo in double df = df.withColumn('FIREPLACES', df['FIREPLACES'].cast('double'))
# Crea il trasformatore di binarizzazione bin = Binarizer(threshold=0.0, inputCol='FIREPLACES', outputCol='FireplaceT') # Applica il trasformatore df = bin.transform(df)
# Controlla i risultati 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 con PySpark

Raggruppamento (Bucketing)

from pyspark.ml.feature import Bucketizer

# Definisci come suddividere i dati splits = [0, 1, 2, 3, 4, float('Inf')]
# Crea il trasformatore di raggruppamento buck = Bucketizer(splits=splits, inputCol='BATHSTOTAL', outputCol='baths') # Applica il trasformatore df = buck.transform(df)
# Controlla i risultati 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 con PySpark

One-hot encoding

CITY diventa 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 con PySpark

One-hot encoding in PySpark

from pyspark.ml.feature import OneHotEncoder, StringIndexer
# Crea il trasformatore indexer
stringIndexer = StringIndexer(inputCol='CITY', outputCol='City_Index')
# Esegui il fit del trasformatore
model = stringIndexer.fit(df)
# Applica il trasformatore
indexed = model.transform(df)
Feature Engineering con PySpark

One-hot encoding in PySpark

# Crea il trasformatore encoder
encoder = OneHotEncoder(inputCol='City_Index', outputCol='City_Vec)
# Applica l'encoder
encoded_df = encoder.transform(indexed)
# Controlla i risultati
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 con PySpark

Passa alla trasformazione!

Feature Engineering con PySpark

Preparing Video For Download...