了解 sklearn 的 KNNImputer

Understanding sklearn's KNNImputer

我正在浏览它的文档,它说

Each sample’s missing values are imputed using the mean value from n_neighbors nearest neighbors found in the training set. Two samples are close if the features that neither are missing are close.

现在,摆弄一个玩具数据集,即

>>>X = [[1, 2, nan], [3, 4, 3], [nan, 6, 5], [8, 8, 7]]
>>>X

   [[ 1.,  2., nan],
    [ 3.,  4.,  3.],
    [nan,  6.,  5.],
    [ 8.,  8.,  7.]]

然后我们制作一个 KNNImputer 如下:

imputer = KNNImputer(n_neighbors=2)

问题是,它是如何填充 nan 的同时在其中 2 列中有 nan 的?例如,如果要在第 1 行的第 3 列中填充 nan,它将如何选择哪些特征最接近,因为其中一行在第一列中也有 nan?当我做 imputer.fit_transform(X) 它给了我

array([[1. , 2. , 4. ],
       [3. , 4. , 3. ],
       [5.5, 6. , 5. ],
       [8. , 8. , 7. ]])

表示填写第一行的nan,最近的邻居是第二行和第三行。它是如何计算第一行和第三行之间的欧氏距离的?

How does it fill the NaNs using rows that also have NaNs?

文档中似乎没有提到这一点。但是通过深入研究源代码,似乎对于被估算的每一列,所有 捐赠者 在较小的距离都被考虑在内,即使它们有缺失值。处理方法是将权重矩阵中的缺失值设置为 0,该权重矩阵是根据使用的距离获得的,请参见 _get_weights

相关代码在_calc_impute,其中找到所有潜在捐助者的距离矩阵,然后是上述权重矩阵,推算为:

# fill nans with zeros
if weight_matrix is not None:
    weight_matrix[np.isnan(weight_matrix)] = 0.0

如果所有潜在捐赠者与接受者

有至少一个非南距离,则所有潜在捐赠者都会被考虑
dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors)
    Distance matrix between the receivers and potential donors from
    training set. There must be at least one non-nan distance between
    a receiver and a potential donor.

我们可以用一个玩具示例来验证这一点;在下面的矩阵中,当在 [nan, 7., 4., 5.] 中输入缺失值时,最后一行(也包含两个 NaN)被选中(注意我设置了 n_neighbors=1)。这是因为最后一行的距离是 0,因为对应于 NaN 值的 距离 已设置为 0。因此,仅通过与行 23 的最小差异,选择最后一行,因为它被视为相等:

X = np.array([[np.nan,7,4,5],[2,8,4,5],[3,7,4,6],[1,np.nan,np.nan,5]])

print(X)
array([[nan,  7.,  4.,  5.],
       [ 2.,  8.,  4.,  5.],
       [ 3.,  7.,  4.,  6.],
       [ 1., nan, nan,  5.]])

from sklearn.impute import KNNImputer
imputer = KNNImputer(n_neighbors=1)

imputer.fit_transform(X)
array([[1., 7., 4., 5.],
       [2., 8., 4., 5.],
       [3., 7., 4., 6.],
       [1., 7., 4., 5.]])