自动机器学习之auto-sklearn入门

当我们做完了特征工程之后,就可以代入模型训练和预测,对于模型的选择及调参,主要根据分析者的经验。在具体使用时,经常遇到同一批数据,同一种模型,不同的分析者得出的结果相差很多。

前面学习了几种常用的机器学习方法原理以及适用场景,对于完全没有经验的开发者,只要有足够时间,尝试足够多的算法和参数组合,理论上也能达到最优的训练结果,同理程序也能实现该功能,并通过算法优化该过程,自动寻找最优的模型解决方案,即自动机器学习框架。

Auto-Sklearn主要基于sklearn机器学习库,使用方法也与之类似,这让熟悉sklearn的开发者很容易切换到Auto-Sklearn。在模型方面,除了sklearn提供的机器学习模型,还加入了xgboost算法支持;在框架整体调优方面,使用了贝叶斯优化。

系统要求:
auto-sklearn has the following system requirements:
    Linux operating system (for example Ubuntu) (get Linux here),
    Python (>=3.5) (get Python here).
    C++ compiler (with C++11 supports) (get GCC here) and
    SWIG (version 3.0 or later) (get SWIG here).

1、建立新环境(这个建立虚拟环境)
conda create --name automl python=3.6
source activate automl

如何建立虚拟环境

2、安装相关包
更新下pip
pip install --upgrade pip
yum install -y libffi-devel python-devel openssl-devel gcc swig
yum install gcc-c++

Please install all dependencies manually with:
curl https://raw.githubusercontent.com/automl/auto-sklearn/master/requirements.txt | xargs -n 1 -L 1 pip install
(这一步因为网络的问题 会出现很多失败的或者下载whl包非常慢情况,建议先本地下载后进行pip install ***.whl , 要耐心,我整了大半天吧)

安装swig到默认目录(从官网下载源码包3.0以上版本,官网下载也很慢要耐心,也可以考虑从CSND下载3.0以上版本)
# ./configure
# make
# make install    

查看swig版本
#swig -version
如果出现swig:error while loading shared libraries:libpcre.so.1异常,
确认是否安装pcre,否则安装pcre

如果确认安装pcre,则运行
#ldd $(which swig)
会看到
    libpcre.so.1 => not found
手动添加链接:
#ln -s /usr/local/lib/libpcre.so.1 /lib
完毕后再次运行
#swig -version

安装swig到用户指定目录
$ ./configure --prefix=usr/local/bin/swig
$ make
$ sudo make install

路径添加到文件,
$ vim /etc/profile (需要管理员权限)

在最后添加一行:PATH=/usr/local/bin/swig:$PATH。保存后重新加载生效:
$source /etc/profile

可看到版本信息。
    SWIG Version 3.0.11
    Compiled with g++ [x86_64-pc-linux-gnu]
    Configured options: +pcre
    Please see http://www.swig.org for reporting bugs and further information


3、安装auto-sklearn
pip install auto-sklearn
pip install statsmodels

4、测试代码
 

import autosklearn.classification
import sklearn.model_selection
import sklearn.datasets
import sklearn.metrics
X, y = sklearn.datasets.load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1)
automl = autosklearn.classification.AutoSklearnClassifier()
automl.fit(X_train, y_train)
y_hat = automl.predict(X_test)
print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_hat))

#结果:Accuracy score 0.9933333333333333

这个注意下,需要等1个小时才出结果。
This will run for one hour and should result in an accuracy above 0.98.

运行过程中出现这个情况,不影响执行,我查了一下 意思是在进行mean()的时候,有空的数组。
  Y_train_pred = np.nanmean(Y_train_pred_full, axis=0)
/home/dm/anaconda3/envs/automl/lib/python3.6/site-packages/autosklearn/evaluation/train_evaluator.py:197: RuntimeWarning: Mean of empty slice
  Y_train_pred = np.nanmean(Y_train_pred_full, axis=0)
/home/dm/anaconda3/envs/automl/lib/python3.6/site-packages/autosklearn/evaluation/train_evaluator.py:197: RuntimeWarning: Mean of empty slice

整个auto-sklearn的环境就搭建好了,希望能帮到大家入门。

5、关键参数

Auto-sklearn支持的参数较多,以分类器为例,参数及其默认值如下图所示:

下面介绍其常用参数,分为四个部分:

(1) 控制训练时间和内存使用量

参数默认训练总时长为一小时(3600),一般使用以下参数按需重置,单位是秒。

    time_left_for_this_task:设置所有模型训练时间总和
    per_run_time_limit:设置单个模型训练最长时间
    ml_memory_limit:设置最大内存用量

(2) 模型存储

参数默认为训练完成后删除训练的暂存目录和输出目录,使用以下参数,可指定其暂存目录及是否删除。

    tmp_folder:暂存目录
    output_folder:输出目录
    delete_tmp_folder_after_terminate:训练完成后是否删除暂存目录
    delete_output_folder_after_terminate:训练完成后是否删除输出目录
    shared_mode:是否共享模型

(3) 数据切分

使用resampling_strategy参数可设置训练集与测试集的切分方法,以防止过拟合,用以下方法设置五折交叉验证:

    resampling_strategy='cv'
    resampling_strategy_arguments={'folds': 5}

用以下方法设置将数据切分为训练集和测集,其中训练集数据占2/3。

    resampling_strategy='holdout',
    resampling_strategy_arguments={'train_size': 0.67}

(4) 模型选择

参数支持指定备选的机器学习模型,或者从所有模型中去掉一些机器学习模型,这两个参数只需要设置其中之一。

    include_estimators:指定可选模型
    exclude_estimators:从所有模型中去掉指定模型

auto-sklearn除了支持sklearn中的模型以外,还支持xgboost模型。具体模型及其在auto-sklearn中对应的名称可通过查看源码中具体实现方法获取,通过以下目录内容查看支持的分类模型:autosklearn/pipeline/components/classification/,可看到其中包含:adaboost、extra_trees、random_forest、libsvm_svc、xgradient_boosting等方法。

实例代码:(需要关注数据的类型,自动学习的时候对类型有要求)

#!-*- coding:utf-8 -*-

import pandas as pd
import time 
import numpy as np
from sklearn.model_selection import train_test_split
import sklearn.metrics
import autosklearn.classification
import statsmodels.api as sm

datas = []
newdatas = []
alldatas = []
labels = []
for line in open('vecs_new.txt'):
    datas.append(eval(line))
for line in open('labels_new.txt'):
    labels.append(eval(line))
datas = np.array(datas)
for item in datas[:,:-1]:
    for lines in item:
        #print(lines)
        newdatas.append(int(lines))
        #print(newdatas)
    alldatas.append(newdatas)
    newdatas = []
datas = alldatas
#datas = datas[:,:-1]
labels = np.array(labels)
print(alldatas[:2])

x_train, x_test, y_train, y_test = train_test_split(datas, labels, train_size=0.7, random_state=1)
print(len(x_train),len(y_train))
x_test = np.array(x_test)
y_test = np.array(y_test)

automl = autosklearn.classification.AutoSklearnClassifier(
   time_left_for_this_task=120, per_run_time_limit=120, # 两分钟
   include_estimators=["random_forest"])
automl.fit(x_train, y_train)
#print(automl.show_models())
print(x_test[:2])
print(y_test[:2])
y_hat = automl.predict(x_test)
print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_hat))
用2分钟时间进行训练结果:
['/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000000.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000001.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000002.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000003.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000004.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000005.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000006.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000007.ensemble', '/tmp/autosklearn_tmp_29423_5323/.auto-sklearn/ensembles/1.0000000008.ensemble']
[[ 6  0  0  4  5  2  1  3  1  0  0  0  0  0  0  0  1  0  0  0  0  0  0  2
   0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
   0  0  0  0  0  0  0  0  0  2  0  0  0  0  0  0  0  0  0  0  0  0 14  0
   0  9  8  4  1  3  1  0  0  0  0  0  0  0  1  0  0  0  0  0  0  2  0  0
   1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
   0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0 12 11]
 [ 0  0  0  1  4  0  0  0  0  0  1  1  0  2  0  0  0  0  0  0  0  0  0  0
   0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
   0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0
   0  1 11  1  1  1  0  0  1  1  0  8  0  0  0  0  0  0  0  0  0  0  0  0
   0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
   0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  9  9]]
[0 0]
Accuracy score 0.5523690773067331

 


参考:
swig 和 pcre 安装
https://blog.csdn.net/shanglianlm/article/details/88797529
https://blog.csdn.net/zhangkzz/article/details/88555830
auto-sklearn 入门
https://www.jiqizhixin.com/articles/2019-08-13-8
https://www.jianshu.com/p/cd775730a1ec
auto-sklearn 安装
https://automl.github.io/auto-sklearn/master/installation.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章