Nhị phân hóa, Phân thùng & Mã hóa

Feature Engineering với PySpark

John Hogue

Lead Data Scientist

Nhị phân hóa

FIREPLACES thành Has_Fireplace
1 ⇨ 1
3 ⇨ 1
1 ⇨ 1
2 ⇨ 1
0 ⇨ 0
Feature Engineering với PySpark

Nhị phân hóa

from pyspark.ml.feature import Binarizer

# Ép kiểu dữ liệu sang double df = df.withColumn('FIREPLACES', df['FIREPLACES'].cast('double'))
# Tạo bộ biến đổi nhị phân hóa bin = Binarizer(threshold=0.0, inputCol='FIREPLACES', outputCol='FireplaceT') # Áp dụng bộ biến đổi df = bin.transform(df)
# Kiểm tra kết quả 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 với PySpark

Phân thùng

from pyspark.ml.feature import Bucketizer

# Định nghĩa cách chia dữ liệu splits = [0, 1, 2, 3, 4, float('Inf')]
# Tạo bộ biến đổi phân thùng buck = Bucketizer(splits=splits, inputCol='BATHSTOTAL', outputCol='baths') # Áp dụng bộ biến đổi df = buck.transform(df)
# Kiểm tra kết quả 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 với PySpark

One Hot Encoding

CITY thành 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 với PySpark

One Hot Encoding với PySpark

from pyspark.ml.feature import OneHotEncoder, StringIndexer
# Tạo bộ biến đổi indexer
stringIndexer = StringIndexer(inputCol='CITY', outputCol='City_Index')
# Fit bộ biến đổi
model = stringIndexer.fit(df)
# Áp dụng bộ biến đổi
indexed = model.transform(df)
Feature Engineering với PySpark

One Hot Encoding với PySpark

# Tạo bộ biến đổi encoder
encoder = OneHotEncoder(inputCol='City_Index', outputCol='City_Vec)
# Áp dụng encoder
encoded_df = encoder.transform(indexed)
# Kiểm tra kết quả
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 với PySpark

Bắt đầu biến đổi!

Feature Engineering với PySpark

Preparing Video For Download...