from sklearn.base import BaseEstimator, TransformerMixin
rooms_ix, bedrooms_ix, population_ix, household_ix = [
list(housing.columns).index(col)
for col in ("total_rooms", "total_bedrooms", "population", "households")]
class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
def __init__(self, add_bedrooms_per_room = True): # no args or *kwargs
self.add_bedrooms_per_room = add_bedrooms_per_room
def fit(self, X, y=None):
return self # nothing else to do
def transform(self, X, y=None):
rooms_per_household = X[:, rooms_ix] / X[:, household_ix]
population_per_household = X[:, population_ix] / X[:, household_ix]
if self.add_bedrooms_per_room:
bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]
return np.c_[X, rooms_per_household, population_per_household,
bedrooms_per_room]
else:
return np.c_[X, rooms_per_household, population_per_household]
attr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False)
housing_extra_attribs = attr_adder.transform(housing.values)
THANK YOU IN ADVANCE
I just went through Chapter 2 so I'll try to explain it.
You write this piece of code to process your inputdata in a modular fashion.
Meaning you can just plugin this functionality to modify your input data if you want, or you could just as easily take it out.
The reason why we would want this is because being able to just plugin/plugout functionality makes it easier for us to create the dataprocessing-pipeline.
It makes it also easier to understand what happens to our data.
The code here is supposed to help you create additional data 'rooms_per_household' and 'population_per_household' based upon the input data 'X'.
Default there will be an additional data column created 'bedrooms_per_room', because the constructor tells it to
def __init__(self, add_bedrooms_per_room=True)
You use BaseEstimator and TransformerMixin to get access to their already built methods.
'fit_transform()', 'get_params()', 'set_params()'
You will insert this Custom Transformer into your data pipeline. (section Transformation Pipelines p70 2nd edition)
`num_pipeline = Pipeline([
('imputer',SimpleImputer(strategy="median")),
('attribs_adder',CombinedAttributesAdder()),
('std_scaler',StandardScaler())
])
I hope this answers your question?
Thanks
No problem :) you mistakingly reopened the issue I assume?
Yup
Most helpful comment
Thanks