网站在哪里找,建设网站制作,加盟网网站建设策划书,学校的网站怎么做运行环境#xff1a;Google Colab
处理缺失数据可简单分为两种方法#xff1a;1. 删除具有缺失值的列 2. 填充
!git clone https://github.com/JeffereyWu/Housing-prices-data.git下载数据集
import pandas as pd
from sklearn.model_selection import train_test_split导…运行环境Google Colab
处理缺失数据可简单分为两种方法1. 删除具有缺失值的列 2. 填充
!git clone https://github.com/JeffereyWu/Housing-prices-data.git下载数据集
import pandas as pd
from sklearn.model_selection import train_test_split导入库
# Read the data
X_full pd.read_csv(/content/Housing-prices-data/train.csv, index_colId)
X_test_full pd.read_csv(/content/Housing-prices-data/test.csv, index_colId)读取数据index_colId是为了将数据框的索引列设置为’Id’列。
# Remove rows with missing target, separate target from predictors
X_full.dropna(axis0, subset[SalePrice], inplaceTrue)
y X_full.SalePrice
X_full.drop([SalePrice], axis1, inplaceTrue)SalePrice 是我们尝试预测的目标变量。删除训练数据中带有缺失目标值‘SalePrice’的行。将目标值‘SalePrice’存储在变量y中并从特征中删除。
# To keep things simple, well use only numerical predictors
X X_full.select_dtypes(exclude[object])
X_test X_test_full.select_dtypes(exclude[object])将特征数据限制为仅包含数值型特征select_dtypes 函数用于根据数据类型在这里是’object’即非数值型选择特定类型的列。
X_train, X_valid, y_train, y_valid train_test_split(X, y, train_size0.8, test_size0.2,random_state0)使用train_test_split 函数将训练数据X和目标值y分成训练集和验证集。train_size参数指定了训练集的比例80%test_size参数指定了验证集的比例20%random_state参数用于控制随机分割的种子以确保每次运行代码时分割结果都一样。
1. 了解训练数据的形状和每列数据中缺失值的数量
# Shape of training data (num_rows, num_columns)
print(X_train.shape)# Number of missing values in each column of training data
missing_val_count_by_column (X_train.isnull().sum())
print(missing_val_count_by_column[missing_val_count_by_column 0])首先使用.isnull()方法将每个单元格是否为缺失值进行检查然后使用.sum()方法计算每列中缺失值的总数。最后它打印出那些包含至少一个缺失值的列的缺失值数量。这段代码可以帮助你了解哪些特征列在训练数据中存在缺失值以便在数据预处理过程中采取适当的措施来处理这些缺失值例如填充它们或者删除相关的特征。
考虑到数据中缺失值的数量并不是很多如果我们删除带有缺失值的列那么就会丢失掉很多有用的信息。因此更好的做法是对缺失值进行填充imputation以尽量保留数据的完整性。填充缺失值通常可以采用一些方法如用平均值、中位数或者其他相关数据来替代缺失值这样可以更好地保留数据的特征和信息提高模型的性能。
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error# Function for comparing different approaches
def score_dataset(X_train, X_valid, y_train, y_valid):model RandomForestRegressor(n_estimators100, random_state0)model.fit(X_train, y_train)preds model.predict(X_valid)return mean_absolute_error(y_valid, preds)RandomForestRegressor 是一个随机森林回归模型用于机器学习中的回归问题。mean_absolute_error 是一个评估回归模型性能的函数它用于计算预测值与实际值之间的平均绝对误差。函数的目的是通过比较不同数据集处理方法的分数来评估哪种方法在机器学习任务中效果最好。
# Get names of columns with missing values
cols_with_missing [col for col in X_train.columnsif X_train[col].isnull().any()]# Drop columns in training and validation data
reduced_X_train X_train.drop(cols_with_missing, axis1)
reduced_X_valid X_valid.drop(cols_with_missing, axis1)创建了一个列表cols_with_missing用于存储训练数据X_train中具有缺失值的列名。遍历X_train的每一列使用.isnull().any()来检查每列是否包含任何缺失值。如果某列中至少有一个缺失值就将其列名添加到cols_with_missing列表中。使用.drop()方法从训练数据X_train和验证数据X_valid中删除具有缺失值的列。cols_with_missing列表中包含了所有具有缺失值的列名通过axis1参数可以指定删除列而不是行。
print(MAE (Drop columns with missing values):)
print(score_dataset(reduced_X_train, reduced_X_valid, y_train, y_valid))2. 数据填充
from sklearn.impute import SimpleImputer# Imputation
my_imputer SimpleImputer()
imputed_X_train pd.DataFrame(my_imputer.fit_transform(X_train))
imputed_X_valid pd.DataFrame(my_imputer.transform(X_valid))# Imputation removed column names; put them back
imputed_X_train.columns X_train.columns
imputed_X_valid.columns X_valid.columns导入了Scikit-learn库中的SimpleImputer类该类用于处理缺失值它可以用于填充数据中的缺失值。分别使用fit_transform方法来对训练数据X_train和验证数据X_valid进行缺失值填充。在训练过程中模型需要学习如何处理缺失值以及其他特征因此使用fit_transform方法对训练数据进行预处理。使用transform方法对验证数据进行数据预处理包括填充缺失值。在验证过程中模型不应该再次拟合填充器因为这会导致信息泄露。模型在实际应用中不会在新的数据上重新拟合填充器而是使用在训练数据上学到的填充策略。将填充后的数据框中的列名恢复为原始数据X_train和X_valid的列名。这是因为在填充数据时列名可能被丢失。
print(MAE (Imputation):)
print(score_dataset(imputed_X_train, imputed_X_valid, y_train, y_valid))这里我们可以看到填充的方法没有删除的方法成效好。由于数据集中缺失值很少所以通常来说使用填充方法来处理缺失值应该比完全删除带有缺失值的列更好。但是在实际情况中填充的方式也需要谨慎选择不一定每次都使用均值填充就是最佳选择。具体的填充策略需要根据数据的特点和背后的含义来确定可能需要尝试不同的填充方式以找到最合适的方法。同时一些填充方式可能会导致糟糕的结果因此需要谨慎评估和选择。
3. 对训练数据和验证数据进行最终的数据预处理
# Preprocessed training and validation features
final_imputer SimpleImputer(strategymedian)
final_X_train pd.DataFrame(final_imputer.fit_transform(X_train))
final_X_valid pd.DataFrame(final_imputer.transform(X_valid))final_X_train.columns X_train.columns
final_X_valid.columns X_valid.columns设置填充策略为’median’中位数。这意味着缺失值将会使用每列的中位数值来进行填充。
# Define and fit model
model RandomForestRegressor(n_estimators100, random_state0)
model.fit(final_X_train, y_train)# Get validation predictions and MAE
preds_valid model.predict(final_X_valid)
print(MAE (Your approach):)
print(mean_absolute_error(y_valid, preds_valid))# Fill in the line below: preprocess test data
final_X_test pd.DataFrame(final_imputer.transform(X_test))
final_X_test.columns X_test.columns# Fill in the line below: get test predictions
preds_test model.predict(final_X_test)# Save test predictions to file
output pd.DataFrame({Id: X_test.index,SalePrice: preds_test})
output.to_csv(submission.csv, indexFalse)
文章转载自: http://www.morning.sfyqs.cn.gov.cn.sfyqs.cn http://www.morning.rkfxc.cn.gov.cn.rkfxc.cn http://www.morning.flqbg.cn.gov.cn.flqbg.cn http://www.morning.nggbf.cn.gov.cn.nggbf.cn http://www.morning.hqgkx.cn.gov.cn.hqgkx.cn http://www.morning.xtkw.cn.gov.cn.xtkw.cn http://www.morning.madamli.com.gov.cn.madamli.com http://www.morning.xstfp.cn.gov.cn.xstfp.cn http://www.morning.dmfdl.cn.gov.cn.dmfdl.cn http://www.morning.cplym.cn.gov.cn.cplym.cn http://www.morning.bfmq.cn.gov.cn.bfmq.cn http://www.morning.yjfzk.cn.gov.cn.yjfzk.cn http://www.morning.mqlsf.cn.gov.cn.mqlsf.cn http://www.morning.wbxtx.cn.gov.cn.wbxtx.cn http://www.morning.frqtc.cn.gov.cn.frqtc.cn http://www.morning.gfqjf.cn.gov.cn.gfqjf.cn http://www.morning.qcsbs.cn.gov.cn.qcsbs.cn http://www.morning.ybmp.cn.gov.cn.ybmp.cn http://www.morning.fosfox.com.gov.cn.fosfox.com http://www.morning.fkgct.cn.gov.cn.fkgct.cn http://www.morning.fxpyt.cn.gov.cn.fxpyt.cn http://www.morning.tpchy.cn.gov.cn.tpchy.cn http://www.morning.qbfkz.cn.gov.cn.qbfkz.cn http://www.morning.kzpy.cn.gov.cn.kzpy.cn http://www.morning.wtnyg.cn.gov.cn.wtnyg.cn http://www.morning.kfstq.cn.gov.cn.kfstq.cn http://www.morning.zxqqx.cn.gov.cn.zxqqx.cn http://www.morning.ltksw.cn.gov.cn.ltksw.cn http://www.morning.nrwr.cn.gov.cn.nrwr.cn http://www.morning.tkryt.cn.gov.cn.tkryt.cn http://www.morning.fdwlg.cn.gov.cn.fdwlg.cn http://www.morning.wrtsm.cn.gov.cn.wrtsm.cn http://www.morning.gjwkl.cn.gov.cn.gjwkl.cn http://www.morning.mnbcj.cn.gov.cn.mnbcj.cn http://www.morning.kaakyy.com.gov.cn.kaakyy.com http://www.morning.gassnw.com.gov.cn.gassnw.com http://www.morning.lwgrf.cn.gov.cn.lwgrf.cn http://www.morning.wspjn.cn.gov.cn.wspjn.cn http://www.morning.pzqnj.cn.gov.cn.pzqnj.cn http://www.morning.pskjm.cn.gov.cn.pskjm.cn http://www.morning.nuobeiergw.cn.gov.cn.nuobeiergw.cn http://www.morning.wpsfc.cn.gov.cn.wpsfc.cn http://www.morning.dfkmz.cn.gov.cn.dfkmz.cn http://www.morning.bgdk.cn.gov.cn.bgdk.cn http://www.morning.fwblh.cn.gov.cn.fwblh.cn http://www.morning.kbntl.cn.gov.cn.kbntl.cn http://www.morning.pwfwk.cn.gov.cn.pwfwk.cn http://www.morning.lqtwb.cn.gov.cn.lqtwb.cn http://www.morning.pzrrq.cn.gov.cn.pzrrq.cn http://www.morning.gzzxlp.com.gov.cn.gzzxlp.com http://www.morning.fmqw.cn.gov.cn.fmqw.cn http://www.morning.ghzfx.cn.gov.cn.ghzfx.cn http://www.morning.rlqml.cn.gov.cn.rlqml.cn http://www.morning.zwsgl.cn.gov.cn.zwsgl.cn http://www.morning.c7627.cn.gov.cn.c7627.cn http://www.morning.qkpzq.cn.gov.cn.qkpzq.cn http://www.morning.webpapua.com.gov.cn.webpapua.com http://www.morning.lzbut.cn.gov.cn.lzbut.cn http://www.morning.baohum.com.gov.cn.baohum.com http://www.morning.mkygc.cn.gov.cn.mkygc.cn http://www.morning.glnfn.cn.gov.cn.glnfn.cn http://www.morning.mflqd.cn.gov.cn.mflqd.cn http://www.morning.pgfkl.cn.gov.cn.pgfkl.cn http://www.morning.sbrjj.cn.gov.cn.sbrjj.cn http://www.morning.rxdsq.cn.gov.cn.rxdsq.cn http://www.morning.ctlzf.cn.gov.cn.ctlzf.cn http://www.morning.ttaes.cn.gov.cn.ttaes.cn http://www.morning.nqyfm.cn.gov.cn.nqyfm.cn http://www.morning.wptrm.cn.gov.cn.wptrm.cn http://www.morning.chzbq.cn.gov.cn.chzbq.cn http://www.morning.dkgtr.cn.gov.cn.dkgtr.cn http://www.morning.cpfx.cn.gov.cn.cpfx.cn http://www.morning.yrhpg.cn.gov.cn.yrhpg.cn http://www.morning.qdxtj.cn.gov.cn.qdxtj.cn http://www.morning.pgfkl.cn.gov.cn.pgfkl.cn http://www.morning.mcmpq.cn.gov.cn.mcmpq.cn http://www.morning.rwjtf.cn.gov.cn.rwjtf.cn http://www.morning.ksjnl.cn.gov.cn.ksjnl.cn http://www.morning.qwqzk.cn.gov.cn.qwqzk.cn http://www.morning.lqynj.cn.gov.cn.lqynj.cn