这里的重点其实是duck_typing的应用而非数据分析。
在搞一些基于DataFrame的研究的时候,经常会遇到想增加或者减少x factor的情况。以下这个类会是一个特别明显以及容易记忆的snippet。ML了解中的一些其他的知识点就这么被点亮啦啦啦:
from sklearn.base import BaseEstimator,TransformerMixin
rooms_ix,bedrooms_ix,population_ix,household_ix = 3,4,5,6
class CombinedAttributesAdder(BaseEstimator,TransformerMixin):#加入BaseEstimater就不用加其他参数了,它会自动去底下的函数里面捞;加入TransformerMixin就可以有def fix_transform这个函数了,至于transform和fit_transform的意义和用法以及差异,和本篇关系并不大,好奇的话,可以查看这个[回答](https://datascience.stackexchange.com/questions/12321/difference-between-fit-and-fit-transform-in-scikit-learn-models%20%E5%9B%9E%E7%AD%94)。
def __init__(self,add_bedrooms_per_room = True): #默认是true
self.add_bedrooms_per_room = add_bedrooms_per_room
def fit(self,X,y=None):
return self
def transform(self,X,y=None):
rooms_per_household = X[:,rooms_ix] / X[:,household_ix] #这个其实也该多看看,取了所有行的第rooms_ix和 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]