本記事では、Pycaretを用いて、スタッキング(Stacking)回帰モデルを構築する雛形コードを載せました。概要は下記です。
stacked_model = stack_models(estimator_list = [reg],
meta_model = best,
choose_better = True,
optimize = 'MAE')
下図は、そのスタッキング回帰モデルの効果を示した図です。下図左は、Pycaretによるベスト回帰モデルの精度です。一方、下図右は、そのベスト回帰モデルとは別に線形回帰モデルを作成して、その2つを合成したスタッキング回帰モデルです。明らかに精度向上してる様子がわかります。つまり、未知の予測をしたい場合は、今回の場合、スタッキング回帰モデルが良いと判断できます。

■本プログラム
テストに用いたデータは、機械学習の回帰分析でお馴染みのボストンデータセットです。ググれば出てきます。
import os
import pandas as pd
file_path = './boston_dataset.csv'
df = pd.read_csv(file_path,
sep=',',
skiprows=0,
header=0,
encoding='utf-8')
display(df)
from pycaret.regression import *
set_data = setup(data = df,
normalize = False,
train_size = 0.75,
session_id = 1,
target = 'PRICE',
silent=True,
)
top3 = compare_models(n_select = 3,
sort = 'MAE',
verbose = False)
tuned_top3 = [tune_model(i, verbose = False) for i in top3]
best = automl(optimize = 'MAE')
predict_model(best)
plot_model(best, plot = 'error')
plot_model(best, plot = 'residuals')
reg = create_model('ridge')
stacked_model = stack_models(estimator_list = [reg],
meta_model = best,
choose_better = True,
optimize = 'MAE')
final_model = finalize_model(stacked_model)
plot_model(estimator = final_model, plot = 'error')
plot_model(final_model, plot = 'residuals')
predict_model(final_model)
import datetime
now = datetime.datetime.now()
now = now.strftime("%y%m%d")
save_model(final_model, model_name = 'finale_model_' + now)
load_reg_model = load_model('finale_model_' + now)
predict_df = predict_model(load_reg_model, data=df)
display(predict_df)
import matplotlib.pyplot as plt
import numpy as np
from scipy import optimize
import math
def approximation_expression(x, a):
return a * x
def plot_reg(DF, target_Yname, pred_Yname):
Y = DF[target_Yname].values.tolist()
pred_Y = DF[pred_Yname].values.tolist()
popt, pcov = optimize.curve_fit(approximation_expression, Y, pred_Y)
ax = plt.figure(num=0, dpi=120).gca()
ax.set_title("pred vs real ", fontsize=14)
ax.set_xlabel(target_Yname, fontsize=14)
ax.set_ylabel("Pred\n" + target_Yname, fontsize=14)
rp = ax.scatter(x = target_Yname,
y = pred_Y,
data = DF,
facecolors="none",
edgecolors='black')
y_min = DF[target_Yname].min()
y_max = DF[target_Yname].max()
y_pred_min = DF[pred_Yname].min()
y_pred_max = DF[pred_Yname].max()
x_min = min(y_min, y_pred_min)
x_max = max(y_max, y_pred_max)
x_range = x_max - x_min
print("x_range = x_max - x_min = " + str(x_range))
if x_max > 1:
print("range A")
min_lim = 0
if x_range <= 10:
max_lim = math.floor(x_max + 1)
else:
max_lim = math.floor(x_max + 10)
elif x_max >= 0:
print("range B")
min_lim = -0.1
max_lim = 1.1
elif x_min >= -1:
print("range C")
min_lim = -1.1
max_lim = 0.1
else:
print("range D")
max_lim = 0.1
if x_range <= 100:
min_lim = math.floor(x_min - 1)
else:
min_lim = math.floor(x_min - 10)
print(min_lim, max_lim)
rp.axes.set_xlim(min_lim, max_lim)
rp.axes.set_ylim(min_lim, max_lim)
x_approximation = np.linspace(min_lim, max_lim, 10)
y_approximation = popt[0] * x_approximation
line_approximation = ax.plot(x_approximation, y_approximation,
linestyle = 'dashed', linewidth = 3, color='r')
rp.axes.set_aspect('equal', adjustable='box')
plt.grid(True)
ax.legend([line_approximation[0]], ["y = {:.3f}x".format(popt[0])],
loc='upper left',
numpoints=1,
fontsize=14)
plt.tick_params(labelsize=14)
plt.tight_layout()
plt.show()
plot_reg(predict_df, 'PRICE', 'Label')
predict_df.to_csv(now + '_predict.csv', index=False, encoding='utf-8')
以上
<広告>
リンク