AutoML-sklearn and torch

2023-05-16

一、auto-sklearn

1.1 环境依赖

  1. 额外安装swig 第三方库

  2. linux 支持, mac,windows不支持

1.2 示例代码

time_left_for_this_task 设定任务最大时间

per_run_time_limit 每个子任务最大训练时间

include 可以限制任务训练的模型

import autosklearn.classification
import sklearn.model_selection
from sklearn import datasets
import sklearn.metrics

if __name__ == "__main__":
    X, y = datasets.load_breast_cancer(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(
        time_left_for_this_task=120,
        per_run_time_limit=30,
        tmp_folder="/tmp/autosklearn_classification_example_tmp",
        include={
            'classifier': ["random_forest"],
            'feature_preprocessor': ["no_preprocessing"]
        }
    )
    automl.fit(X_train, y_train)
    y_hat = automl.predict(X_test)
    automl.get_models_with_weights()
    print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_hat))
    print(automl.leaderboard())
    models_with_weights = automl.get_models_with_weights()
    with open('../../preprocess/models_report.txt', 'w') as f:
        for model in models_with_weights:
            f.write(str(model) + '\n')

结果展示:

可以展示参数任务cost值排列顺序
在这里插入图片描述
以及训练参数配置:
在这里插入图片描述

1.3 模块扩展

在不支持的训练模块,可以扩展及自定义模型进行自动调参

代码示例:

继承AutoSklearnClassificationAlgorithm 并重写子方法

autosklearn.pipeline.components.classification.add_classifier(MLPClassifier) 将自定义模块注册至模块中

include 参数添加既可调用

"""
====================================================
Extending Auto-Sklearn with Classification Component
====================================================

The following example demonstrates how to create a new classification
component for using in auto-sklearn.
"""
from typing import Optional
from pprint import pprint

from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import (
    CategoricalHyperparameter,
    UniformIntegerHyperparameter,
    UniformFloatHyperparameter,
)

import sklearn.metrics

from autosklearn.askl_typing import FEAT_TYPE_TYPE
import autosklearn.classification
import autosklearn.pipeline.components.classification
from autosklearn.pipeline.components.base import AutoSklearnClassificationAlgorithm
from autosklearn.pipeline.constants import (
    DENSE,
    SIGNED_DATA,
    UNSIGNED_DATA,
    PREDICTIONS,
)

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split


############################################################################
# Create MLP classifier component for auto-sklearn
# ================================================


class MLPClassifier(AutoSklearnClassificationAlgorithm):
    def __init__(
            self,
            hidden_layer_depth,
            num_nodes_per_layer,
            activation,
            alpha,
            solver,
            random_state=None,
    ):
        self.hidden_layer_depth = hidden_layer_depth
        self.num_nodes_per_layer = num_nodes_per_layer
        self.activation = activation
        self.alpha = alpha
        self.solver = solver
        self.random_state = random_state

    def fit(self, X, y):
        self.num_nodes_per_layer = int(self.num_nodes_per_layer)
        self.hidden_layer_depth = int(self.hidden_layer_depth)
        self.alpha = float(self.alpha)

        from sklearn.neural_network import MLPClassifier

        hidden_layer_sizes = tuple(
            self.num_nodes_per_layer for i in range(self.hidden_layer_depth)
        )

        self.estimator = MLPClassifier(
            hidden_layer_sizes=hidden_layer_sizes,
            activation=self.activation,
            alpha=self.alpha,
            solver=self.solver,
            random_state=self.random_state,
        )
        self.estimator.fit(X, y)
        return self

    def predict(self, X):
        if self.estimator is None:
            raise NotImplementedError()
        return self.estimator.predict(X)

    def predict_proba(self, X):
        if self.estimator is None:
            raise NotImplementedError()
        return self.estimator.predict_proba(X)

    @staticmethod
    def get_properties(dataset_properties=None):
        return {
            "shortname": "MLP Classifier",
            "name": "MLP CLassifier",
            "handles_regression": False,
            "handles_classification": True,
            "handles_multiclass": True,
            "handles_multilabel": False,
            "handles_multioutput": False,
            "is_deterministic": False,
            # Both input and output must be tuple(iterable)
            "input": [DENSE, SIGNED_DATA, UNSIGNED_DATA],
            "output": [PREDICTIONS],
        }

    @staticmethod
    def get_hyperparameter_search_space(
            feat_type: Optional[FEAT_TYPE_TYPE] = None, dataset_properties=None
    ):
        cs = ConfigurationSpace()
        hidden_layer_depth = UniformIntegerHyperparameter(
            name="hidden_layer_depth", lower=1, upper=3, default_value=1
        )
        num_nodes_per_layer = UniformIntegerHyperparameter(
            name="num_nodes_per_layer", lower=16, upper=216, default_value=32
        )
        activation = CategoricalHyperparameter(
            name="activation",
            choices=["identity", "logistic", "tanh", "relu"],
            default_value="relu",
        )
        alpha = UniformFloatHyperparameter(
            name="alpha", lower=0.0001, upper=1.0, default_value=0.0001
        )
        solver = CategoricalHyperparameter(
            name="solver", choices=["lbfgs", "sgd", "adam"], default_value="adam"
        )
        cs.add_hyperparameters(
            [
                hidden_layer_depth,
                num_nodes_per_layer,
                activation,
                alpha,
                solver,
            ]
        )
        return cs


# Add MLP classifier component to auto-sklearn.
autosklearn.pipeline.components.classification.add_classifier(MLPClassifier)
cs = MLPClassifier.get_hyperparameter_search_space()
print(cs)


############################################################################
# Data Loading
# ============
def get_local_csv():
    import pandas as pd
    import numpy as np
    df = pd.read_csv("/data/projects/example/auto_ml/Radiomics-2D/features.csv")
    label = pd.read_csv("/data/projects/example/auto_ml/Radiomics-2D/labels.csv")["label"]
    label = np.array([1 if l == "Positive" else 0 for l in label])
    return df.to_numpy(), label


# local
X, y = get_local_csv()

# breast cancer
# X, y = load_breast_cancer(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(X, y)

############################################################################
# Fit MLP classifier to the data
# ==============================

clf = autosklearn.classification.AutoSklearnClassifier(
    time_left_for_this_task=60,
    per_run_time_limit=30,
    include={"classifier": ["gradient_boosting", "adaboost", "MLPClassifier"],
             'feature_preprocessor': ["no_preprocessing"]},
)
clf.fit(X_train, y_train)

############################################################################
# Print test accuracy and statistics
# ==================================

y_pred = clf.predict(X_test)
print("accuracy: ", sklearn.metrics.accuracy_score(y_pred, y_test))
print(clf.sprint_statistics())
print(clf.leaderboard(detailed=False,top_k=30))
pprint(clf.show_models(), indent=4)

models_with_weights = clf.get_models_with_weights()
with open('./models_report.txt', 'w') as f:
    for model in models_with_weights:
        f.write(str(model) + '\n')

二、auto-pytorch

1. 1 环境依赖

额外安装brew install cmake

lightgbm 库依赖第三方库 pip install lightgbm

brew install libomp

pip install autoPyTorch

mac 允许不限制memory, M1 芯片对内容限制的操作目前还有bug

在这里插入图片描述

1.2 支持用法

支持大量的表格型数据,图片数据支持少,且不支持扩展
在这里插入图片描述
代码示例:

用法比较固定,没有更多的文档来作为参考,且无法扩展。

import numpy as np

import sklearn.model_selection

import torchvision.datasets

from autoPyTorch.pipeline.image_classification import ImageClassificationPipeline

# Get the training data for tabular classification
trainset = torchvision.datasets.FashionMNIST(root='../datasets/', train=True, download=True)
data = trainset.data.numpy()
data = np.expand_dims(data, axis=3)
# Create a proof of concept pipeline!
dataset_properties = dict()
pipeline = ImageClassificationPipeline(dataset_properties=dataset_properties)

# Train and test split
train_indices, val_indices = sklearn.model_selection.train_test_split(
    list(range(data.shape[0])),
    random_state=1,
    test_size=0.25,
)

# Configuration space
pipeline_cs = pipeline.get_hyperparameter_search_space()
print("Pipeline CS:\n", '_' * 40, f"\n{pipeline_cs}")
config = pipeline_cs.sample_configuration()
print("Pipeline Random Config:\n", '_' * 40, f"\n{config}")
pipeline.set_hyperparameters(config)

# Fit the pipeline
print("Fitting the pipeline...")

pipeline.fit(X=dict(X_train=data,
                    is_small_preprocess=True,
                    dataset_properties=dict(mean=np.array([np.mean(data[:, :, :, i]) for i in range(1)]),
                                            std=np.array([np.std(data[:, :, :, i]) for i in range(1)]),
                                            num_classes=10,
                                            num_features=data.shape[1] * data.shape[2],
                                            image_height=data.shape[1],
                                            image_width=data.shape[2],
                                            is_small_preprocess=True),
                    train_indices=train_indices,
                    val_indices=val_indices,
                    )
             )

# Showcase some components of the pipeline
print(pipeline)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AutoML-sklearn and torch 的相关文章

随机推荐

  • 使用ESP8266驱动TFT显示屏

    1 准备工作 材料 xff1a ESP8266开发板 1 54寸IPS显示屏 开发环境 xff1a Arduino 驱动库 xff1a TFT eSPI 连线 xff1a SCK GPIO14D5MOSIGPIO13D7RESGPIO2D4
  • PX4学习笔记(3)

    1 编译PX4 1 1 编译对应的代码 教程链接 xff1a https docs px4 io main zh dev setup building px4 html 由于我使用的是pixhawk 2 4 8 xff0c 应该使用以下命令
  • VDO---虚拟数据优化

    学习目标 xff1a 理解什么是VDO xff0c VDO有什么作用 学会使用VDO 内容前导 xff1a VDO xff08 Virtual Data Optimize xff0c 虚拟数据优化 xff09 是一种通过压缩或删除存储设备上
  • 阿里云轻量应用服务器centos7搭建hadoop伪分布式集群

    centos7上hadoop伪分布式集群配置 写在前面 云计算实验 xff0c hadoop完全式分布集群 xff0c 没那么多服务器就搞了个伪分布式 纯粹为了应付老师 xff0c 教程是一边查一遍弄的 xff0c 重复装了一次 xff0c
  • Eigen/Sparse稀疏矩阵SparseMatrix

    关于Eigen的稀疏矩阵的介绍 xff1a 原文链接 1 SparseMatrix的格式 SparseMatrix主要包含以下4个数组 xff1a Values stores the coefficient values of the no
  • SpringBoot事件监听器的四种方式

    Java事件监听 事件监听的概念 xff1a 事件监听就是让电脑通过你的操作得到一些数据并对这些数据做出反应 xff0c 反馈相应的行为或者指令的操作 java中的事件机制的参与者有3种角色 xff1b event object 事件状态对
  • OAI搭建步骤(EPC+eNB)

    声明 xff1a 本文CSDN作者原创投稿文章 xff0c 未经许可禁止任何形式的转载 xff0c 原文链接 文章目录 一 系统概述二 搭建核心网EPC openair cn 2 1 准备主机2 2 更换内核2 3 获取openair cn
  • Layui网址

    http laizhefa com layer index html
  • Spring Security

    Spring Security简介 Spring Security是一个高度自定义的安全框架 利用Spring IOC DI和AOP功能 xff0c 为系统提供了声明式安全访问控制功能 xff0c 减少了为系统安全而编写大量重复代码的工作
  • Hibernate基本使用

    Hibrenate框架 一 Hibrenate 1 是一个持久层框架 xff0c 实现jdbc的封装 是一个全自动的ORM框架 2 ORM xff1a 对象 关系 数据库表 映射 xff0c orm致力于将数据库操作转换成Java程序熟悉的
  • Nginx学习笔记

    文章目录 一 Nginx初始二 正向代理和反向代理 xff08 一 xff09 正向代理 xff08 二 xff09 正向代理的使用场景 xff08 三 xff09 反向代理 xff08 四 xff09 反向代理的使用场景 三 Nginx的
  • Mybatis+Mybatis-plus+SpringBoot整合(完整版)

    文章目录 一 Mybatis xff08 一 xff09 Mybatis简介1 Mybatis历史2 Mybatis特性3 Mybatis下载4 和其它持久化层技术对比 xff08 二 xff09 搭建Mybatis1 MySQL不同版本的
  • SpringMVC+SSM整合(完整版)

    文章目录 一 SpringMVC xff08 一 xff09 SpringMVC简介1 什么是MVC2 什么是SpringMVC3 SpringMVC的特点4 MVC的工作流程 xff08 二 xff09 入门案例1 创建maven工程 引
  • C语言实现CNN的前向推理

    利用Python训练模型 xff0c 提取模型参数到C语言的头文件 xff0c C语言进行前向推理计算 目录 1 填充算子1 1多维数组实现1 2一维数组实现 2 卷积算子2 1多维数组实现2 2一维数组实现 3 池化算子3 1多维数组实现
  • 树莓派3B+安装系统

    系统镜像下载 树莓派官方镜像下载地址 xff1a https www raspberrypi org downloads xff08 如果找不到就点击See all download options xff09 https www rasp
  • ubuntu16.04安装中文输入法并设置显示中文

    参考自 xff1a https jingyan baidu com article bad08e1ef4b2f109c85121b7 html 原材料 xff1a ubuntu16 步骤 xff1a 1 在桌面的最左边选择设置 xff08
  • 用PrtSc键触发启动flameshot

    进入系统设置中的 键盘快捷键 先将系统默认的快捷键prt sc禁用 xff0c 否则可能不能再设置用这个快捷键 页面中会列出所有现有的键盘快捷键 xff0c 拉到底部会看见一个 43 按钮 点击 43 按钮添加自定义快捷键并输入以下两个字段
  • 在GitHub的README中使图片深浅主题自适应

    声明 xff1a 本文CSDN作者原创投稿文章 xff0c 未经许可禁止任何形式的转载 xff0c 原文链接 在GitHub的Markdown文件中 xff0c 我们可以针对同一图片使用两份深浅主题的链接 xff0c 以保证在适应GitHu
  • P4:正则表达式(Regular Expression)学习笔记

    正则表达式学习 1 初始正则表达式1 1正则表达式练习11 2正则表达式练习21 3正则表达式练习3 2 正则表达式源码分析2 1 源码分析 matcher find 2 2源码分析 matcher group 0 2 3 整体代码2 4源
  • AutoML-sklearn and torch

    一 auto sklearn 1 1 环境依赖 额外安装swig 第三方库 linux 支持 mac xff0c windows不支持 1 2 示例代码 time left for this task 设定任务最大时间 per run ti