Search code examples
pythonpandasmachine-learningscikit-learnpipeline

scikit learn classifier with mixed type features returns 0% accuracy with test data


I'm new to machine learning and python. I want to use the DecisionTreeClassifier from sklearn. Since my features are part numerical and part categorical I need to transform them, because the DecisionTreeClassifier only accepts numerical features as input. To do that I'm using a ColumnTransformer and pipelines. The idea is the following:

  1. Categorical and numerical features get transformed in seperate pipelines
  2. Both combined form the input for the classifier

However, the accuracy using my test data is always 0%, while my accuracy with training data is ~85%. Additionally, calling cross_val_score() returns

ValueError: Found unknown categories ['Holand-Netherlands'] in column 7 during transform

This is strange, because I used this very data to train the full_pipeline. Using different classifiers results in the same behaviour, which leads me to believe there is an issue with the transformations. Help is much appreciated!

Below is my code:

names = ["age",
         "workclass",
         "final-weight",
         "education",
         "education-num",
         "martial-status",
         "occupation",
         "relationship",
         "race",
         "sex",
         "capital-gain",
         "capial-loss",
         "hours-per-week",
         "native-country",
         "agrossincome"]

categorical_features = ["workclass", "education", "martial-status", "occupation", "relationship", "race", "sex", "native-country"]
numerical_features = ["age","final-weight", "education-num", "capital-gain", "capial-loss", "hours-per-week"] 
features = np.concatenate([categorical_features, numerical_features])


# create pandas dataframe for adult dataset
adult_train = pd.read_csv(filepath_or_buffer= "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data" ,
            delimiter= ',',
            index_col = False,
            skipinitialspace = True,
            header = None,
            names = names )

adult_test = pd.read_csv( filepath_or_buffer= "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test" ,
            delimiter= ',',
            index_col = False,
            skipinitialspace = True,
            header = None,
            names = names )

adult_test.drop(0, inplace =True)
adult_test.reset_index(inplace = True)
adult_train.replace(to_replace= "?", value = np.NaN, inplace = True)
adult_test.replace(to_replace= "?", value = np.NaN, inplace= True)


# split data into features and targets
x_train = adult_train[features]
y_train = adult_train.agrossincome

x_test = adult_test[features]
y_test = adult_test.agrossincome


# create pipeline for preprocessing + classifier
categorical_pipeline = Pipeline( steps = [ ( 'imputer', SimpleImputer(strategy='constant', fill_value='missing') ),
                                           ( 'encoding', OrdinalEncoder() ) 
                                         ])

numerical_pipeline = Pipeline( steps = [ ( 'imputer', SimpleImputer(strategy='median') ),
                                         ( 'std_scaler', StandardScaler( with_mean = False ) ) 
                                       ])

preprocessing = ColumnTransformer( transformers = [ ( 'categorical_pipeline', categorical_pipeline, categorical_features ), 
                                                   ( 'numerical_pipeline', numerical_pipeline, numerical_features ) ] )

full_pipeline = Pipeline(steps= [ ('preprocessing', preprocessing),
                                  ('model', DecisionTreeClassifier(random_state= 0, max_depth = 5) ) ])

full_pipeline.fit(x_train, y_train)
print(full_pipeline.score(x_test, y_test))
#print(cross_val_score(full_pipeline, x_train, y_train, cv=3).mean())

Solution

  • The error come from y_test which looks like

    enter image description here

    while

    enter image description here

    Deleting the '.' at the end should fix it

    enter image description here