使用Astartes进行采样#
如果你曾怀疑随机划分训练集/测试集是否真的是处理光谱数据的最佳方法,那么你并非一个人。随机划分可能会在你的校准集中留下空白,或者更糟的是,在两组中都放入非常相似的样本——从而导致过于乐观的误差估计。
Astartes solves this problem. It's a Python library that works as a drop-in replacement for sklearn.model_selection.train_test_split, but with access to sampling algorithms that actually make sense for chemometrics: Kennard-Stone, SPXY, and others.
为什么这很重要?#
例如,Kennard-Stone会选择最大化覆盖你光谱空间的样本。你不是希望随机抽取给你一个有代表性的校准集,而是*保证*这一点。这降低了预测新样本时的外推风险。
SPXY更进一步,在选择样本时同时考虑光谱(X)和参考值(y)——这在你的y值跨度很大时很有用。
可用的采样器#
Astartes将其采样器分为两类:
内插式:选择样本以确保*在*数据空间内的覆盖。适用于构建通用模型。
外推式:将样本分组为聚类,并保留整个聚类。这测试了模型对*未见区域*的泛化能力。
以下是一些对光谱数据最有用的采样器:
采样器 |
类型 |
使用场景 |
|---|---|---|
|
内插式 |
基线比较。与sklearn的默认设置相同。 |
|
内插式 |
光谱分析的常用选择。选择能最大化X空间覆盖的样本。 |
|
内插式 |
类似于Kennard-Stone,但也考虑y值。非常适合校准转移。 |
|
外推式 |
对样本进行聚类,然后保留整个聚类。测试对新区域的泛化能力。 |
|
外推式 |
排除距离阈值内的样本。有助于测试对数据间隙的鲁棒性。 |
完整列表(包括Scaffold等分子特定采样器),请查看 Astartes GitHub页面 。
与Chemotools结合使用#
这两个库很好地互补:
Chemotools 处理光谱预处理(平滑、基线校正、导数等)。
Astartes 在你开始建模之前处理样本选择。
两者结合,为你提供了一个干净、经过充分验证的流程。
示例:Kennard-Stone划分#
这里有一个快速示例。我们加载一些光谱,用Kennard-Stone划分它们,然后通过预处理流程运行:
from astartes import train_test_split
from chemotools.datasets import load_fermentation_train
from chemotools.baseline import AirPls
from sklearn.pipeline import make_pipeline
from sklearn.decomposition import PCA
# Load the data (returns pandas DataFrames)
X, y = load_fermentation_train()
# Split with Kennard-Stone instead of random
X_train, X_test, y_train, y_test = train_test_split(
X.values, # astartes expects numpy arrays
y.values,
train_size=0.75,
sampler='kennard_stone'
)
# Preprocess and reduce dimensionality
pipeline = make_pipeline(
AirPls(),
PCA(n_components=3)
)
pipeline.fit(X_train)
scores = pipeline.transform(X_test)
如果你希望在选择逻辑中包含y值,只需切换到 sampler='spxy' 。
安装#
Astartes不是 chemotools 的依赖项,因此你需要单独安装它:
pip install astartes
For more details, check out the Astartes documentation.