关于人工智能:通过遗传算法进行超参数调整和自动时间序列建模

6次阅读

共计 5674 个字符,预计需要花费 15 分钟才能阅读完成。

在以前的文章中咱们介绍过一些基于遗传算法的常识,本篇文章将应用遗传算法解决机器学习模型和工夫序列数据。

超参数调整(TPOT)

主动机器学习(Auto ML)通过自动化整个机器学习过程,帮咱们找到最适宜预测的模型,对于机器学习模型来说 Auto ML 可能更多的意味着超参数的调整和优化。

在这里咱们应用 python 的一个名叫 Tpot 的包来操作,TPOT 是建设在 scikit-learn 之上,尽管还是处在开发中,然而他的性能曾经能够帮忙咱们理解这些概念了,下图显示了 Tpot 的工作原理:

from tpot import TPOTClassifier
from tpot import TPOTRegressormodel = TPOTClassifier(generations=100, population_size=100, offspring_size=None, mutation_rate=0.9, crossover_rate=0.1, scoring=None, cv=5, subsample=1.0, n_jobs=1, max_time_mins=None, max_eval_time_mins=5, random_state=None, config_dict=None, template=None, warm_start=False, memory=None, use_dask=False, periodic_checkpoint_folder=None, early_stop=None, verbosity=0, disable_update_check=False, log_file=None)

通过下面的代码就能够取得简略的回归模型,这是默认参数列表

generations=100, 
population_size=100, 
offspring_size=None  # Jeff notes this gets set to population_size
mutation_rate=0.9, 
crossover_rate=0.1, 
scoring="Accuracy",  # for Classification
cv=5, 
subsample=1.0, 
n_jobs=1,
max_time_mins=None, 
max_eval_time_mins=5,
random_state=None, 
config_dict=None,
warm_start=False, 
memory=None,
periodic_checkpoint_folder=None, 
early_stop=None
verbosity=0
disable_update_check=False

咱们看看有哪些超参数能够进行调整:

generations:迭代次数。默认值为 100。population_size:每代遗传编程种群中保留的个体数。默认值为 100。offspring_size:在每一代遗传编程中产生的后辈数量。默认值为 100。mutation_rate:遗传编程算法的突变率 范畴 [0.0, 1.0]。该参数通知 GP 算法有多少管道将随机更改利用于每词迭代。默认值为 0.9
crossover_rate:遗传编程算法穿插率,范畴 [0.0, 1.0]。这个参数通知遗传编程算法每一代要“培养”多少管道。scoring:用于评估问题函数,如准确率、均匀精度、roc_auc、召回率等。默认为准确率。cv:评估管道时应用的穿插验证策略。默认值为 5。random_state:TPOT 中应用的伪随机数生成器的种子。应用此参数可确保运行 TPOT 时应用雷同随机种子,失去雷同的后果。n_jobs:= - 1 多个 CPU 内核上运行以放慢 tpot 过程。period_checkpoint_folder:“any_string”,能够在训练分数进步的同时察看模型的演变。

mutation_rate + crossover_rate 不能超过 1.0。

上面咱们将 Tpot 和 sklearn 联合应用,进行模型的训练。

from pandas import read_csv
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import RepeatedStratifiedKFold
from tpot import TPOTClassifier

dataframe = read_csv('sonar.csv')
#define X and y 
data = dataframe.values
X, y = data[:, :-1], data[:, -1]

# minimally prepare dataset
X = X.astype('float32')
y = LabelEncoder().fit_transform(y.astype('str'))

#split the dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# define cross validation 
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)

当初咱们运行 TPOTClassifier,进行超参数的优化

#initialize the classifier
model = TPOTClassifier(generations=5, population_size=50,max_time_mins= 2,cv=cv, scoring='accuracy', verbosity=2, random_state=1, n_jobs=-1)
model.fit(X_train, y_train)

#export the best model
model.export('tpot_best_model.py')

最初一句代码将模型保留在 .py 文件中,在应用的是后能够间接 import。因为对于 AutoML 来说,最大的问题就是训练的工夫,所以为了节省时间,population_size、max_time_mins 等值都应用了最小的设置。

当初咱们关上文件 tpot_best_model.py,看看内容:

import numpy as np
import pandas as pd
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from tpot.export_utils import set_param_recursive

# NOTE: Make sure that the outcome column is labeled 'target' in the data file
tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)
features = tpot_data.drop('target', axis=1)
training_features, testing_features, training_target, testing_target = \
            train_test_split(features, tpot_data['target'], random_state=1)

# Average CV score on the training set was: -29.099695845082277
exported_pipeline = make_pipeline(PolynomialFeatures(degree=2, include_bias=False, interaction_only=False),
    RidgeCV())

# Fix random state for all the steps in exported pipeline
set_param_recursive(exported_pipeline.steps, 'random_state', 1)

exported_pipeline.fit(training_features, training_target)
results = exported_pipeline.predict(testing_features)

如果想做预测的话,应用上面代码

yhat = exported_pipeline.predict(new_data)

以上就是遗传算法进行 AutoML/ 机器学习中超参数优化的办法。遗传算法受到达尔文自然选择过程的启发,并被用于计算机科学以寻找优化搜寻。简而言之遗传算法由 3 种常见行为组成:抉择、穿插、渐变

上面咱们看看它对解决工夫序列的模型有什么帮忙

工夫序列数据建模(AutoTS)

在 Python 中有一个名叫 AutoTS 的包能够解决工夫序列数据,咱们从它开始

#AutoTS
from autots import AutoTS
from autots.models.model_list import model_lists
print(model_lists)

autots 中有大量不同类型的工夫序列模型,他就是以这些算法为根底,通过遗传算法的优化来找到最优的模型。

当初让咱们加载数据。

#default data
from autots.datasets import load_monthly
#data was in long format
df_long = load_monthly(long=True)

用不同的参数初始化 AutoTS

model = AutoTS(
    forecast_length=3,
    frequency='infer',
    ensemble='simple',
    max_generations=5,
    num_validations=2,
)
model = model.fit(df_long, date_col='datetime', value_col='value', id_col='series_id')
#help(AutoTS)

这个步骤须要很长的工夫,因为它必须通过屡次算法迭代。

print(model)

咱们还能够查看模型准确率分数

#accuracy score
model.results()
#aggregated from cross validation
validation_results = model.results("validation")

从模型准确度分数列表中,还能够看到下面突出显示的“Ensemble”这一栏,它的低精度验证了一个实践,即 Ensemble 总是体现更好, 这种说法是不正确的。

找到了最好的模型,就能够进行预测了。

prediction = model.predict()
forecasts_df = prediction.forecast
upper_forecasts_df = prediction.upper_forecast
lower_forecasts_df = prediction.lower_forecast
#or
forecasts_df1 = prediction.long_form_results()
upper_forecasts_df1 = prediction.long_form_results()
lower_forecasts_df1 = prediction.long_form_results()

默认的办法是应用 AutoTs 提供的所有模型进行训练,如果咱们想要在一些模型列表上执行,并对某个个性设定不同的权重,就须要一些自定义的配置。

首先还是读取数据

from autots import AutoTS
from autots.datasets import load_hourlydf_wide = load_hourly(long=False)

# here we care most about traffic volume, all other series assumed to be weight of 1
weights_hourly = {'traffic_volume': 20}

定义模型列表:

model_list = [
    'LastValueNaive',
    'GLS',
    'ETS',
    'AverageValueNaive',
]

model = AutoTS(
    forecast_length=49,
    frequency='infer',
    prediction_interval=0.95,
    ensemble=['simple', 'horizontal-min'],
    max_generations=5,
    num_validations=2,
    validation_method='seasonal 168',
    model_list=model_list,
    transformer_list='all',
    models_to_validate=0.2,
    drop_most_recent=1,
    n_jobs='auto',
)

在用数据拟合模型时定义权重:

model = model.fit(
    df_wide,
    weights=weights_hourly,
)

prediction = model.predict()
forecasts_df = prediction.forecast

这样就实现了,对于应用来说十分的简略

相干资源

以下是两个 python 包的文档:

https://winedarksea.github.io…

http://epistasislab.github.io…

最初如果你对加入 Kaggle 较量感兴趣,请私信我,邀你进入 Kaggle 较量交换群

正文完
 0