机器学习笔记 - AutoML框架AutoKeras初体验

一、概述

        AutoKeras:基于 Keras 的 AutoML 系统。它由德克萨斯 A&M 大学的DATA实验室开发。AutoKeras 的目标是让每个人都可以使用机器学习。

        它提供了一种简单而有效的方法,可以自动为各种预测建模任务找到性能最佳的模型,包括表格或所谓的结构化分类和回归数据集。        自动化机器学习,或简称 AutoML,是指为预测建模问题自动找到数据准备、模型和模型超参数的最佳组合。AutoML 的好处是允许机器学习从业者以很少的输入快速有效地处理预测建模任务。

        本着 Keras 的精神,AutoKeras 为不同的任务提供了易于使用的界面,例如图像分类、结构化数据分类或回归等。用户只需要指定数据的位置和要尝试的模型数量,就会返回一个在该数据集上实现最佳性能(在配置的约束下)的模型。

        官网地址

AutoKerashttps://autokeras.com/        使用如下命令安装

pip install autokeras

        AutoKeras使用了高效神经架构搜索(ENAS)。ENAS 应用了一个类似于迁移学习的概念,其思想是:在特定任务上为特定模型学习的参数可以用于其他任务上的其他模型。因此,ENAS 迫使所有生成的子模型共享权值,从而刻意防止从头开始训练每一个子模型。这篇论文的作者表明,ENAS 不仅可以在子模型之间共享参数,还能够获得非常强的性能。 

二、AutoKeras用于回归

1、数据集

        采用kaggle tabular-playground-series-jan-2021的数据集。地址如下

Tabular Playground Series - Jan 2021 | Kaggleicon-default.png?t=M276https://www.kaggle.com/c/tabular-playground-series-jan-2021        一共30w条数据的训练集,20w条数据的测试集。

id cont1 cont2 cont3 cont4 cont5 cont6 cont7 cont8 cont9 cont10 cont11 cont12 cont13 cont14 target
1 0.67039 0.8113 0.643968 0.291791 0.284117 0.855953 0.8907 0.285542 0.558245 0.779418 0.921832 0.866772 0.878733 0.305411 7.243043
3 0.388053 0.621104 0.686102 0.501149 0.64379 0.449805 0.510824 0.580748 0.418335 0.432632 0.439872 0.434971 0.369957 0.369484 8.203331
4 0.83495 0.227436 0.301584 0.293408 0.606839 0.829175 0.506143 0.558771 0.587603 0.823312 0.567007 0.677708 0.882938 0.303047 7.776091
5 0.820708 0.160155 0.546887 0.726104 0.282444 0.785108 0.752758 0.823267 0.574466 0.580843 0.769594 0.818143 0.914281 0.279528 6.957716
8 0.935278 0.421235 0.303801 0.880214 0.66561 0.830131 0.487113 0.604157 0.874658 0.863427 0.983575 0.900464 0.935918 0.435772 7.951046
9 0.352623 0.258867 0.327373 0.802627 0.284219 0.296886 0.209743 0.27371 0.308018 0.235851 0.27876 0.251406 0.339135 0.293129 7.346874

2、使用AutoKeras

        参考代码

# use autokeras to find a model for the insurance dataset
from numpy import asarray
import numpy as np
import pandas as pd
from pandas import read_csv
from sklearn.model_selection import train_test_split
from autokeras import StructuredDataRegressor
import tensorflow as tf
from keras.models import Sequential, load_model

# 加载训练数据
train = pd.read_csv('train.csv', index_col='id')
# 加载验证数据
test = pd.read_csv('test.csv', index_col='id')

# 节省内存的方法
def reduce_mem_usage(df):
    start_mem = df.memory_usage().sum() / 1024 ** 2
    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))

    for col in df.columns:
        col_type = df[col].dtype

        if col_type != object and col!= 'time':
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)
        else:
            df[col] = df[col].astype('category')

    end_mem = df.memory_usage().sum() / 1024 ** 2
    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))

    return df

# 获取标签
y = train['target']
del train['target']
# del test['cont9']

# 扩充下训练数据集
train['max'] = train.max(axis=1)
train['min'] = train.min(axis=1)
train['mean'] = train.mean(axis=1)
train['sum'] = train.sum(axis=1)
train['cha'] = train.max(axis=1) - train.min(axis=1)
train['zhong'] = (train.max(axis=1) + train.min(axis=1))/2

# 扩充下测试数据集,用于测试
test['max'] = test.max(axis=1)
test['min'] = test.min(axis=1)
test['mean'] = test.mean(axis=1)
test['sum'] = test.sum(axis=1)
test['cha'] = test.max(axis=1) - test.min(axis=1)
test['zhong'] = (test.max(axis=1) + test.min(axis=1))/2

# 转数据类型,以便减少内存
train = reduce_mem_usage(train)
test = reduce_mem_usage(test)


def train_1():
    # 分割训练集
    X_train, X_test, y_train, y_test = train_test_split(train, y, test_size=0.33, random_state=1)
    print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

    # 定义搜索
    search = StructuredDataRegressor(max_trials=15, loss='mean_absolute_error')

    # 执行搜索
    search.fit(x=X_train, y=y_train, verbose=1)

    # 验证
    mae, _ = search.evaluate(X_test, y_test, verbose=0)
    print('MAE: %.3f' % mae)

    # 获得最佳模型
    model = search.export_model()
    # 打印模型
    model.summary()

    # 在测试集上进行测试
    predictions = model.predict(test)
    preds = []
    for pred in predictions:
        preds.append(pred[0])

    res = pd.DataFrame()
    res['target'] = preds
    res.to_csv("predict_test_v1.csv")



train_1()

3、运行结果

        可以看到最终的到的模型的结构。

MAE: 0.622
Model: "model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_1 (InputLayer)        [(None, 20)]              0         
                                                                 
 multi_category_encoding (Mu  (None, 20)               0         
 ltiCategoryEncoding)                                            
                                                                 
 normalization (Normalizatio  (None, 20)               41        
 n)                                                              
                                                                 
 dense (Dense)               (None, 128)               2688      
                                                                 
 re_lu (ReLU)                (None, 128)               0         
                                                                 
 dropout (Dropout)           (None, 128)               0         
                                                                 
 dense_1 (Dense)             (None, 64)                8256      
                                                                 
 re_lu_1 (ReLU)              (None, 64)                0         
                                                                 
 dropout_1 (Dropout)         (None, 64)                0         
                                                                 
 dropout_2 (Dropout)         (None, 64)                0         
                                                                 
 regression_head_1 (Dense)   (None, 1)                 65        
                                                                 
=================================================================
Total params: 11,050
Trainable params: 11,009
Non-trainable params: 41
_________________________________________________________________

Process finished with exit code 0

4、提交预测

        将测试集的结果的csv上传到kaggle,因为比赛是21年的,所以马上就出来结果了,Private Score得分0.74792。

三、AutoKeras用于分类

        暂时没有用进行分类测试,请参考官方的demo。

Structured Data Classification - AutoKerasicon-default.png?t=M276https://autokeras.com/tutorial/structured_data_classification/

四、使用感受

        就kaggle tabular-playground-series-jan-2021比赛结果和传统的算法比较,分数还是不如传统的机器学习的集成算法(之前测试过很多bagging、k折、stacking分数都更好),但是可以作为一个得分参考,以及得到一个相对来说不错的模型结构建议,后面还可以参考这个模型自行调整。

        类似Google AutoML和Auto-Keras等自动机器学习技术和框架,不应该过度依赖。更重要的是相关领域的专业知识,对于提高模型准确率非常关键。

猜你喜欢

转载自blog.csdn.net/bashendixie5/article/details/123454174
今日推荐