为测试集计算缺失值

时间:2018-01-29 06:15:29

标签: python machine-learning

我使用了adult data here,为训练数据计算了缺失值,而我希望将从训练数据获得的相同数字应用于测试数据。我必须错过一些东西,不能把它弄好。我的代码如下:

import numpy as np
import pandas as pd
from sklearn.base import TransformerMixin
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")

features = ['age','workclass','fnlwgt','education','educationNum','maritalStatus','occupation','relationship','race','sex','capitalGain','capitalLoss','hoursPerWeek','nativeCountry']

x_train = train[list(features)]
y_train = train['class']
x_test = test[list(features)]
y_test = test['class']

class DataFrameImputer(TransformerMixin):
    def _init_(self):
        """Impute missing values.
        Columns of dtype object are imputed with the most frequent value in column.
        columns of other types are imputed with mean of column"""
    def fit(self, X, y=None):
        self.fill = pd.Series([X[c].value_counts().index[0]
                               if X[c].dtype == np.dtype('O') else X[c].mean() for c in X],
                              index=X.columns)
        return self

    def transform(self, X, y=None):
        return X.fillna(self.fill)


# 2 step transformation, fit and transform
# -------Impute missing values-------------

x_train = pd.DataFrame(x_train)  # x_train is class
x_test = pd.DataFrame(x_test)
x_train_new = DataFrameImputer().fit_transform(x_train)
x_train_new = pd.DataFrame(x_train_new)
# use same value fitted training data to fit test data

for c in x_test:
    if x_test[c].dtype==np.dtype('O'):
        x_test.fillna(x_train[c].value_counts().index[0])
    else:
        x_test.fillna(x_train[c].mean(),inplace=True)

1 个答案:

答案 0 :(得分:-1)

我们希望使用从训练数据中获得的内容,将其应用于测试数据,在上一段代码中,循环不起作用,第一列是一列数字,因此它将填充所有NaN在测试数据中作为第一列训练数据的平均值。相反,如果我使用fillna值,这里的值是字典,测试数据将根据类别匹配训练数据。

values = {} #declare dict
for c in x_train:
    if x_train[c].dtype==np.dtype('O'):
        values[c]=x_train[c].value_counts().index[0]
    else:
        values[c]=x_train[c].mean()
    values.update({c:values[c]})

x_test_new = x_test.fillna(value=values)