用决策树随机森林填充空值

随机森林

from  sklearn import ensemble
from sklearn.preprocessing import LabelEncoder
def set_missing(df,estimate_list,miss_col):
    """df要处理的数据帧,estimate_list用来估计缺失值的字段列表,miss_col缺失字段名称;会直接在原来的数据帧上修改"""
    col_list=estimate_list
    col_list.append(miss_col)   
    process_df = df.loc[:,col_list]
    class_le= LabelEncoder()
    for i in col_list[:-1]:
        process_df.loc[:,i]=class_le.fit_transform(process_df.loc[:,i].values)
    # 分成已知该特征和未知该特征两部分
    known=process_df[process_df[miss_col].notnull()].values
    known[:, -1]=class_le.fit_transform(known[:, -1])
    unknown = process_df[process_df[miss_col].isnull()].values
    # X为特征属性值
    X = known[:, :-1]
    # y为结果标签值
    y = known[:, -1]
    # fit到RandomForestRegressor之中
    rfr = ensemble.RandomForestRegressor(random_state=1, n_estimators=200,max_depth=4,n_jobs=-1)
    rfr.fit(X,y)
    # 用得到的模型进行未知特征值预测
    predicted = rfr.predict(unknown[:, :-1]).round(0).astype(int)
    predicted=class_le.inverse_transform(predicted)
    #print(predicted)
    # 用得到的预测结果填补原缺失数据
    df.loc[(df[miss_col].isnull()), miss_col] = predicted
    return df
 

决策树

from sklearn import tree
dt=tree.DecisionTreeRegressor()
dt.fit(X,y)
predicted = clf.predict(unknown[:, :3]).round(0)
predicted=class_le.inverse_transform(predicted)
print(predicted)

原文链接:https://blog.csdn.net/qq_41780234/article/details/103306928

你可能感兴趣的:(用决策树随机森林填充空值)