为机器学习算法准备数据
现在来为机器学习算法准备数据。不要手工来做,你需要写一些函数,理由如下:
函数可以让你在任何数据集上(比如,你下一次获取的是一个新的数据集)方便地进行重复数据转换。
你能慢慢建立一个转换函数库,可以在未来的项目中复用。
在将数据传给算法之前,你可以在实时系统中使用这些函数。
这可以让你方便地尝试多种数据转换,查看哪些转换方法结合起来效果最好。
但是,还是先回到干净的训练集(通过再次复制strat_train_set),将预测量和标签分开,因为我们不想对预测量和目标值应用相同的转换(注意drop()创建了一份数据的备份,而不影响strat_train_set):
housing = strat_train_set.drop("median_house_value", axis=1)housing_labels = strat_train_set["median_house_value"].copy()
数据清洗
大多机器学习算法不能处理缺失的特征,因此先创建一些函数来处理特征缺失的问题。前面,你应该注意到了属性total_bedrooms有一些缺失值。有三个解决选项:
去掉对应的街区;
去掉整个属性;
进行赋值(0、平均值、中位数等等)。
用DataFrame的dropna(),drop(),和fillna()方法,可以方便地实现:
housing.dropna(subset=["total_bedrooms"]) # 选项1housing.drop("total_bedrooms", axis=1) # 选项2median = housing["total_bedrooms"].median()housing["total_bedrooms"].fillna(median) # 选项3
如果选择选项 3,你需要计算训练集的中位数,用中位数填充训练集的缺失值,不要忘记保存该中位数。后面用测试集评估系统时,需要替换测试集中的缺失值,也可以用来实时替换新数据中的缺失值。
Scikit-Learn 提供了一个方便的类来处理缺失值:Imputer。下面是其使用方法:首先,需要创建一个Imputer实例,指定用某属性的中位数来替换该属性所有的缺失值:
from sklearn.preprocessing import Imputerimputer = Imputer(strategy="median")
因为只有数值属性才能算出中位数,我们需要创建一份不包括文本属性ocean_proximity的数据副本:
housing_num = housing.drop("ocean_proximity", axis=1)
现在,就可以用fit()方法将imputer实例拟合到训练数据:
imputer.fit(housing_num)
imputer计算出了每个属性的中位数,并将结果保存在了实例变量statistics_中。虽然此时只有属性total_bedrooms存在缺失值,但我们不能确定在以后的新的数据中会不会有其他属性也存在缺失值,所以安全的做法是将imputer应用到每个数值:
>>> imputer.statistics_array([ -118.51 , 34.26 , 29. , 2119. , 433. , 1164. , 408. , 3.5414])>>> housing_num.median().valuesarray([ -118.51 , 34.26 , 29. , 2119. , 433. , 1164. , 408. , 3.5414])
现在,你就可以使用这个“训练过的”imputer来对训练集进行转换,将缺失值替换为中位数:
X = imputer.transform(housing_num)
结果是一个包含转换后特征的普通的 Numpy 数组。如果你想将其放回到 PandasDataFrame中,也很简单:
housing_tr = pd.DataFrame(X, columns=housing_num.columns)
Scikit-Learn 设计
Scikit-Learn 设计的 API 设计的非常好。它的主要设计原则是:
一致性:所有对象的接口一致且简单:
- 估计器(estimator)。任何可以基于数据集对一些参数进行估计的对象都被称为估计器(比如,
imputer就是个估计器)。估计本身是通过fit()方法,只需要一个数据集作为参数(对于监督学习算法,需要两个数据集;第二个数据集包含标签)。任何其它用来指导估计过程的参数都被当做超参数(比如imputer的strategy),并且超参数要被设置成实例变量(通常通过构造器参数设置)。- 转换器(transformer)。一些估计器(比如
imputer)也可以转换数据集,这些估计器被称为转换器。API也是相当简单:转换是通过transform()方法,被转换的数据集作为参数。返回的是经过转换的数据集。转换过程依赖学习到的参数,比如imputer的例子。所有的转换都有一个便捷的方法fit_transform(),等同于调用fit()再transform()(但有时fit_transform()经过优化,运行的更快)。- 预测器(predictor)。最后,一些估计器可以根据给出的数据集做预测,这些估计器称为预测器。例如,上一章的
LinearRegression模型就是一个预测器:它根据一个国家的人均 GDP 预测生活满意度。预测器有一个predict()方法,可以用新实例的数据集做出相应的预测。预测器还有一个score()方法,可以根据测试集(和相应的标签,如果是监督学习算法的话)对预测进行衡器。可检验。所有估计器的超参数都可以通过实例的public变量直接访问(比如,
imputer.strategy),并且所有估计器学习到的参数也可以通过在实例变量名后加下划线来访问(比如,imputer.statistics_)。类不可扩散。数据集被表示成 NumPy 数组或 SciPy 稀疏矩阵,而不是自制的类。超参数只是普通的 Python 字符串或数字。
可组合。尽可能使用现存的模块。例如,用任意的转换器序列加上一个估计器,就可以做成一个流水线,后面会看到例子。
合理的默认值。Scikit-Learn 给大多数参数提供了合理的默认值,很容易就能创建一个系统。
处理文本和类别属性
前面,我们丢弃了类别属性ocean_proximity,因为它是一个文本属性,不能计算出中位数。大多数机器学习算法跟喜欢和数字打交道,所以让我们把这些文本标签转换为数字。
Scikit-Learn 为这个任务提供了一个转换器LabelEncoder:
>>> from sklearn.preprocessing import LabelEncoder>>> encoder = LabelEncoder()>>> housing_cat = housing["ocean_proximity"]>>> housing_cat_encoded = encoder.fit_transform(housing_cat)>>> housing_cat_encodedarray([1, 1, 4, ..., 1, 0, 3])
译注:
在原书中使用
LabelEncoder转换器来转换文本特征列的方式是错误的,该转换器只能用来转换标签(正如其名)。在这里使用LabelEncoder没有出错的原因是该数据只有一列文本特征值,在有多个文本特征列的时候就会出错。应使用factorize()方法来进行操作:
housing_cat_encoded, housing_categories = housing_cat.factorize()housing_cat_encoded[:10]
好了一些,现在就可以在任何 ML 算法里用这个数值数据了。你可以查看映射表,编码器是通过属性classes_来学习的(<1H OCEAN被映射为 0,INLAND被映射为 1,等等):
>>> print(encoder.classes_)['<1H OCEAN' 'INLAND' 'ISLAND' 'NEAR BAY' 'NEAR OCEAN']
这种做法的问题是,ML 算法会认为两个临近的值比两个疏远的值要更相似。显然这样不对(比如,分类 0 和 4 比 0 和 1 更相似)。要解决这个问题,一个常见的方法是给每个分类创建一个二元属性:当分类是<1H OCEAN,该属性为 1(否则为 0),当分类是INLAND,另一个属性等于 1(否则为 0),以此类推。这称作独热编码(One-Hot Encoding),因为只有一个属性会等于 1(热),其余会是 0(冷)。
Scikit-Learn 提供了一个编码器OneHotEncoder,用于将整数分类值转变为独热向量。注意fit_transform()用于 2D 数组,而housing_cat_encoded是一个 1D 数组,所以需要将其变形:
>>> from sklearn.preprocessing import OneHotEncoder>>> encoder = OneHotEncoder()>>> housing_cat_1hot = encoder.fit_transform(housing_cat_encoded.reshape(-1,1))>>> housing_cat_1hot<16513x5 sparse matrix of type '<class 'numpy.float64'>'with 16513 stored elements in Compressed Sparse Row format>
注意输出结果是一个 SciPy 稀疏矩阵,而不是 NumPy 数组。当类别属性有数千个分类时,这样非常有用。经过独热编码,我们得到了一个有数千列的矩阵,这个矩阵每行只有一个 1,其余都是 0。使用大量内存来存储这些 0 非常浪费,所以稀疏矩阵只存储非零元素的位置。你可以像一个 2D 数据那样进行使用,但是如果你真的想将其转变成一个(密集的)NumPy 数组,只需调用toarray()方法:
>>> housing_cat_1hot.toarray()array([[ 0., 1., 0., 0., 0.],[ 0., 1., 0., 0., 0.],[ 0., 0., 0., 0., 1.],...,[ 0., 1., 0., 0., 0.],[ 1., 0., 0., 0., 0.],[ 0., 0., 0., 1., 0.]])
使用类LabelBinarizer,我们可以用一步执行这两个转换(从文本分类到整数分类,再从整数分类到独热向量):
>>> from sklearn.preprocessing import LabelBinarizer>>> encoder = LabelBinarizer()>>> housing_cat_1hot = encoder.fit_transform(housing_cat)>>> housing_cat_1hotarray([[0, 1, 0, 0, 0],[0, 1, 0, 0, 0],[0, 0, 0, 0, 1],...,[0, 1, 0, 0, 0],[1, 0, 0, 0, 0],[0, 0, 0, 1, 0]])
注意默认返回的结果是一个密集 NumPy 数组。向构造器LabelBinarizer传递sparse_output=True,就可以得到一个稀疏矩阵。
译注:
在原书中使用
LabelBinarizer的方式也是错误的,该类也应用于标签列的转换。正确做法是使用sklearn即将提供的CategoricalEncoder类。如果在你阅读此文时sklearn中尚未提供此类,用如下方式代替:(来自Pull Request # 9151)
# Definition of the CategoricalEncoder class, copied from PR # 9151.# Just run this cell, or copy it to your code, do not try to understand it (yet).from sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.utils import check_arrayfrom sklearn.preprocessing import LabelEncoderfrom scipy import sparseclass CategoricalEncoder(BaseEstimator, TransformerMixin):"""Encode categorical features as a numeric array.The input to this transformer should be a matrix of integers or strings,denoting the values taken on by categorical (discrete) features.The features can be encoded using a one-hot aka one-of-K scheme(``encoding='onehot'``, the default) or converted to ordinal integers(``encoding='ordinal'``).This encoding is needed for feeding categorical data to many scikit-learnestimators, notably linear models and SVMs with the standard kernels.Read more in the :ref:`User Guide <preprocessing_categorical_features>`.Parameters----------encoding : str, 'onehot', 'onehot-dense' or 'ordinal'The type of encoding to use (default is 'onehot'):- 'onehot': encode the features using a one-hot aka one-of-K scheme(or also called 'dummy' encoding). This creates a binary column foreach category and returns a sparse matrix.- 'onehot-dense': the same as 'onehot' but returns a dense arrayinstead of a sparse matrix.- 'ordinal': encode the features as ordinal integers. This results ina single column of integers (0 to n_categories - 1) per feature.categories : 'auto' or a list of lists/arrays of values.Categories (unique values) per feature:- 'auto' : Determine categories automatically from the training data.- list : ``categories[i]`` holds the categories expected in the ithcolumn. The passed categories are sorted before encoding the data(used categories can be found in the ``categories_`` attribute).dtype : number type, default np.float64Desired dtype of output.handle_unknown : 'error' (default) or 'ignore'Whether to raise an error or ignore if a unknown categorical feature ispresent during transform (default is to raise). When this is parameteris set to 'ignore' and an unknown category is encountered duringtransform, the resulting one-hot encoded columns for this featurewill be all zeros.Ignoring unknown categories is not supported for``encoding='ordinal'``.Attributes----------categories_ : list of arraysThe categories of each feature determined during fitting. Whencategories were specified manually, this holds the sorted categories(in order corresponding with output of `transform`).Examples--------Given a dataset with three features and two samples, we let the encoderfind the maximum value per feature and transform the data to a binaryone-hot encoding.>>> from sklearn.preprocessing import CategoricalEncoder>>> enc = CategoricalEncoder(handle_unknown='ignore')>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])... # doctest: +ELLIPSISCategoricalEncoder(categories='auto', dtype=<... 'numpy.float64'>,encoding='onehot', handle_unknown='ignore')>>> enc.transform([[0, 1, 1], [1, 0, 4]]).toarray()array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.],[ 0., 1., 1., 0., 0., 0., 0., 0., 0.]])See also--------sklearn.preprocessing.OneHotEncoder : performs a one-hot encoding ofinteger ordinal features. The ``OneHotEncoder assumes`` that inputfeatures take on values in the range ``[0, max(feature)]`` instead ofusing the unique values.sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding ofdictionary items (also handles string-valued features).sklearn.feature_extraction.FeatureHasher : performs an approximate one-hotencoding of dictionary items or strings."""def __init__(self, encoding='onehot', categories='auto', dtype=np.float64,handle_unknown='error'):self.encoding = encodingself.categories = categoriesself.dtype = dtypeself.handle_unknown = handle_unknowndef fit(self, X, y=None):"""Fit the CategoricalEncoder to X.Parameters----------X : array-like, shape [n_samples, n_feature]The data to determine the categories of each feature.Returns-------self"""if self.encoding not in ['onehot', 'onehot-dense', 'ordinal']:template = ("encoding should be either 'onehot', 'onehot-dense' ""or 'ordinal', got %s")raise ValueError(template % self.handle_unknown)if self.handle_unknown not in ['error', 'ignore']:template = ("handle_unknown should be either 'error' or ""'ignore', got %s")raise ValueError(template % self.handle_unknown)if self.encoding == 'ordinal' and self.handle_unknown == 'ignore':raise ValueError("handle_unknown='ignore' is not supported for"" encoding='ordinal'")X = check_array(X, dtype=np.object, accept_sparse='csc', copy=True)n_samples, n_features = X.shapeself._label_encoders_ = [LabelEncoder() for _ in range(n_features)]for i in range(n_features):le = self._label_encoders_[i]Xi = X[:, i]if self.categories == 'auto':le.fit(Xi)else:valid_mask = np.in1d(Xi, self.categories[i])if not np.all(valid_mask):if self.handle_unknown == 'error':diff = np.unique(Xi[~valid_mask])msg = ("Found unknown categories {0} in column {1}"" during fit".format(diff, i))raise ValueError(msg)le.classes_ = np.array(np.sort(self.categories[i]))self.categories_ = [le.classes_ for le in self._label_encoders_]return selfdef transform(self, X):"""Transform X using one-hot encoding.Parameters----------X : array-like, shape [n_samples, n_features]The data to encode.Returns-------X_out : sparse matrix or a 2-d arrayTransformed input."""X = check_array(X, accept_sparse='csc', dtype=np.object, copy=True)n_samples, n_features = X.shapeX_int = np.zeros_like(X, dtype=np.int)X_mask = np.ones_like(X, dtype=np.bool)for i in range(n_features):valid_mask = np.in1d(X[:, i], self.categories_[i])if not np.all(valid_mask):if self.handle_unknown == 'error':diff = np.unique(X[~valid_mask, i])msg = ("Found unknown categories {0} in column {1}"" during transform".format(diff, i))raise ValueError(msg)else:# Set the problematic rows to an acceptable value and# continue `The rows are marked `X_mask` and will be# removed later.X_mask[:, i] = valid_maskX[:, i][~valid_mask] = self.categories_[i][0]X_int[:, i] = self._label_encoders_[i].transform(X[:, i])if self.encoding == 'ordinal':return X_int.astype(self.dtype, copy=False)mask = X_mask.ravel()n_values = [cats.shape[0] for cats in self.categories_]n_values = np.array([0] + n_values)indices = np.cumsum(n_values)column_indices = (X_int + indices[:-1]).ravel()[mask]row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),n_features)[mask]data = np.ones(n_samples * n_features)[mask]out = sparse.csc_matrix((data, (row_indices, column_indices)),shape=(n_samples, indices[-1]),dtype=self.dtype).tocsr()if self.encoding == 'onehot-dense':return out.toarray()else:return out转换方法:
# from sklearn.preprocessing import CategoricalEncoder # in future versions of Scikit-Learncat_encoder = CategoricalEncoder()housing_cat_reshaped = housing_cat.values.reshape(-1, 1)housing_cat_1hot = cat_encoder.fit_transform(housing_cat_reshaped)housing_cat_1hot
自定义转换器
尽管 Scikit-Learn 提供了许多有用的转换器,你还是需要自己动手写转换器执行任务,比如自定义的清理操作,或属性组合。你需要让自制的转换器与 Scikit-Learn 组件(比如流水线)无缝衔接工作,因为 Scikit-Learn 是依赖鸭子类型的(而不是继承),你所需要做的是创建一个类并执行三个方法:fit()(返回self),transform(),和fit_transform()。通过添加TransformerMixin作为基类,可以很容易地得到最后一个。另外,如果你添加BaseEstimator作为基类(且构造器中避免使用*args和**kargs),你就能得到两个额外的方法(get_params()和set_params()),二者可以方便地进行超参数自动微调。例如,一个小转换器类添加了上面讨论的属性:
from sklearn.base import BaseEstimator, TransformerMixinrooms_ix, bedrooms_ix, population_ix, household_ix = 3, 4, 5, 6class CombinedAttributesAdder(BaseEstimator, TransformerMixin):def __init__(self, add_bedrooms_per_room = True): # no *args or **kargsself.add_bedrooms_per_room = add_bedrooms_per_roomdef fit(self, X, y=None):return self # nothing else to dodef 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)
在这个例子中,转换器有一个超参数add_bedrooms_per_room,默认设为True(提供一个合理的默认值很有帮助)。这个超参数可以让你方便地发现添加了这个属性是否对机器学习算法有帮助。更一般地,你可以为每个不能完全确保的数据准备步骤添加一个超参数。数据准备步骤越自动化,可以自动化的操作组合就越多,越容易发现更好用的组合(并能节省大量时间)。
特征缩放
数据要做的最重要的转换之一是特征缩放。除了个别情况,当输入的数值属性量度不同时,机器学习算法的性能都不会好。这个规律也适用于房产数据:总房间数分布范围是 6 到 39320,而收入中位数只分布在 0 到 15。注意通常情况下我们不需要对目标值进行缩放。
有两种常见的方法可以让所有的属性有相同的量度:线性函数归一化(Min-Max scaling)和标准化(standardization)。
线性函数归一化(许多人称其为归一化(normalization))很简单:值被转变、重新缩放,直到范围变成 0 到 1。我们通过减去最小值,然后再除以最大值与最小值的差值,来进行归一化。Scikit-Learn 提供了一个转换器MinMaxScaler来实现这个功能。它有一个超参数feature_range,可以让你改变范围,如果不希望范围是 0 到 1。
标准化就很不同:首先减去平均值(所以标准化值的平均值总是 0),然后除以方差,使得到的分布具有单位方差。与归一化不同,标准化不会限定值到某个特定的范围,这对某些算法可能构成问题(比如,神经网络常需要输入值得范围是 0 到 1)。但是,标准化受到异常值的影响很小。例如,假设一个街区的收入中位数由于某种错误变成了100,归一化会将其它范围是 0 到 15 的值变为 0-0.15,但是标准化不会受什么影响。Scikit-Learn 提供了一个转换器StandardScaler来进行标准化。
警告:与所有的转换一样,缩放器只能向训练集拟合,而不是向完整的数据集(包括测试集)。只有这样,你才能用缩放器转换训练集和测试集(和新数据)。
转换流水线
你已经看到,存在许多数据转换步骤,需要按一定的顺序执行。幸运的是,Scikit-Learn 提供了类Pipeline,来进行这一系列的转换。下面是一个数值属性的小流水线:
from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalernum_pipeline = Pipeline([('imputer', Imputer(strategy="median")),('attribs_adder', CombinedAttributesAdder()),('std_scaler', StandardScaler()),])housing_num_tr = num_pipeline.fit_transform(housing_num)
Pipeline构造器需要一个定义步骤顺序的名字/估计器对的列表。除了最后一个估计器,其余都要是转换器(即,它们都要有fit_transform()方法)。名字可以随意起。
当你调用流水线的fit()方法,就会对所有转换器顺序调用fit_transform()方法,将每次调用的输出作为参数传递给下一个调用,一直到最后一个估计器,它只执行fit()方法。
流水线暴露相同的方法作为最终的估计器。在这个例子中,最后的估计器是一个StandardScaler,它是一个转换器,因此这个流水线有一个transform()方法,可以顺序对数据做所有转换(它还有一个fit_transform方法可以使用,就不必先调用fit()再进行transform())。
你现在就有了一个对数值的流水线,你还需要对分类值应用LabelBinarizer:如何将这些转换写成一个流水线呢?Scikit-Learn 提供了一个类FeatureUnion实现这个功能。你给它一列转换器(可以是所有的转换器),当调用它的transform()方法,每个转换器的transform()会被并行执行,等待输出,然后将输出合并起来,并返回结果(当然,调用它的fit()方法就会调用每个转换器的fit())。一个完整的处理数值和类别属性的流水线如下所示:
from sklearn.pipeline import FeatureUnionnum_attribs = list(housing_num)cat_attribs = ["ocean_proximity"]num_pipeline = Pipeline([('selector', DataFrameSelector(num_attribs)),('imputer', Imputer(strategy="median")),('attribs_adder', CombinedAttributesAdder()),('std_scaler', StandardScaler()),])cat_pipeline = Pipeline([('selector', DataFrameSelector(cat_attribs)),('label_binarizer', LabelBinarizer()),])full_pipeline = FeatureUnion(transformer_list=[("num_pipeline", num_pipeline),("cat_pipeline", cat_pipeline),])
译注:
如果你在上面代码中的
cat_pipeline流水线使用LabelBinarizer转换器会导致执行错误,解决方案是用上文提到的CategoricalEncoder转换器来代替:
cat_pipeline = Pipeline([('selector', DataFrameSelector(cat_attribs)),('cat_encoder', CategoricalEncoder(encoding="onehot-dense")),])
你可以很简单地运行整个流水线:
>>> housing_prepared = full_pipeline.fit_transform(housing)>>> housing_preparedarray([[ 0.73225807, -0.67331551, 0.58426443, ..., 0. ,0. , 0. ],[-0.99102923, 1.63234656, -0.92655887, ..., 0. ,0. , 0. ],[...]>>> housing_prepared.shape(16513, 17)
每个子流水线都以一个选择转换器开始:通过选择对应的属性(数值或分类)、丢弃其它的,来转换数据,并将输出DataFrame转变成一个 NumPy 数组。Scikit-Learn 没有工具来处理 PandasDataFrame,因此我们需要写一个简单的自定义转换器来做这项工作:
from sklearn.base import BaseEstimator, TransformerMixinclass DataFrameSelector(BaseEstimator, TransformerMixin):def __init__(self, attribute_names):self.attribute_names = attribute_namesdef fit(self, X, y=None):return selfdef transform(self, X):return X[self.attribute_names].values
