使用 MLflow 记录可视化
在本指南的这一部分,我们强调使用 MLflow 记录可视化的重要性。将可视化与训练好的模型一起保留,可以提高模型的可解释性、可审计性和可追溯性,从而确保健壮且透明的机器学习生命周期。
我们在做什么?
- 存储可视化图件:我们将各种图表作为可视化图件记录在 MLflow 中,确保它们始终可访问并与相应的模型和运行数据保持一致。
- 提高模型可解释性:这些可视化有助于理解和解释模型行为,从而提高模型的透明度和问责制。
它如何应用于 MLflow?
- 集成可视化日志记录:MLflow 无缝集成了用于记录和访问可视化图件的功能,从而提高了处理可视化上下文和见解的便捷性和效率。
- 便捷访问:在 MLflow UI 的“运行”视图窗格中可以显示记录的图表,从而确保快速轻松地进行分析和审查。
注意
虽然 MLflow 在记录可视化方面提供了简洁性和便利性,但确保可视化图件与相应的模型数据保持一致性和相关性至关重要,从而维护模型信息的完整性和全面性。
为什么一致的日志记录很重要?
- 审计和可追溯性:可视化的一致和全面的记录对于审计至关重要,确保每个模型都附有相关的可视化见解,以便进行彻底的分析和审查。
- 增强模型理解:适当的可视化上下文可以增强对模型行为的理解,有助于进行有效的模型评估和验证。
总之,MLflow 的可视化日志记录功能在确保全面、透明和高效的机器学习生命周期方面发挥着不可估量的作用,增强了模型的可解释性、可审计性和可追溯性。
生成合成苹果销售数据
在下一节中,我们将使用 generate_apple_sales_data_with_promo_adjustment 函数深入探讨为苹果销售需求预测生成合成数据。该函数模拟了与苹果销售相关的各种特征,提供了丰富的数据集供探索和建模。
我们在做什么?
- 模拟真实数据:生成包含日期、平均温度、降雨量、周末标志等特征的数据集,模拟真实的苹果销售场景。
- 整合各种效应:该函数整合了促销调整、季节性和竞争对手定价等效应,这些效应都会影响“需求”目标变量。
它如何应用于数据生成?
- 全面的数据集:合成数据集提供了全面的特征和交互集,非常适合探索需求预测的各种方面和维度。
- 自由和灵活性:合成数据的性质允许无约束的探索和分析,不受现实世界数据敏感性和限制的影响。
注意
虽然合成数据在探索和学习方面具有许多优势,但承认其在捕捉现实世界复杂性和细微差别方面的局限性至关重要。
为什么承认局限性很重要?
- 现实世界的复杂性:合成数据可能无法捕捉现实世界数据中存在的所有复杂模式和异常,这可能导致模型和见解过于简化。
- 向现实世界场景的可转移性:确保从合成数据中获得的见解和模型可转移到现实世界场景需要仔细考虑和验证。
总之,generate_apple_sales_data_with_promo_adjustment 函数为生成全面的苹果销售需求预测合成数据集提供了一个强大的工具,它有助于广泛的探索和分析,同时承认合成数据的局限性。
import math
import pathlib
from datetime import datetime, timedelta
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats
from sklearn.linear_model import Ridge
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
mean_squared_log_error,
median_absolute_error,
r2_score,
)
from sklearn.model_selection import train_test_split
import mlflow
def generate_apple_sales_data_with_promo_adjustment(
base_demand: int = 1000,
n_rows: int = 5000,
competitor_price_effect: float = -50.0,
):
"""
Generates a synthetic dataset for predicting apple sales demand with multiple
influencing factors.
This function creates a pandas DataFrame with features relevant to apple sales.
The features include date, average_temperature, rainfall, weekend flag, holiday flag,
promotional flag, price_per_kg, competitor's price, marketing intensity, stock availability,
and the previous day's demand. The target variable, 'demand', is generated based on a
combination of these features with some added noise.
Args:
base_demand (int, optional): Base demand for apples. Defaults to 1000.
n_rows (int, optional): Number of rows (days) of data to generate. Defaults to 5000.
competitor_price_effect (float, optional): Effect of competitor's price being lower
on our sales. Defaults to -50.
Returns:
pd.DataFrame: DataFrame with features and target variable for apple sales prediction.
Example:
>>> df = generate_apple_sales_data_with_promo_adjustment(base_demand=1200, n_rows=6000)
>>> df.head()
"""
# Set seed for reproducibility
np.random.seed(9999)
# Create date range
dates = [datetime.now() - timedelta(days=i) for i in range(n_rows)]
dates.reverse()
# Generate features
df = pd.DataFrame(
{
"date": dates,
"average_temperature": np.random.uniform(10, 35, n_rows),
"rainfall": np.random.exponential(5, n_rows),
"weekend": [(date.weekday() >= 5) * 1 for date in dates],
"holiday": np.random.choice([0, 1], n_rows, p=[0.97, 0.03]),
"price_per_kg": np.random.uniform(0.5, 3, n_rows),
"month": [date.month for date in dates],
}
)
# Introduce inflation over time (years)
df["inflation_multiplier"] = 1 + (df["date"].dt.year - df["date"].dt.year.min()) * 0.03
# Incorporate seasonality due to apple harvests
df["harvest_effect"] = np.sin(2 * np.pi * (df["month"] - 3) / 12) + np.sin(
2 * np.pi * (df["month"] - 9) / 12
)
# Modify the price_per_kg based on harvest effect
df["price_per_kg"] = df["price_per_kg"] - df["harvest_effect"] * 0.5
# Adjust promo periods to coincide with periods lagging peak harvest by 1 month
peak_months = [4, 10] # months following the peak availability
df["promo"] = np.where(
df["month"].isin(peak_months),
1,
np.random.choice([0, 1], n_rows, p=[0.85, 0.15]),
)
# Generate target variable based on features
base_price_effect = -df["price_per_kg"] * 50
seasonality_effect = df["harvest_effect"] * 50
promo_effect = df["promo"] * 200
df["demand"] = (
base_demand
+ base_price_effect
+ seasonality_effect
+ promo_effect
+ df["weekend"] * 300
+ np.random.normal(0, 50, n_rows)
) * df["inflation_multiplier"] # adding random noise
# Add previous day's demand
df["previous_days_demand"] = df["demand"].shift(1)
df["previous_days_demand"].fillna(method="bfill", inplace=True) # fill the first row
# Introduce competitor pricing
df["competitor_price_per_kg"] = np.random.uniform(0.5, 3, n_rows)
df["competitor_price_effect"] = (
df["competitor_price_per_kg"] < df["price_per_kg"]
) * competitor_price_effect
# Stock availability based on past sales price (3 days lag with logarithmic decay)
log_decay = -np.log(df["price_per_kg"].shift(3) + 1) + 2
df["stock_available"] = np.clip(log_decay, 0.7, 1)
# Marketing intensity based on stock availability
# Identify where stock is above threshold
high_stock_indices = df[df["stock_available"] > 0.95].index
# For each high stock day, increase marketing intensity for the next week
for idx in high_stock_indices:
df.loc[idx : min(idx + 7, n_rows - 1), "marketing_intensity"] = np.random.uniform(0.7, 1)
# If the marketing_intensity column already has values, this will preserve them;
# if not, it sets default values
fill_values = pd.Series(np.random.uniform(0, 0.5, n_rows), index=df.index)
df["marketing_intensity"].fillna(fill_values, inplace=True)
# Adjust demand with new factors
df["demand"] = df["demand"] + df["competitor_price_effect"] + df["marketing_intensity"]
# Drop temporary columns
df.drop(
columns=[
"inflation_multiplier",
"harvest_effect",
"month",
"competitor_price_effect",
"stock_available",
],
inplace=True,
)
return df
生成苹果销售数据
在此单元格中,我们调用 generate_apple_sales_data_with_promo_adjustment 函数来生成苹果销售数据集。
使用的参数:
base_demand:设置为 1000,表示苹果的基本需求。n_rows:设置为 10,000,确定生成数据集中行的数量或数据点。competitor_price_effect:设置为 -25.0,表示当竞争对手价格较低时对我们销售的影响。
通过运行此单元格,我们获得了一个名为 my_data 的数据集,其中包含具有上述配置的合成苹果销售数据。此数据集将用于此笔记本后续步骤中的进一步探索和分析。
您可以在生成单元格之后的单元格中看到数据。
my_data = generate_apple_sales_data_with_promo_adjustment(
base_demand=1000, n_rows=10_000, competitor_price_effect=-25.0
)
my_data
| 日期 | 平均温度 | 降雨量 | 周末 | 假期 | 每公斤价格 | 促销 | 需求 | 前几天的需求 | competitor_price_per_kg | marketing_intensity | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1996-05-11 13:10:40.689999 | 30.584727 | 1.831006 | 1 | 0 | 1.578387 | 1 | 1301.647352 | 1326.324266 | 0.755725 | 0.323086 |
| 1 | 1996-05-12 13:10:40.689999 | 15.465069 | 0.761303 | 1 | 0 | 1.965125 | 0 | 1143.972638 | 1326.324266 | 0.913934 | 0.030371 |
| 2 | 1996-05-13 13:10:40.689998 | 10.786525 | 1.427338 | 0 | 0 | 1.497623 | 0 | 890.319248 | 1168.942267 | 2.879262 | 0.354226 |
| 3 | 1996-05-14 13:10:40.689997 | 23.648154 | 3.737435 | 0 | 0 | 1.952936 | 0 | 811.206168 | 889.965021 | 0.826015 | 0.953000 |
| 4 | 1996-05-15 13:10:40.689997 | 13.861391 | 5.598549 | 0 | 0 | 2.059993 | 0 | 822.279469 | 835.253168 | 1.130145 | 0.953000 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 9995 | 2023-09-22 13:10:40.682895 | 23.358868 | 7.061220 | 0 | 0 | 1.556829 | 1 | 1981.195884 | 2089.644454 | 0.560507 | 0.889971 |
| 9996 | 2023-09-23 13:10:40.682895 | 14.859048 | 0.868655 | 1 | 0 | 1.632918 | 0 | 2180.698138 | 2005.305913 | 2.460766 | 0.884467 |
| 9997 | 2023-09-24 13:10:40.682894 | 17.941035 | 13.739986 | 1 | 0 | 0.827723 | 1 | 2675.093671 | 2179.813671 | 1.321922 | 0.884467 |
| 9998 | 2023-09-25 13:10:40.682893 | 14.533862 | 1.610512 | 0 | 0 | 0.589172 | 0 | 1703.287285 | 2674.209204 | 2.604095 | 0.812706 |
| 9999 | 2023-09-26 13:10:40.682889 | 13.048549 | 5.287508 | 0 | 0 | 1.794122 | 1 | 1971.029266 | 1702.474579 | 1.261635 | 0.750458 |
10000 行 × 11 列
需求的 time series 可视化
在本节中,我们正在创建一个 time series 图来可视化需求数据及其滚动平均值。
为什么这很重要?
可视化 time series 数据对于识别模式、理解变异性以及做出更明智的决策至关重要。通过绘制滚动平均值,我们可以平滑短期波动并突出长期趋势或周期。这种视觉辅助工具对于理解数据并做出更准确、更明智的预测和决策至关重要。
代码结构:
- 输入验证:代码首先确保数据是 pandas DataFrame。
- 日期转换:它将“date”列转换为 datetime 格式,以便进行准确绘图。
- 滚动平均值计算:它计算“demand”的滚动平均值,窗口大小为指定的
window_size,默认为 7 天。 - 绘图:它将原始需求数据和计算出的滚动平均值绘制在同一张图上进行比较。原始需求数据以低 alpha 值绘制,显得“模糊”,以确保滚动平均值更加突出。
- 标签和图例:添加了充分的标签和图例以提高清晰度。
为什么返回图表?
我们返回图表对象 (fig),而不是直接渲染它,这样模型训练事件的每一次迭代都可以将图表作为记录的图件消耗到 MLflow 中。这种方法允许我们持久化数据可视化状态,并精确匹配用于训练的数据状态。MLflow 可以存储此图表对象,从而可以在 MLflow UI 中轻松检索和渲染,确保可视化始终可访问并与相关的模型和数据信息配对。
def plot_time_series_demand(data, window_size=7, style="seaborn", plot_size=(16, 12)):
if not isinstance(data, pd.DataFrame):
raise TypeError("df must be a pandas DataFrame.")
df = data.copy()
df["date"] = pd.to_datetime(df["date"])
# Calculate the rolling average
df["rolling_avg"] = df["demand"].rolling(window=window_size).mean()
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
# Plot the original time series data with low alpha (transparency)
ax.plot(df["date"], df["demand"], "b-o", label="Original Demand", alpha=0.15)
# Plot the rolling average
ax.plot(
df["date"],
df["rolling_avg"],
"r",
label=f"{window_size}-Day Rolling Average",
)
# Set labels and title
ax.set_title(
f"Time Series Plot of Demand with {window_size} day Rolling Average",
fontsize=14,
)
ax.set_xlabel("Date", fontsize=12)
ax.set_ylabel("Demand", fontsize=12)
# Add legend to explain the lines
ax.legend()
plt.tight_layout()
plt.close(fig)
return fig
使用箱形图可视化周末与工作日的需求
在本节中,我们使用箱形图来可视化周末与工作日需求的分布。这种可视化有助于理解基于一周中日期的需求变异性和中心趋势。
为什么这很重要?
了解周末与工作日之间的需求差异对于就库存、人员配置和其他运营方面做出明智的决策至关重要。它有助于识别需求较高的时期,从而更好地进行资源分配和规划。
代码结构:
- 箱形图:代码使用 Seaborn 创建一个箱形图,显示周末(1)和工作日(0)的需求分布。箱形图提供了两种类别需求中位数、四分位数和可能异常值的信息。
- 添加单个数据点:为了提供更多上下文,将单个数据点作为散点图叠加在箱形图上。它们为了更好的可视化而进行了抖动处理,并根据日期类型进行了颜色编码。
- 样式:为了清晰起见,对图表进行了样式设置,并删除了不必要的图例以提高可读性。
为什么返回图表?
与 time series 图一样,此函数也返回图表对象 (fig),而不是直接显示它。
def plot_box_weekend(df, style="seaborn", plot_size=(10, 8)):
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
sns.boxplot(data=df, x="weekend", y="demand", ax=ax, color="lightgray")
sns.stripplot(
data=df,
x="weekend",
y="demand",
ax=ax,
hue="weekend",
palette={0: "blue", 1: "green"},
alpha=0.15,
jitter=0.3,
size=5,
)
ax.set_title("Box Plot of Demand on Weekends vs. Weekdays", fontsize=14)
ax.set_xlabel("Weekend (0: No, 1: Yes)", fontsize=12)
ax.set_ylabel("Demand", fontsize=12)
for i in ax.get_xticklabels() + ax.get_yticklabels():
i.set_fontsize(10)
ax.legend_.remove()
plt.tight_layout()
plt.close(fig)
return fig
探索需求与每公斤价格之间的关系
在此可视化中,我们正在创建一个散点图来研究 demand 和 price_per_kg 之间的关系。理解这种关系对于定价策略和需求预测至关重要。
为什么这很重要?
- 定价策略见解:这种可视化有助于揭示需求随每公斤价格的变化情况,为设置价格以优化销售和收入提供宝贵的见解。
- 理解需求弹性:它有助于理解需求相对于价格的弹性,从而在制定促销和折扣方面做出明智的、数据驱动的决策。
代码结构:
- 散点图:代码生成一个散点图,其中每个点的位置由
price_per_kg和demand决定,颜色表示该天是周末还是工作日。这种颜色编码有助于快速识别周末或工作日特有的模式。 - 透明度和抖动:点以透明度 (
alpha=0.15) 绘制,以处理重叠点,从而可以可视化点的密度。 - 回归线:对于每个子组(周末和工作日),在同一轴上拟合并绘制单独的回归线。这些线清楚地显示了每个组的需求相对于每公斤价格的趋势。
def plot_scatter_demand_price(df, style="seaborn", plot_size=(10, 8)):
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
# Scatter plot with jitter, transparency, and color-coded based on weekend
sns.scatterplot(
data=df,
x="price_per_kg",
y="demand",
hue="weekend",
palette={0: "blue", 1: "green"},
alpha=0.15,
ax=ax,
)
# Fit a simple regression line for each subgroup
sns.regplot(
data=df[df["weekend"] == 0],
x="price_per_kg",
y="demand",
scatter=False,
color="blue",
ax=ax,
)
sns.regplot(
data=df[df["weekend"] == 1],
x="price_per_kg",
y="demand",
scatter=False,
color="green",
ax=ax,
)
ax.set_title("Scatter Plot of Demand vs Price per kg with Regression Line", fontsize=14)
ax.set_xlabel("Price per kg", fontsize=12)
ax.set_ylabel("Demand", fontsize=12)
for i in ax.get_xticklabels() + ax.get_yticklabels():
i.set_fontsize(10)
plt.tight_layout()
plt.close(fig)
return fig
可视化需求密度:工作日 vs. 周末
此可视化允许我们分别观察工作日和周末的 demand 分布。
为什么这很重要?
- 需求分布见解:了解工作日与周末的需求分布可以为库存管理和人员配置需求提供信息。
- 指导业务战略:这些见解对于制定有关促销、折扣和其他在特定日期可能更有效的策略的数据驱动决策至关重要。
代码结构:
- 密度图:代码生成一个
demand的密度图,分为工作日和周末。 - 颜色编码组:两个组(工作日和周末)进行了颜色编码(分别为蓝色和绿色),易于区分。
- 透明度和填充:密度曲线下方的区域以浅色、透明的颜色(
alpha=0.15)填充,以便于可视化,同时避免视觉混乱。
视觉元素是什么?
- 两条密度曲线:图表包含两条密度曲线,一条代表工作日,另一条代表周末。这些曲线清晰地可视化了每个组的需求分布。
- 图例:添加了一个图例,以帮助识别哪条曲线对应哪个组(工作日或周末)。
def plot_density_weekday_weekend(df, style="seaborn", plot_size=(10, 8)):
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
# Plot density for weekdays
sns.kdeplot(
df[df["weekend"] == 0]["demand"],
color="blue",
label="Weekday",
ax=ax,
fill=True,
alpha=0.15,
)
# Plot density for weekends
sns.kdeplot(
df[df["weekend"] == 1]["demand"],
color="green",
label="Weekend",
ax=ax,
fill=True,
alpha=0.15,
)
ax.set_title("Density Plot of Demand by Weekday/Weekend", fontsize=14)
ax.set_xlabel("Demand", fontsize=12)
ax.legend(fontsize=12)
for i in ax.get_xticklabels() + ax.get_yticklabels():
i.set_fontsize(10)
plt.tight_layout()
plt.close(fig)
return fig
模型系数可视化
在本节中,我们正在使用条形图来可视化训练模型的特征系数。
为什么这很重要?
理解系数的大小和方向对于解释模型至关重要。它有助于识别影响预测的最重要特征。这些见解对于特征选择、工程以及最终提高模型性能至关重要。
代码结构:
- 上下文设置:代码通过设置“seaborn”绘图样式来启动,以增强美观性。
- 图表初始化:它创建用于绘图的图表和坐标轴。
- 条形图:它使用水平条形图 (
barh) 来可视化每个特征的系数。y 轴表示特征名称,x 轴表示系数。这种可视化易于比较系数,提供了对其相对重要性和对目标变量影响的见解。 - 标题和标签:它设置了一个合适的标题(“Coefficient Plot”)以及 x 轴(“Coefficient Value”)和 y 轴(“Features”)的标签,以确保清晰度和可理解性。
通过可视化系数,我们可以更深入地了解模型,从而更容易解释模型的预测,并就特征重要性和影响做出更明智的决策。
def plot_coefficients(model, feature_names, style="seaborn", plot_size=(10, 8)):
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
ax.barh(feature_names, model.coef_)
ax.set_title("Coefficient Plot", fontsize=14)
ax.set_xlabel("Coefficient Value", fontsize=12)
ax.set_ylabel("Features", fontsize=12)
plt.tight_layout()
plt.close(fig)
return fig
残差可视化
在本节中,我们正在创建图表来可视化模型的残差,即观测值与预测值之间的差异。
为什么这很重要?
残差图是回归分析中的基本诊断工具,用于调查预测变量和响应变量之间关系的不可预测性。它有助于识别非线性、异方差和异常值。此图有助于验证误差服从正态分布且具有恒定方差的假设,这对于回归模型预测的可靠性至关重要。
代码结构:
- 残差计算:代码首先将实际值 (
y_test) 和预测值 (y_pred) 之间的差值计算为残差。 - 上下文设置:代码将绘图样式设置为“seaborn”,以获得美观的图表。
- 图表初始化:它创建用于绘图的图表和坐标轴。
- 残差绘图:它利用 Seaborn 的
residplot创建残差图,并带有 lowess(局部加权散点图平滑)线以突出残差的趋势。 - 零线:在零处添加一条虚线作为参考,用于观察残差。线上方的残差表示预测不足,线下的残差表示预测过度。
- 标题和标签:它设置了一个合适的标题(“Residual Plot”)以及 x 轴(“Predicted values”)和 y 轴(“Residuals”)的标签,以确保清晰度和可理解性。
通过检查残差图,我们可以就模型的充分性以及进一步改进或增加复杂性的可能需求做出更明智的决策。
def plot_residuals(y_test, y_pred, style="seaborn", plot_size=(10, 8)):
residuals = y_test - y_pred
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
sns.residplot(
x=y_pred,
y=residuals,
lowess=True,
ax=ax,
line_kws={"color": "red", "lw": 1},
)
ax.axhline(y=0, color="black", linestyle="--")
ax.set_title("Residual Plot", fontsize=14)
ax.set_xlabel("Predicted values", fontsize=12)
ax.set_ylabel("Residuals", fontsize=12)
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(10)
plt.tight_layout()
plt.close(fig)
return fig
预测误差可视化
在本节中,我们正在创建图表来可视化预测误差,展示我们模型中观测值与预测值之间的差异。
为什么这很重要?
理解预测误差对于评估模型的性能至关重要。预测误差图提供了对误差分布的见解,并有助于识别趋势、偏差或异常值。这种可视化是模型评估的关键组成部分,有助于识别模型可能需要改进的领域,并确保模型能够很好地泛化到新数据。
代码结构:
- 上下文设置:代码将绘图样式设置为“seaborn”,以获得简洁美观的图表。
- 图表初始化:它初始化用于绘图的图表和坐标轴。
- 散点图:代码绘制预测值与误差(实际值 - 预测值)的关系图。图上的每个点代表一个特定的观测值,其在 y 轴上的位置表示误差的大小和方向(零以上表示预测不足,零以下表示预测过度)。
- 零线:在 y=0 处绘制一条红色虚线作为参考,有助于轻松识别误差。该线上方的点是预测不足,下方的点是预测过度。
- 标题和标签:它添加了一个标题(“Prediction Error Plot”)以及 x 轴(“Predicted Values”)和 y 轴(“Errors”)的标签,以提高清晰度和理解度。
通过分析预测误差图,从业人员可以获得关于模型性能的宝贵见解,有助于进一步改进和增强模型,以获得更好、更可靠的预测。
def plot_prediction_error(y_test, y_pred, style="seaborn", plot_size=(10, 8)):
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
ax.scatter(y_pred, y_test - y_pred)
ax.axhline(y=0, color="red", linestyle="--")
ax.set_title("Prediction Error Plot", fontsize=14)
ax.set_xlabel("Predicted Values", fontsize=12)
ax.set_ylabel("Errors", fontsize=12)
plt.tight_layout()
plt.close(fig)
return fig
分位数-分位数图(QQ 图)可视化
在本节中,我们将生成一个 QQ 图来可视化我们模型预测的残差分布。
为什么这很重要?
QQ 图对于评估模型的残差是否服从正态分布至关重要,这是线性回归模型中的一个基本假设。如果 QQ 图中的点不紧密跟随直线并显示出模式,则表明残差可能不服从正态分布,这可能意味着模型存在问题,例如异方差或非线性。
代码结构:
- 残差计算:代码首先通过将预测值从实际测试值中减去来计算残差。
- 上下文设置:将绘图样式设置为“seaborn”,以获得美观的绘图。
- 图表初始化:初始化用于绘图的图表和坐标轴。
- QQ 图生成:使用
stats.probplot函数生成 QQ 图。它将残差的分位数与正态分布的分位数进行绘制。 - 添加标题:在图表中添加了标题(“QQ Plot”),以提高清晰度。
通过仔细分析 QQ 图,我们可以确保模型的残差满足正态性假设。如果不是,则可能需要探索其他模型类型或转换来提高模型的性能和可靠性。
def plot_qq(y_test, y_pred, style="seaborn", plot_size=(10, 8)):
residuals = y_test - y_pred
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
stats.probplot(residuals, dist="norm", plot=ax)
ax.set_title("QQ Plot", fontsize=14)
plt.tight_layout()
plt.close(fig)
return fig
特征相关性矩阵
在本节中,我们正在生成一个特征相关性矩阵来可视化数据集中不同特征之间的关系。
注意:与本笔记本中的其他图表不同,我们将图表保存到本地副本,以展示记录任意文件的替代机制,即 log_artifact() API。在下面的主要模型训练和日志记录部分中,您将看到此图表如何添加到 MLflow 运行中。
为什么这很重要?
理解不同特征之间的相关性对于
- 识别多重共线性,这会影响模型性能和可解释性。
- 获得变量之间关系的见解,这可以为特征工程和选择提供信息。
- 揭示不同特征之间潜在的因果关系或交互作用,这可以为领域理解和进一步分析提供信息。
代码结构:
- 相关性计算:代码首先计算给定 DataFrame 的相关性矩阵。
- 掩码:为相关性矩阵的上三角形创建了一个掩码,因为矩阵是对称的,我们不需要可视化重复的信息。
- 热力图生成:生成一个热力图来可视化相关性系数。颜色梯度和注释提供了变量之间关系的清晰见解。
- 添加标题:添加了一个标题以清晰地标识图表。
通过分析相关性矩阵,我们可以就特征选择做出更明智的决策,并更好地理解数据集中的关系。
def plot_correlation_matrix_and_save(
df, style="seaborn", plot_size=(10, 8), path="/tmp/corr_plot.png"
):
with plt.style.context(style=style):
fig, ax = plt.subplots(figsize=plot_size)
# Calculate the correlation matrix
corr = df.corr()
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(
corr,
mask=mask,
cmap="coolwarm",
vmax=0.3,
center=0,
square=True,
linewidths=0.5,
annot=True,
fmt=".2f",
)
ax.set_title("Feature Correlation Matrix", fontsize=14)
plt.tight_layout()
plt.close(fig)
# convert to filesystem path spec for os compatibility
save_path = pathlib.Path(path)
fig.savefig(save_path)
模型训练和可视化主执行的详细概述
本节深入探讨了为模型训练、预测、错误计算和可视化执行的全面工作流程。详细讨论了每个步骤的意义以及特定选择的原因。
结构化执行的好处
以结构化的方式执行模型训练和评估的所有关键步骤是至关重要的。它提供了一个框架,确保考虑了建模过程的每个方面,从而提供更可靠、更强大的模型。这种精简的执行有助于避免被忽略的错误或偏差,并确保模型在所有必要的方面都得到评估。
将可视化记录到 MLflow 的重要性
将可视化记录到 MLflow 可带来几个关键优势
-
持久性:与笔记本的临时状态不同,笔记本中的单元格可能按任意顺序运行,导致潜在的误解,将图表记录到 MLflow 可确保可视化与特定运行永久存储。这种持久性保证了模型训练和评估的可视化上下文得以保留,消除了混淆并确保了解释的清晰度。
-
可追溯性:通过记录可视化,可以捕获模型训练时数据的确切状态和关系。这种做法对于很久以前训练的模型至关重要。它提供了一个可靠的参考点来理解模型行为和训练时的数据特征,从而确保见解和解释随着时间的推移保持有效和可靠。
-
可访问性:将可视化存储在 MLflow 中,所有参与的团队成员或利益相关者都可以轻松访问。这种可视化的集中存储增强了协作,允许不同的团队成员轻松查看、分析和解释可视化,从而做出更明智、更集体的决策。
代码的详细结构:
-
设置 MLflow:
- 定义了 MLflow 的跟踪 URI。
- 设置了一个名为“Visualizations Demo”的实验,所有运行和日志都将存储在该实验下。
-
数据准备:
X和y分别定义为特征和目标变量。- 数据集被划分为训练集和测试集,以确保模型的性能在未见过的数据上得到评估。
-
初始图表生成:
- 生成了包括 time series、箱形图、散点图和密度图在内的初始图表。
- 这些图表提供了对数据及其特征的初步见解。
-
模型定义和训练:
- 定义了一个
alpha为 1.0 的 Ridge 回归模型。 - 模型在训练数据上进行训练,学习数据中的关系和模式。
- 定义了一个
-
预测和误差计算:
- 使用训练好的模型对测试数据进行预测。
- 计算了包括 MSE、RMSE、MAE、R2、MSLE 和 MedAE 在内的各种误差指标来评估模型性能。
-
附加图表生成:
- 生成了包括残差图、系数图、预测误差图和 QQ 图在内的附加图表。
- 这些图表提供了对模型性能、残差行为和误差分布的进一步见解。
-
记录到 MLflow:
- 训练好的模型、计算出的指标、定义的参数 (
alpha) 以及所有生成的图表都已记录到 MLflow。 - 此日志记录可确保与模型相关的所有信息和可视化都存储在一个集中、可访问的位置。
- 训练好的模型、计算出的指标、定义的参数 (
结论:
通过执行此全面且结构化的代码,我们确保涵盖了模型训练、评估和解释的每个方面。将所有相关信息和可视化记录到 MLflow 的做法进一步增强了模型及其性能的可靠性、可访问性和可解释性,从而有助于做出更明智、更可靠的模型部署和利用。
mlflow.set_tracking_uri("http://127.0.0.1:8080")
mlflow.set_experiment("Visualizations Demo")
X = my_data.drop(columns=["demand", "date"])
y = my_data["demand"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
fig1 = plot_time_series_demand(my_data, window_size=28)
fig2 = plot_box_weekend(my_data)
fig3 = plot_scatter_demand_price(my_data)
fig4 = plot_density_weekday_weekend(my_data)
# Execute the correlation plot, saving the plot to a local temporary directory
plot_correlation_matrix_and_save(my_data)
# Define our Ridge model
model = Ridge(alpha=1.0)
# Train the model
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Calculate error metrics
mse = mean_squared_error(y_test, y_pred)
rmse = math.sqrt(mse)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
msle = mean_squared_log_error(y_test, y_pred)
medae = median_absolute_error(y_test, y_pred)
# Generate prediction-dependent plots
fig5 = plot_residuals(y_test, y_pred)
fig6 = plot_coefficients(model, X_test.columns)
fig7 = plot_prediction_error(y_test, y_pred)
fig8 = plot_qq(y_test, y_pred)
# Start an MLflow run for logging metrics, parameters, the model, and our figures
with mlflow.start_run() as run:
# Log the model
mlflow.sklearn.log_model(sk_model=model, input_example=X_test, name="model")
# Log the metrics
mlflow.log_metrics(
{"mse": mse, "rmse": rmse, "mae": mae, "r2": r2, "msle": msle, "medae": medae}
)
# Log the hyperparameter
mlflow.log_param("alpha", 1.0)
# Log plots
mlflow.log_figure(fig1, "time_series_demand.png")
mlflow.log_figure(fig2, "box_weekend.png")
mlflow.log_figure(fig3, "scatter_demand_price.png")
mlflow.log_figure(fig4, "density_weekday_weekend.png")
mlflow.log_figure(fig5, "residuals_plot.png")
mlflow.log_figure(fig6, "coefficients_plot.png")
mlflow.log_figure(fig7, "prediction_errors.png")
mlflow.log_figure(fig8, "qq_plot.png")
# Log the saved correlation matrix plot by referring to the local file system location
mlflow.log_artifact("/tmp/corr_plot.png")
2023/09/26 13:10:41 INFO mlflow.tracking.fluent: Experiment with name 'Visualizations Demo' does not exist. Creating a new experiment.
/Users/benjamin.wilson/miniconda3/envs/mlflow-dev-env/lib/python3.8/site-packages/mlflow/models/signature.py:333: UserWarning: Hint: Inferred schema contains integer column(s). Integer columns in Python cannot represent missing values. If your input data contains missing values at inference time, it will be encoded as floats and will cause a schema enforcement error. The best way to avoid this problem is to infer the model schema based on a realistic data sample (training dataset) that includes missing values. Alternatively, you can declare integer columns as doubles (float64) whenever these columns may have missing values. See `Handling Integers With Missing Values <https://www.mlflow.org/docs/latest/models.html#handling-integers-with-missing-values>`_ for more details.
input_schema = _infer_schema(input_ex)
/Users/benjamin.wilson/miniconda3/envs/mlflow-dev-env/lib/python3.8/site-packages/_distutils_hack/__init__.py:30: UserWarning: Setuptools is replacing distutils.
warnings.warn("Setuptools is replacing distutils.")