微软出品!FLAML:一款可以自动化机器学习过程的神器!

x33g5p2x  于2021-09-22 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(358)

机器学习是我们使用一组算法解决来解决生活中问题的过程。创建机器学习模型很容易,但选择在泛化和性能方面都最适合的模型是一项艰巨的任务。

有多种机器学习算法可用于回归和分类,可根据我们要解决的问题来选择,但选择合适的模型是一个需要高计算成本、时间和精力的过程。

为解决上述问题,今天我给大家分享一款非常棒的工具包:FLAML,它是一个轻量级的开源 Python 库,有助于自动、高效地找出最佳机器学习模型,不仅速度快,节省时间,而且设计轻巧。

让我们详细的介绍一下它吧…

安装所需的库

我们将首先使用 pip 安装来安装 FLAML。下面给出的命令将使用 pip 安装。

  1. pip install flaml
导入所需的库

在这一步中,我们将导入创建机器学习模型和下载数据集所需的所有库。

  1. from flaml import AutoML
解决分类问题

现在我们将从解决分类问题开始。我们将在这里使用的数据是著名的 Iris 数据集,可以从 Seaborn 库轻松加载。让我们开始创建模型。

  1. #Loading the Dataset
  2. from sklearn.datasets import load_iris

为 Automl 创建实例很重要,同时也定义 Automl 设置,因此在这一步中,我们还将创建 Automl 实例并定义设置。

  1. automl = AutoML()
  2. automl_settings = {
  3. "time_budget": 10, # in seconds
  4. "metric": 'accuracy',
  5. "task": 'classification'
  6. }

接下来,我们将拆分数据并将其拟合到模型中。最后,我们还将使用模型进行预测并找到最佳模型。

  1. X_train, y_train = load_iris(return_X_y=True)
  2. # Train with labeled input data
  3. automl.fit(X_train=X_train, y_train=y_train,
  4. **automl_settings)
  5. print(automl.predict_proba(X_train).shape)
  6. # Export the best model
  7. print(automl.model)

在这里,我们可以清楚地看到 ExtraTreeEstimator 是此数据的最佳模型。现在让我们打印模型的最佳超参数和准确性。

  1. print('Best ML leaner:', automl.best_estimator)
  2. print('Best hyperparmeter config:', automl.best_config)
  3. print('Best accuracy on validation data: {0:.4g}'.format(1-automl.best_loss))
  4. print('Training duration of best run: {0:.4g} s'.format(automl.best_config_train_time))

同样,对于回归问题,我们也将遵循相同的过程。

解决回归问题

现在将解决一个回归问题。我们将在这里使用的数据是著名的波士顿数据集,可以从 Seaborn 库轻松加载。我们可以遵循与分类问题完全相同的过程。

  1. from sklearn.datasets import load_boston
  2. automl = AutoML()
  3. automl_settings = {
  4. "time_budget": 10, # in seconds
  5. "metric": 'r2',
  6. "task": 'regression'
  7. }
  8. X_train, y_train = load_boston(return_X_y=True)
  9. # Train with labeled input data
  10. automl.fit(X_train=X_train, y_train=y_train,
  11. **automl_settings)
  12. # Predict
  13. print(automl.predict(X_train).shape)
  14. # Export the best model
  15. print(automl.model)

  1. print('Best ML leaner:', automl.best_estimator)
  2. print('Best hyperparmeter config:', automl.best_config)
  3. print('Best accuracy on validation data: {0:.4g}'.format(1-automl.best_loss))
  4. print('Training duration of best run: {0:.4g} s'.format(automl.best_config_train_time))

在这里,我们也可以清楚地看到回归问题的最佳模型和超参数。同样,你可以对你关注的数据集执行此过程,并找到最佳模型和超参数。

相关文章