了解sklearn的KNI计算机

2024-09-28 21:11:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我查看了它的文档,上面写着

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.]]

我们制作了一台KNI计算机,如下所示:

imputer = KNNImputer(n_neighbors=2)

问题是,当其中两列中有nan时,它是如何填充nan的?例如,如果要填充第一行第三列中的nan,由于其中一行的第一列中也有nan,它将如何选择最接近的特征?当我做imputer.fit_transform(X)它给我

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

这意味着要填写第1行中的nan,最近邻是第二行和第三行。它是如何计算第一行和第三行之间的欧几里德距离的


Tags: thesample文档closevalueneighborsnanmean
1条回答
网友
1楼 · 发布于 2024-09-28 21:11:34

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

文件中似乎没有提到这一点。但是,通过对源代码进行深入研究,似乎对于每个被插补的列,都会考虑距离较小的所有供体,即使它们缺少值。处理方法是将权重矩阵中的缺失值设置为0,该矩阵是根据使用的距离获得的,请参见^{}

相关代码在^{}中,在找到所有潜在捐赠者的距离矩阵以及上述权重矩阵后,将其插补为:

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

如果所有潜在捐赠者与接受者至少有一个非nan距离,则考虑所有潜在捐赠者

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)。这是因为最后一行的距离wrt是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.]])

相关问题 更多 >