Advertisement

Best Practices to Clean and Prepare Data Before Feeding

阅读量:

作者:禅与计算机程序设计艺术

1.简介

The data forms the foundation of modern machine learning systems. Consequently, ensuring high-quality data is crucial for developing reliable models capable of excelling in real-world applications. In this piece, we delve into eight expert strategies for ensuring data integrity and readiness for machine learning applications.

Clean and Organize Data

  • 去除重复的行或列
  • 处理缺失值
  • 归一化或标准化特征
  • 编码分类变量

Split Data into Train and Test Sets

  • 根据目标变量进行分层划分
    • 采用基于时间的验证方法论

Handle Imbalanced Classes with Resampling Techniques

  • Synthetical Minority-class oversampling method (SMOTE)
  • Under-sampling methods such as Random Under-Sampling or Cluster centroid-based

Use Feature Engineering to Create New Features

  • Methods such as logarithmic transformation, square root transformation, cube root transformation and so on.
  • The interactions between features can be incorporated using polynomial features and also interaction features.
  • Information can be extracted from textual data through the Bag of Words model and also through TF-IDF vectorization techniques.

Determine the target variable type as continuous data, select an appropriate binning method, and then apply this method to discretize the continuous variables into discrete ones using binning techniques.

  • 等宽区间划分法
  • 基于K均值聚类的区间划分法
  • 根据局部分布自适应调整的区间划分法

Examine heteroscedasticity through analyzing Variance Inflation Factor (VIF) values. VIF is measured as the degree of multicollinearity between variables. It is advisable to check whether any variable exceeds a VIF threshold of 5, which indicates multicollinearity among them, potentially leading to issues in regression analysis. If multiple variables have high VIF values, it may require removing redundant features or applying regularization techniques to prevent overfitting.

The entire process of preparing data for machine learning involves cleaning, organizing, transforming, resampling, feature engineering, binning, splitting data into train and test sets, and handling heteroscedasticity. We have discussed each step in detail below along with code examples. You’ll gain an understanding of how to ensure your data is ready for training machine learning models and improve their accuracy while reducing errors and improving efficiency.

2.背景介绍

近年来,机器学习因其能够处理海量数据而日益受到重视。尽管如此,在输入这些系统之前,数据质量的低劣可能导致结果出现偏差。优质的数据准备能够通过数据收集、数据清洗以及数据准备等三个关键步骤显著提升机器学习模型的表现力。本文探讨了用于清洁和准备数据的各种方法和技术。

3.数据清洗与准备

数据移除重复项

一个数据集常见地包含多个样本或数据记录。当遇到重复的数据时,则应予以去除处理。这种现象通常是不可接受的,并会干扰模型预测能力;因此,在实际应用中应当尽可能地剔除这些异常值。

借助 pandas 的 drop_duplicates() 函数可以有效地去除数据中的重复项或重复列。该函数默认保留首次出现的数据项,并将后续数据项设置为NaN值。以下是一个具体的实现示例:

复制代码
    import pandas as pd
    
    df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'c'],
                   'C': [1., 2., np.nan], 'D': [True, False, True]})
    
    print(df)
    
    """
       A  B     C   D
    0  1  a  1.0  1
    1  2  b  2.0  0
    2  3  c  NaN  1
    
    Note: There are two rows with identical values except for index and boolean flag.
    """
    
    new_df = df.drop_duplicates() # Drop duplicate rows
    print("New DataFrame after removing duplicates:\n", new_df)
    
    """
       A  B    C   D
    0  1  a  1.0  1
    1  2  b  2.0  0
    2  3  c  NaN  1
    """
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    代码解读

通过有效手段对数据进行重新组织与整理格式后能够使后续的数据处理变得更加简便直观且高效。对于具备相似格式的数据类型我们可以通过将其整合到同一个表格中来优化数据的可读性并提升工作效率。

缺失值处理

由于大部分机器学习模型在面对缺失数据时会遇到处理上的困难,在实际应用中为了确保数据的完整性与一致性性状的一致性, 必须首先对缺失值的数量以及它们的位置进行必要的调查研究. 缺失值主要可分为两类: 真实存在的无效数据(例如一个空字符串、空值或不存在的数值)以及被暂时标记为缺失的数据.

无效数据:指的是无法提供有效信息的数据。一般情况下,无效数据被视为错误的样本点,并从训练集中排除。

"暂缺"数据即指因特定原因导致的数据缺失情况。如在收集数据的过程中,某些变量的取值可能因多种因素难以获取,而另一些变量则可顺利取得数值。在此情形下,"暂缺"的数据需采用特定符号标识,以便依据具体需求补充完整。

关于缺失值处理的方法主要有以下几种:

删除包含缺失值的行或列:这种方法是最直接且最容易实施的方式。当遇到任何数据点包含缺失值时,则需立即删除。这种做法可能导致整体数据量的缩减,并且在面对大量样本同时出现较多缺失值的情况下,不推荐使用这种方法。

  1. 一种常用的方法是使用样本的均值或众数来替代缺失数据。这种方法虽然简便易行。
    除了删除数据点之外,
    另一种方法是将缺失的数据用样本的均值或众数进行填补。
    这种做法可能会导致模型出现过拟合问题。

  2. 用全局均值/众数补全缺失值:在各个特征维度上计算全局均值和众数通常能有效反映数据的整体特性。那么是否能在各个特征维度中分别计算出其全局均值与众数,并将这些统计量作为对应特征缺失值的替代方案呢?这种方法不仅有助于消除不同维度之间可能存在的相关性,并且还能对缺失值分布进行建模。然而,在实际应用中这种方法仍然依赖于数据的具体情况,在数据分布存在较大差异时可能会降低模型预测的效果

用整合自身特征求取均值或众数的方式补全缺失数据:另一种常用的技术是利用样本自身的均质信息来进行填补操作。具体而言,在求取某个变量的具体数值时,在计算前需对该变量的所有可能取样点进行标准化处理以消除潜在偏差,在此基础上再求取其算术平均或多数投票的结果作为填补依据。值得注意的是,在实际应用中这一方法能够有效降低极端异常点所带来的影响效果。然而需要注意的是,在实际应用中这一方法仍存在局限性——不同属性间可能存在高度相关关系,在新数据中难以准确推广

数据归一化/标准化

数据规范化处理和标准处理方法是两种常用的技术手段,在消除量纲差异方面具有显著作用。规范化处理的目标是将数据转换至[0, 1]或[-1, 1]区间内实施操作,而标准处理方法则旨在使数据分布符合均值为零、方差为一的标准形态。

数据标准化

数据标准化又被称作Z-Score标准化,则是一种通过方法将原始数据转换成均值为0、标准差为1的技术手段。该过程通常会导致转换后的数据服从标准正态分布规律,并且其取值范围被限制在-3至+3之间;这种方法因其简便高效而被广泛采用

复制代码
    def standardize(data):
    mean = np.mean(data)
    std = np.std(data)
    return (data - mean)/std
    
      
      
      
    
    代码解读

数据归一化

归一化处理又称为Min-Max标准化,在机器学习领域中被广泛采用。该方法通过线性变换将原始数据转换为[0, 1]或[-1, 1]区间内的值,在实际应用中具有较高的实用性。其具体操作过程如下:对于任意一个特征值x_i,在原始数据集中的最小值min(x)和最大值max(x)的基础上进行标准化处理。

其中原始数据为X,则其归一化后结果表示为X';而min(x)和max(x)分别为该组数据的最小值与最大值。在Python编程中,则可以通过导入sklearn库并使用其中的MinMaxScaler或MaxAbsScaler类来完成这一归一化处理的方法。

复制代码
    from sklearn.preprocessing import MinMaxScaler
    
    scaler = MinMaxScaler()
    norm_data = scaler.fit_transform(raw_data)
    
      
      
      
    
    代码解读

数据预处理的总结

数据预处理过程包含三大核心环节:首先是对数据进行去重操作;其次是对缺失值进行处理;最后是对数据进行归一化处理。在机器学习模型的数据准备阶段中,“清洗与准备”是十分关键的一个环节,“清洗与准备”是指对原始数据进行系统性优化的过程。“清洗与准备”这一工作有助于提高机器学习模型的预测能力和性能。我们来看几个具体的代码实现案例吧。

一元线性回归的示例代码

我们假设有这样一个一元线性回归的问题:设x为自变量、y为因变量。从某些数据源中获取了一个由x与y组成的矩阵(如公式所示):\mathbf{X} = [\mathbf{x}_1, \mathbf{x}_2, ..., \mathbf{x}_n]^T \mathbf{Y} = [y_1, y_2, ..., y_n]^T

复制代码
    import numpy as np
    
    x = np.array([2, 4, 6, 8, 10]).reshape((-1, 1))
    y = np.array([3, 7, 9, 12, 15])
    
      
      
      
    
    代码解读

该数据集包含五个样本,并无缺失值。为建立机器学习模型需做预处理工作。首先需去除数据中的重复项:

复制代码
    unique_idx = np.unique(np.hstack((x, y)), axis=None)
    x = x[unique_idx].reshape(-1, 1)
    y = y[unique_idx]
    
      
      
    
    代码解读

接着,我们将数据标准化:

复制代码
    scaler = StandardScaler().fit(x)
    x_scaled = scaler.transform(x)
    
      
    
    代码解读

最后,我们将数据分割成训练集和测试集,并进行训练:

复制代码
    from sklearn.model_selection import train_test_split
    
    train_x, test_x, train_y, test_y = train_test_split(x_scaled, y, test_size=0.3, random_state=0)
    model = LinearRegression().fit(train_x, train_y)
    score = model.score(test_x, test_y)
    print('R^2 score:', score)
    
      
      
      
      
      
    
    代码解读

二元线性回归的示例代码

设自变量为 x_1x_2,则响应变量为 y。在此时的数据集中,呈现为 (x_1, x_2, y) 的具体形式如上所示。

复制代码
    import numpy as np
    
    x1 = np.array([1, 2, 3, 4, 5])
    x2 = np.array([2, 4, 6, 8, 10])
    y = np.array([5, 11, 13, 17, 23])
    
      
      
      
      
    
    代码解读

为了构建模型,我们对数据进行预处理,首先,我们删除重复项:

复制代码
    unique_idx = np.unique(np.hstack((x1, x2, y)), axis=None)
    x1 = x1[unique_idx]
    x2 = x2[unique_idx]
    y = y[unique_idx]
    
      
      
      
    
    代码解读

然后,我们对数据进行归一化:

复制代码
    scaler = MinMaxScaler().fit(np.vstack((x1, x2)).T)
    x1_scaled = scaler.transform(x1[:, np.newaxis])
    x2_scaled = scaler.transform(x2[:, np.newaxis])
    
      
      
    
    代码解读

最后,我们将数据分割成训练集和测试集,并进行训练:

复制代码
    from sklearn.model_selection import train_test_split
    
    train_x1, test_x1, train_x2, test_x2, train_y, test_y = \
            train_test_split(x1_scaled, x2_scaled, y, test_size=0.3, random_state=0)
    model = LinearRegression().fit(np.hstack((train_x1, train_x2)), train_y)
    score = model.score(np.hstack((test_x1, test_x2)), test_y)
    print('R^2 score:', score)
    
      
      
      
      
      
      
    
    代码解读

多元线性回归的示例代码

我们假设存在一个三维自变量向量 X = (x1, x2, x3),其中 y 为因变量。此时数据集的结构转换为包含四个元素的有序组(x1, x2, x3, y)。

复制代码
    import numpy as np
    
    x1 = np.array([1, 2, 3, 4, 5])
    x2 = np.array([2, 4, 6, 8, 10])
    x3 = np.array([1, 2, 3, 4, 5])
    y = np.array([5, 11, 13, 17, 23])
    
      
      
      
      
      
    
    代码解读

为了构建模型,我们对数据进行预处理,首先,我们删除重复项:

复制代码
    unique_idx = np.unique(np.hstack((x1, x2, x3, y)), axis=None)
    x1 = x1[unique_idx]
    x2 = x2[unique_idx]
    x3 = x3[unique_idx]
    y = y[unique_idx]
    
      
      
      
      
    
    代码解读

然后,我们对数据进行归一化:

复制代码
    scaler = MinMaxScaler().fit(np.vstack((x1, x2, x3)).T)
    x1_scaled = scaler.transform(x1[:, np.newaxis])
    x2_scaled = scaler.transform(x2[:, np.newaxis])
    x3_scaled = scaler.transform(x3[:, np.newaxis])
    
      
      
      
    
    代码解读

最后,我们将数据分割成训练集和测试集,并进行训练:

复制代码
    from sklearn.model_selection import train_test_split
    
    train_x1, test_x1, train_x2, test_x2, train_x3, test_x3, train_y, test_y = \
            train_test_split(x1_scaled, x2_scaled, x3_scaled, y, test_size=0.3, random_state=0)
    model = LinearRegression().fit(np.hstack((train_x1, train_x2, train_x3)), train_y)
    score = model.score(np.hstack((test_x1, test_x2, test_x3)), test_y)
    print('R^2 score:', score)
    
      
      
      
      
      
      
    
    代码解读

分类问题的示例代码

考虑一个二元分类任务,在此场景下, 我们设定x作为自变量输入数据集, 并将y定义为其对应的因变量输出结果。特别地, y仅取两个离散值(如0和1)。通过收集和整理数据, 我们构建了一个包含x和y的数据矩阵:

复制代码
    import numpy as np
    
    x = np.random.randn(100, 4)
    y = np.where(np.sum(x ** 2, axis=1) > 1, 1, 0)
    
      
      
      
    
    代码解读

该数据集包含 100 个样本无缺失值。在模型构建前,我们对所有样本进行去重操作:首先剔除重复项

复制代码
    unique_idx = np.unique(np.hstack((x, y.astype(int))), axis=None).astype(int)
    x = x[unique_idx]
    y = y[unique_idx]
    
      
      
    
    代码解读

接着,我们将数据标准化:

复制代码
    scaler = StandardScaler().fit(x)
    x_scaled = scaler.transform(x)
    
      
    
    代码解读

最后,我们将数据分割成训练集和测试集,并进行训练:

复制代码
    from sklearn.model_selection import train_test_split
    
    train_x, test_x, train_y, test_y = train_test_split(x_scaled, y, test_size=0.3, random_state=0)
    model = LogisticRegression().fit(train_x, train_y)
    score = model.score(test_x, test_y)
    print('Accuracy score:', score)
    
      
      
      
      
      
    
    代码解读

全部评论 (0)

还没有任何评论哟~