ColumnTransformer稀疏阈值审查:零很多,为什么仍输出稠密矩阵
模型生成概念示意图:抽象表现不同分支参与格式决策,不是实际矩阵拼接结果或软件截图。
AI检查预处理流水线时,看到输出有八成是零,就判断ColumnTransformer应该返回稀疏矩阵。这个推断可能与实际结果相反:sparse_threshold用到的密度,并不总是整张矩阵中数学意义上的非零比例。分支返回什么存储格式,也会参与决定。
先把密度的分子算对
本文锁定scikit-learn 1.8.0、SciPy 1.17.0,使用二维NumPy数组和CSR矩阵,保持默认输出配置。官方接口文档说明:存在稀疏分支时,根据整体密度与阈值决定拼接格式;如果全部分支都返回稠密数据,则直接输出稠密结果。
1.8.0版本源码给出了更具体的计数:稀疏块取nnz,稠密块取行数乘列数,分母是所有块的位置总数。因此实现比较的是ρ=(稀疏块存储项数之和+稠密块位置数之和)/全部位置数,而不是逐个扫描所有块后计算count_nonzero。
还要注意nnz的名字容易误导。SciPy文档明确指出,它包括显式存储的零。稀疏结构可以不存储某个零,也可以保留一个值为零的存储项,两者展开后的数值相同,nnz却可能不同。
四行数据就能复现意外稠密化
实验让第一个分支返回4×4单位阵的CSR表示,nnz为4;第二个分支直接返回4×1全零稠密列。拼接后共有20个位置,真正非零只有4个,占比0.2。但决策分子会计入稠密列的全部4个位置,所以ρ=(4+4)/20=0.4。
默认阈值0.3下,结果因此是NumPy稠密数组。把阈值设成0.4也一样,因为比较条件是严格的ρ<sparse_threshold;只有略大于0.4时,这个例子才选择稀疏输出。代码用np.nextafter构造紧邻的更大浮点数,直接测试等号边界。
完整可运行核验
保存为test.py,按首行安装固定版本后运行。每一组都核对展开后的数值,避免把格式变化误当作特征内容变化。
# python -m pip install numpy==2.3.5 scipy==1.17.0 scikit-learn==1.8.0
import numpy as np
import scipy
import sklearn
from scipy import sparse
from numpy.testing import assert_array_equal
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import FunctionTransformer
assert sklearn.__version__ == "1.8.0", sklearn.__version__
assert scipy.__version__ == "1.17.0", scipy.__version__
def as_dense(matrix):
return matrix.toarray() if sparse.issparse(matrix) else matrix
def mixed(threshold):
return ColumnTransformer([
("sparse_part", FunctionTransformer(sparse.csr_matrix), [0, 1, 2, 3]),
("dense_zero", "passthrough", [4]),
], sparse_threshold=threshold)
X = np.column_stack([np.eye(4), np.zeros(4)])
sparse_part = sparse.csr_matrix(X[:, :4])
dense_part = X[:, [4]]
logical_density = np.count_nonzero(X) / X.size
# Mirror the version-pinned decision: sparse stored entries + dense positions.
counted = sparse_part.nnz + dense_part.shape[0] * dense_part.shape[1]
decision_density = counted / (X.shape[0] * X.shape[1])
assert logical_density == 0.2 and decision_density == 0.4
thresholds = [0.0, 0.3, 0.4, float(np.nextafter(0.4, 1.0)), 1.0]
flags = []
for threshold in thresholds:
ct = mixed(threshold)
out = ct.fit_transform(X)
expected = decision_density < threshold
assert bool(ct.sparse_output_) == expected
assert sparse.issparse(out) == expected
assert_array_equal(as_dense(out), X)
flags.append(sparse.issparse(out))
assert flags == [False, False, False, True, True]
# A threshold does not convert a collection of all-dense outputs to sparse.
all_dense = ColumnTransformer(
[("dense", "passthrough", [0, 1, 2, 3, 4])], sparse_threshold=1.0,
)
dense_out = all_dense.fit_transform(X)
assert not sparse.issparse(dense_out) and not all_dense.sparse_output_
assert_array_equal(dense_out, X)
def explicit_csr(values):
values = np.asarray(values)
n_rows, n_cols = values.shape
return sparse.csr_matrix((
values.ravel().copy(),
np.tile(np.arange(n_cols), n_rows),
np.arange(n_rows + 1) * n_cols,
), shape=values.shape)
def compact_csr(values):
result = explicit_csr(values)
result.eliminate_zeros()
return result
identity = np.eye(4)
stored = explicit_csr(identity)
compact = compact_csr(identity)
assert stored.nnz == 16 and compact.nnz == 4
assert np.count_nonzero(stored.toarray()) == 4
assert_array_equal(stored.toarray(), compact.toarray())
zero_flags = []
for conversion in [explicit_csr, compact_csr]:
ct = ColumnTransformer([
("csr", FunctionTransformer(conversion), [0, 1, 2, 3]),
], sparse_threshold=1.0)
out = ct.fit_transform(identity)
zero_flags.append(sparse.issparse(out))
assert_array_equal(as_dense(out), identity)
assert zero_flags == [False, True] # 1 < 1 is false; 0.25 < 1 is true.
# Ordinary transform reuses the fitted output-format flag.
fixed = mixed(0.5).fit(X)
future = np.ones_like(X)
future_out = fixed.transform(future)
fresh_out = mixed(0.5).fit_transform(future)
assert sparse.issparse(future_out) and not sparse.issparse(fresh_out)
assert_array_equal(as_dense(future_out), future)
assert_array_equal(fresh_out, future)
print(f"NumPy={np.__version__}, SciPy={scipy.__version__}, scikit-learn={sklearn.__version__}")
print("logical_density=", logical_density)
print("decision_density=", decision_density)
print("thresholds=", thresholds)
print("mixed_output_is_sparse=", flags)
print("all_dense_at_threshold_1_is_sparse=", sparse.issparse(dense_out))
print("stored_vs_compact_nnz=", [stored.nnz, compact.nnz])
print("explicit_zero_vs_compact_output_is_sparse=", zero_flags)
print("future_transform_vs_refit_is_sparse=", [sparse.issparse(future_out), sparse.issparse(fresh_out)])
print("Dense blocks, stored zeros, strict threshold and fitted-format checks: PASS")实际输出
NumPy=2.3.5, SciPy=1.17.0, scikit-learn=1.8.0 logical_density= 0.2 decision_density= 0.4 thresholds= [0.0, 0.3, 0.4, 0.4000000000000001, 1.0] mixed_output_is_sparse= [False, False, False, True, True] all_dense_at_threshold_1_is_sparse= False stored_vs_compact_nnz= [16, 4] explicit_zero_vs_compact_output_is_sparse= [False, True] future_transform_vs_refit_is_sparse= [True, False] Dense blocks, stored zeros, strict threshold and fitted-format checks: PASS
阈值设成1,也不是无条件稀疏
代码另建两个数值相同的单位阵:一个CSR显式保存全部16个位置,另一个删除零存储项后只保留4项。对只包含该稀疏分支的ColumnTransformer,前者ρ=1,后者ρ=0.25。阈值都设为1,前者仍输出稠密,后者才输出稀疏。
这同时验证了“nnz包含显式零”和“比较严格小于”两个细节。另一个对照把所有分支都改成稠密输出,即使阈值为1且数值中零很多,也不会自动转换为稀疏矩阵。提高阈值不能替代对分支输出类型的检查。
输出格式在拟合时确定
本版本在拟合时保存sparse_output_,普通transform沿用它,不会随每个新批次重新做密度选择。实验在ρ=0.4的数据上用阈值0.5拟合,随后传入全为1的新矩阵,仍得到稀疏输出;另建同配置对象在全1矩阵上拟合,则得到稠密输出。
这里的重新拟合只是用来定位决策时机,不是建议上线时按批次重训预处理。部署应复用与模型配套的拟合对象,同时在有代表性的输入批次上检查实际存储成本。
怎样审查AI给出的内存优化建议
依次记录分支类型、形状、稀疏块nnz、是否保留显式零,以及最终sparse_output_。需要比较数学上的非零比例时,另行定义并计算,不要把它与实现使用的计数混称为一个指标。
这个小例子证明的是格式选择规则,没有证明稀疏一定省内存或更快。CSR还要保存索引和行指针,下游估计器也可能再次转换格式。真正的内存审查应结合数据规模、数值类型、索引存储与后续算子;不能只把sparse_threshold调高就宣布优化完成。


