You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DictVectorizer稀疏数组特征索引疑问:温度值为何索引为(0,3)?

问题解析:DictVectorizer输出稀疏矩阵的索引对应关系

代码示例

measurements = [
     {'city': 'Dubai', 'temperature': 33.},
     {'city': 'London', 'temperature': 12.},
     {'city': 'San Francisco', 'temperature': 18.}]
vec = DictVectorizer()
transformed_sparse = vec.fit_transform(measurements)
print(transformed_sparse)

运行结果

(0, 0)    1.0
  (0, 3)    33.0
  (1, 1)    1.0
  (1, 3)    12.0
  (2, 2)    1.0
  (2, 3)    18.0

疑问解答

稀疏矩阵中温度值的索引为(0,3),核心原因是DictVectorizer的特征转换规则:

  • 对于类别型特征(比如city字段,取值为离散字符串),工具会自动将每个不同取值转换成独立的独热编码列;
  • 对于数值型特征(比如temperature字段,取值为数值),直接保留为单独一列。

你可以调用vec.get_feature_names_out()查看特征与索引的对应关系,输出结果为:

['city=Dubai', 'city=London', 'city=San Francisco', 'temperature']

可见:

  • 索引0对应city=Dubai,索引1对应city=London,索引2对应city=San Francisco,这三列都是city字段拆分出的独热编码列;
  • 索引3对应temperature,即数值特征列。

所以第一行的温度值会出现在(0,3)的位置——前3列都是city的衍生列,temperature是第4列(从0开始计数,索引为3),并非你预期的第二列。

内容的提问来源于stack exchange,提问作者Junior Developers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:45:21