使用 PySpark 进行特征工程
John Hogue
Lead Data Scientist, General Mills
基础模型参数
featuresCol="features"labelCol="label"predictionCol="prediction"seed=None本模型的参数取值
featuresCol="features"labelCol="SALESCLOSEPRICE"predictionCol="Prediction_Price"seed=42from pyspark.ml.regression import RandomForestRegressor
# 使用指定列初始化模型
rf = RandomForestRegressor(featuresCol="features",
labelCol="SALESCLOSEPRICE",
predictionCol="Prediction_Price",
seed=42
)
# 训练模型
model = rf.fit(train_df)
# 生成预测
predictions = model.transform(test_df)
# 查看结果
predictions.select("Prediction_Price", "SALESCLOSEPRICE").show(5)
+------------------+---------------+
| Prediction_Price|SALESCLOSEPRICE|
+------------------+---------------+
|426029.55463222397| 415000|
| 708510.8806005502| 842500|
| 164275.7116183204| 161000|
| 208943.4143642175| 200000|
|217152.43272221283| 205000|
+------------------+---------------+
only showing top 5 rows
from pyspark.ml.evaluation import RegressionEvaluator
# 选择用于计算测试误差的列
evaluator = RegressionEvaluator(labelCol="SALESCLOSEPRICE",
predictionCol="Prediction_Price")
# 计算评估指标
rmse = evaluator.evaluate(predictions, {evaluator.metricName: "rmse"})
r2 = evaluator.evaluate(predictions, {evaluator.metricName: "r2"})
# 打印模型指标
print('RMSE: ' + str(rmse))
print('R^2: ' + str(r2))
RMSE: 22898.84041072095
R^2: 0.9666594402208077
使用 PySpark 进行特征工程