gpt4 book ai didi

python - 了解 sklearn 的 KNNImputer

转载 作者:行者123 更新时间:2023-12-03 23:47:30 28 4
gpt4 key购买 nike

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

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 s 同时有 nan s 在 2 列中?比如如果是填 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 s)被选中(注意我已经设置了 n_neighbors=1 )。这是因为最后一行的距离是 0 , 作为 NaN 对应的距离值已设置为 0 .因此,只需与行 2 的差异最小即可和 3 ,最后一行被选中,因为它被视为相等:
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.]])

关于python - 了解 sklearn 的 KNNImputer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61752284/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com