AttributeError: ‘numpy.ndarray’ object has no attribute ‘fit’ to check if the numeric pipeline works when calling fit_transform on a pipeline works

  pipeline, python, scikit-learn

I am getting the below error when I call num_pipeline.fit_transform(data_num).

AttributeError: ‘numpy.ndarray’ object has no attribute ‘fit’

import pandas as pd
import numpy as np

data = pd.read_csv("CustomTransformerData.csv")
from sklearn.base import BaseEstimator,TransformerMixin

#column index
x1_ix, x2_ix, x3_ix, x4_ix, x5_ix = 0,1,2,3,4

class Assignment4Transformer(BaseEstimator, TransformerMixin):
    #the constructor
    def __init__(self, add_x6 = True, y = None):
        self.add_x6 = add_x6
        self.flag = True
    
    #estimator method
    def fit(self, data, y=None):
        return self
    
    #transformation
    def transform(self, data):
        #getting the two extra attributes by dividing appropriate attributes
        
        if self.add_x6:
            y = []
            x4 = (x1_ix**3) / (x5_ix)
            y.append(x4)
            x1 = (x1_ix**3) / (x5_ix)
            y.append(x1)
            x2 = (x1_ix**3) / (x5_ix)
            y.append(x2)
            x3 = (x1_ix**3) / (x5_ix)
            y.append(x3)
            x5 = (x1_ix**3) / (x5_ix)
            y.append(x5)
            x6 = (x1_ix**3) / (x5_ix)
            y.append(x6)
        return y

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([('imputer', SimpleImputer(strategy="mean")),
                         ('attribs_adder', Assignment4Transformer),
                         ('std_scaler', StandardScaler())])

data_num = data.drop("x3", axis = 1)
data_cat = data.drop(["x1", "x2", "x4", "x5"], axis = 1)

from sklearn.compose import ColumnTransformer
data_num_transformed = num_pipeline.fit_transform(data_num)

When I try the final line I just get:

AttributeError: ‘numpy.ndarray’ object has no attribute ‘fit’

Source: Python Questions

LEAVE A COMMENT