格點搜尋

使用 PySpark 的機器學習

Andrew Collier

Data Scientist, Fathom Data

選擇最佳參數值

使用 PySpark 的機器學習

再次回到汽車資料

cars.select('mass', 'cyl', 'consumption').show(5)
+------+---+-----------+
|  mass|cyl|consumption|
+------+---+-----------+
|1451.0|  6|       9.05|
|1129.0|  4|       6.53|
|1399.0|  4|       7.84|
|1147.0|  4|       7.84|
|1111.0|  4|       9.05|
+------+---+-----------+
使用 PySpark 的機器學習

含截距的油耗模型

具有截距的線性迴歸。以訓練資料擬合。

regression = LinearRegression(labelCol='consumption', fitIntercept=True)
regression = regression.fit(cars_train)

計算測試資料的 RMSE。

evaluator.evaluate(regression.transform(cars_test))
# RMSE for model with an intercept
0.745974203928479
使用 PySpark 的機器學習

不含截距的油耗模型

不含截距的線性迴歸。以訓練資料擬合。

regression = LinearRegression(labelCol='consumption', fitIntercept=False)
regression = regression.fit(cars_train)

計算測試資料的 RMSE。

# RMSE for model without an intercept (second model)
0.852819012439
# RMSE for model with an intercept    (first model)
0.745974203928
使用 PySpark 的機器學習

參數格點

from pyspark.ml.tuning import ParamGridBuilder

# Create a parameter grid builder
params = ParamGridBuilder()

# Add grid points params = params.addGrid(regression.fitIntercept, [True, False])
# Construct the grid params = params.build()
# How many models? print('Number of models to be tested: ', len(params))
Number of models to be tested:  2
使用 PySpark 的機器學習

交叉驗證的格點搜尋

建立交叉驗證器並擬合訓練資料。

cv = CrossValidator(estimator=regression,
                    estimatorParamMaps=params,
                    evaluator=evaluator)
cv = cv.setNumFolds(10).setSeed(13).fit(cars_train)

每個模型的交叉驗證 RMSE 是多少?

cv.avgMetrics
[0.800663722151, 0.907977823182]
使用 PySpark 的機器學習

最佳模型與參數

# Access the best model
cv.bestModel

或直接使用交叉驗證器物件。

predictions = cv.transform(cars_test)

取回最佳參數。

cv.bestModel.explainParam('fitIntercept')
'fitIntercept: whether to fit an intercept term (default: True, current: True)'
使用 PySpark 的機器學習

更複雜的格點

params = ParamGridBuilder() \
            .addGrid(regression.fitIntercept, [True, False]) \

.addGrid(regression.regParam, [0.001, 0.01, 0.1, 1, 10]) \
.addGrid(regression.elasticNetParam, [0, 0.25, 0.5, 0.75, 1]) \ .build()

現在有多少個模型?

print ('Number of models to be tested: ', len(params))
Number of models to be tested:  50
使用 PySpark 的機器學習

找出最佳參數!

使用 PySpark 的機器學習

Preparing Video For Download...