python 如何通過KNN來填充缺失值
看代碼吧~
# 加載庫 import numpy as np from fancyimpute import KNN from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_blobs # 創(chuàng)建模擬特征矩陣 features, _ = make_blobs(n_samples = 1000, n_features = 2, random_state = 1) # 標(biāo)準(zhǔn)化特征 scaler = StandardScaler() standardized_features = scaler.fit_transform(features) standardized_features # 制造缺失值 true_value = standardized_features[0,0] standardized_features[0,0] = np.nan standardized_features # 預(yù)測(cè) features_knn_imputed = KNN(k=5, verbose=0).fit_transform(standardized_features) # features_knn_imputed = KNN(k=5, verbose=0).complete(standardized_features) features_knn_imputed # #對(duì)比真實(shí)值和預(yù)測(cè)值 print("真實(shí)值:", true_value) print("預(yù)測(cè)值:", features_knn_imputed[0,0]) # 加載庫 import numpy as np from fancyimpute import KNN from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_blobs # 創(chuàng)建模擬特征矩陣 features, _ = make_blobs(n_samples = 1000, n_features = 2, random_state = 1) # 標(biāo)準(zhǔn)化特征 scaler = StandardScaler() standardized_features = scaler.fit_transform(features) standardized_features # 制造缺失值 true_value = standardized_features[0,0] standardized_features[0,0] = np.nan standardized_features # 預(yù)測(cè) features_knn_imputed = KNN(k=5, verbose=0).fit_transform(standardized_features) # features_knn_imputed = KNN(k=5, verbose=0).complete(standardized_features) features_knn_imputed # #對(duì)比真實(shí)值和預(yù)測(cè)值 print("真實(shí)值:", true_value) print("預(yù)測(cè)值:", features_knn_imputed[0,0]) 真實(shí)值: 0.8730186113995938 預(yù)測(cè)值: 1.0955332713113226
補(bǔ)充:scikit-learn中一種便捷可靠的缺失值填充方法:KNNImputer
在數(shù)據(jù)挖掘工作中,處理樣本中的缺失值是必不可少的一步。其中對(duì)于缺失值插補(bǔ)方法的選擇至關(guān)重要,因?yàn)樗鼤?huì)對(duì)最后模型擬合的效果產(chǎn)生重要影響。
在2019年底,scikit-learn發(fā)布了0.22版本,此次版本除了修復(fù)之前的一些bug外,還更新了很多新功能,對(duì)于數(shù)據(jù)挖掘人員來說更加好用了。其中我發(fā)現(xiàn)了一個(gè)新增的非常好用的缺失值插補(bǔ)方法:KNNImputer。這個(gè)基于KNN算法的新方法使得我們現(xiàn)在可以更便捷地處理缺失值,并且與直接用均值、中位數(shù)相比更為可靠。利用“近朱者赤”的KNN算法原理,這種插補(bǔ)方法借助其他特征的分布來對(duì)目標(biāo)特征進(jìn)行缺失值填充。
下面,就讓我們用實(shí)際例子來看看KNNImputer是如何使用的吧
使用KNNImputer需要從scikit-learn中導(dǎo)入:
from sklearn.impute import KNNImputer
先來一個(gè)小例子開開胃,data中第二個(gè)樣本存在缺失值。
data = [[2, 4, 8], [3, np.nan, 7], [5, 8, 3], [4, 3, 8]]
KNNImputer中的超參數(shù)與KNN算法一樣,n_neighbors為選擇“鄰居”樣本的個(gè)數(shù),先試試n_neighbors=1。
imputer = KNNImputer(n_neighbors=1) imputer.fit_transform(data)
可以看到,因?yàn)榈诙€(gè)樣本的第一列特征3和第三列特征7,與第一行樣本的第一列特征2和第三列特征8的歐氏距離最近,所以缺失值按照第一個(gè)樣本來填充,填充值為4。那么n_neighbors=2呢?
imputer = KNNImputer(n_neighbors=2) imputer.fit_transform(data)
此時(shí)根據(jù)歐氏距離算出最近相鄰的是第一行樣本與第四行樣本,此時(shí)的填充值就是這兩個(gè)樣本第二列特征4和3的均值:3.5。
接下來讓我們看一個(gè)實(shí)際案例,該數(shù)據(jù)集來自Kaggle皮馬人糖尿病預(yù)測(cè)的分類賽題,其中有不少缺失值,我們?cè)囋囉肒NNImputer進(jìn)行插補(bǔ)。
import numpy as np import pandas as pd import pandas_profiling as pp import matplotlib.pyplot as plt import seaborn as sns sns.set(context="notebook", style="darkgrid") import warnings warnings.filterwarnings('ignore') %matplotlib inline from sklearn.impute import KNNImputer
#Loading the dataset diabetes_data = pd.read_csv('pima-indians-diabetes.csv') diabetes_data.columns = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age', 'Outcome'] diabetes_data.head()
在這個(gè)數(shù)據(jù)集中,0值代表的就是缺失值,所以我們需要先將0轉(zhuǎn)化為nan值然后進(jìn)行缺失值處理。
diabetes_data_copy = diabetes_data.copy(deep=True) diabetes_data_copy[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']] = diabetes_data_copy[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']].replace(0, np.NaN) print(diabetes_data_copy.isnull().sum())
在本文中,我們嘗試用DiabetesPedigreeFunction與Age,對(duì)BloodPressure中的35個(gè)缺失值進(jìn)行KNNImputer插補(bǔ)。
先來看一下缺失值都在哪幾個(gè)樣本:
null_index = diabetes_data_copy.loc[diabetes_data_copy['BloodPressure'].isnull(), :].index null_index
imputer = KNNImputer(n_neighbors=10) diabetes_data_copy[['BloodPressure', 'DiabetesPedigreeFunction', 'Age']] = imputer.fit_transform(diabetes_data_copy[['BloodPressure', 'DiabetesPedigreeFunction', 'Age']]) print(diabetes_data_copy.isnull().sum())
可以看到現(xiàn)在BloodPressure中的35個(gè)缺失值消失了。我們看看具體填充后的數(shù)據(jù)(只截圖了部分):
diabetes_data_copy.iloc[null_index]
到此,BloodPressure中的缺失值已經(jīng)根據(jù)DiabetesPedigreeFunction與Age運(yùn)用KNNImputer填充完成了。注意的是,對(duì)于非數(shù)值型特征需要先轉(zhuǎn)換為數(shù)值型特征再進(jìn)行KNNImputer填充操作,因?yàn)槟壳癒NNImputer方法只支持?jǐn)?shù)值型特征(ʘ̆ωʘ̥̆‖)՞。
相關(guān)文章
python使用paramiko模塊通過ssh2協(xié)議對(duì)交換機(jī)進(jìn)行配置的方法
今天小編就為大家分享一篇python使用paramiko模塊通過ssh2協(xié)議對(duì)交換機(jī)進(jìn)行配置的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-07-07Python 靜態(tài)導(dǎo)入與動(dòng)態(tài)導(dǎo)入的實(shí)現(xiàn)示例
Python靜態(tài)導(dǎo)入和動(dòng)態(tài)導(dǎo)入是指導(dǎo)入模塊或模塊內(nèi)部函數(shù)的兩種方式,本文主要介紹了Python 靜態(tài)導(dǎo)入與動(dòng)態(tài)導(dǎo)入的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05python數(shù)據(jù)可視化 – 利用Bokeh和Bottle.py在網(wǎng)頁上展示你的數(shù)據(jù)
本文將展示如何使用python搭建一個(gè)網(wǎng)頁應(yīng)用來展示你的數(shù)據(jù)圖表 很多有關(guān)于使用python搭建網(wǎng)頁應(yīng)用的文章聚焦在如何教讀者搭建一個(gè)網(wǎng)頁應(yīng)用(大多是博客),很多關(guān)于使用python做數(shù)據(jù)可視化的文章聚焦在如何教讀者使用python的圖表庫來做可視化2021-10-10Scrapy爬蟲多線程導(dǎo)致抓取錯(cuò)亂的問題解決
本文針對(duì)Scrapy爬蟲多線程導(dǎo)致抓取錯(cuò)亂的問題進(jìn)行了深入分析,并提出了相應(yīng)的解決方案,具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11Collatz 序列、逗號(hào)代碼、字符圖網(wǎng)格實(shí)例
下面小編就為大家?guī)硪黄狢ollatz 序列、逗號(hào)代碼、字符圖網(wǎng)格實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06利用Python找出刪除自己微信的好友并將他們自動(dòng)化刪除
你是否有微信被刪了好友不自知,還傻傻的給對(duì)方發(fā)消息,結(jié)果出現(xiàn)了下圖中那尷尬的一幕的經(jīng)歷呢?其實(shí)我們可以用Python提前把他們找出來并自動(dòng)化刪除避免尷尬的2023-01-01