EDA(Exploratory Data Analysis)探索性数据分析

EDA(Exploratory Data Analysis)中文名称为探索性数据分析,是为了在特征工程或模型开发之前对数据有个基本的了解。数据类型通常分为两类:连续类型和离散类型,特征类型不同,我们探索的内容也不同。

1. 特征类型

1.1 连续型特征

定义:取值为数值类型且数值之间的大小具有实际含义。例如:收入。对于连续型变量,需要进行EDA的内容包括:

  • 缺失值
  • 均值
  • 方差
  • 标准差
  • 最大值
  • 最小值
  • 中位数
  • 众数
  • 四分位数
  • 偏度
  • 最大取值类别对应的样本数

1.2 离散型特征

定义:不具有数学意义的特征。如:性别。对于离散型变量,需要进行EDA的内容包括:

  • 缺失值
  • 众数
  • 取值个数
  • 最大取值类别对应的样本数
  • 每个取值对应的样本数

2. EDA目的

​ 通过EDA,需要达到以下几个目的:

​ (1)可以有效发现变量类型、分布趋势、缺失值、异常值等。

​ (2)缺失值处理:(i)删除缺失值较多的列,通常缺失超过50%的列需要删除;(ii)缺失值填充。对于离散特征,通常将NAN单独作为一个类别;对于连续特征,通常使用均值、中值、0或机器学习算法进行填充。具体填充方法因业务的不同而不同。

​ (3)异常值处理(主要针对连续特征)。如:Winsorizer方法处理。

​ (4)类别合并(主要针对离散特征)。如果某个取值对应的样本个数太少,就需要将该取值与其他值合并。因为样本过少会使数据的稳定性变差,且不具有统计意义,可能导致结论错误。由于展示空间有限,通常选择取值个数最少或最多的多个取值进行展示。

​ (5)删除取值单一的列。

​ (6)删除最大类别取值数量占比超过阈值的列。

3.实验

3.1 统计变量类型、分布趋势、缺失值、异常值等

#!/usr/bin/pythonimport pandas as pd
import numpy as npdef getTopValues(series, top = 5, reverse = False):"""Get top/bottom n valuesArgs:series (Series): data seriestop (number): number of top/bottom n valuesreverse (bool): it will return bottom n values if True is givenReturns:Series: Series of top/bottom n values and percentage. ['value:percent', None]"""itype = 'top'counts = series.value_counts()counts = list(zip(counts.index, counts, counts.divide(series.size)))if reverse:counts.reverse()itype = 'bottom'template = "{0[0]}:{0[2]:.2%}"indexs = [itype + str(i + 1) for i in range(top)]values = [template.format(counts[i]) if i < len(counts) else None for i in range(top)]return pd.Series(values, index = indexs)def getDescribe(series, percentiles = [.25, .5, .75]):"""Get describe of seriesArgs:series (Series): data seriespercentiles: the percentiles to include in the outputReturns:Series: the describe of data include mean, std, min, max and percentiles"""d = series.describe(percentiles)return d.drop('count')def countBlank(series, blanks = []):"""Count number and percentage of blank values in seriesArgs:series (Series): data seriesblanks (list): list of blank valuesReturns:number: number of blanksstr: the percentage of blank values"""if len(blanks)>0:isnull = series.replace(blanks, None).isnull()else:isnull = series.isnull()n = isnull.sum()ratio = isnull.mean()return (n, "{0:.2%}".format(ratio))def isNumeric(series):"""Check if the series's type is numericArgs:series (Series): data seriesReturns:bool"""return series.dtype.kind in 'ifc'def detect(dataframe):""" Detect dataArgs:dataframe (DataFrame): data that will be detectedReturns:DataFrame: report of detecting"""numeric_rows = []category_rows = []for name, series in dataframe.items():# 缺失值比例nblank, pblank = countBlank(series)# 最大类别取值占比biggest_category_percentage = series.value_counts(normalize=True, dropna=False).values[0] * 100if isNumeric(series):desc = getDescribe(series,percentiles=[.01, .1, .5, .75, .9, .99])details = desc.tolist()details_index = ['mean', 'std', 'min', '1%', '10%', '50%', '75%', '90%', '99%', 'max']row = pd.Series(index=['type', 'size', 'missing', 'unique', 'biggest_category_percentage', 'skew'] + details_index,data=[series.dtype, series.size, pblank, series.nunique(), biggest_category_percentage, series.skew()] + details)row.name = namenumeric_rows.append(row)else:top5 = getTopValues(series)bottom5 = getTopValues(series, reverse=True)details = top5.tolist() + bottom5[::-1].tolist()details_index = ['top1', 'top2', 'top3', 'top4', 'top5', 'bottom5', 'bottom4', 'bottom3', 'bottom2', 'bottom1']row = pd.Series(index=['type', 'size', 'missing', 'unique', 'biggest_category_percentage'] + details_index,data=[series.dtype, series.size, pblank, series.nunique(), biggest_category_percentage] + details)row.name = namecategory_rows.append(row)return pd.DataFrame(numeric_rows), pd.DataFrame(category_rows)

demo(数据来自:https://www.kaggle.com/competitions/home-credit-default-risk/data)

import os
import eda
import pandas as pd
import numpy as npdata_dir = "./"df = pd.read_csv(os.path.join(data_dir, "bureau.csv"))
numeric_df, category_df = eda.detect(df)

在这里插入图片描述
在这里插入图片描述

3.2 缺失值处理(示例)

#连续特征
df[col].fillna(-df[col].mean(), inplace=True)
#离散特征
df[col].fillna('nan', inplace=True)

3.3 删除无用特征

def get_del_columns(df):del_columns = {}for index, row in df.iterrows():if row["unique"] < 2:del_columns[row["Feature"]] = "取值单一"continueif row["missing"] > 90:del_columns[row["Feature"]] = "缺失值数量大于90%"continueif row["biggest_category_percentage"] > 99:del_columns[row["Feature"]] = "取值最多的类别占比超过99%"continuedel_columns[row["Feature"]] = "正常"return del_columns

3.4 异常值处理

Winsorizer算法(定义某个变量的上界和下界,取值超过边界的话会用边界的值取代):
在这里插入图片描述

class Winsorizer():"""Performs Winsorization 1->1*Warning: this class should not be used directly."""    def __init__(self,trim_quantile=0.0):self.trim_quantile=trim_quantileself.winsor_lims=Nonedef train(self,X):# get winsor limitsself.winsor_lims=np.ones([2,X.shape[1]])*np.infself.winsor_lims[0,:]=-np.infif self.trim_quantile>0:for i_col in np.arange(X.shape[1]):lower=np.percentile(X[:,i_col],self.trim_quantile*100)upper=np.percentile(X[:,i_col],100-self.trim_quantile*100)self.winsor_lims[:,i_col]=[lower,upper]def trim(self,X):X_=X.copy()X_=np.where(X>self.winsor_lims[1,:],np.tile(self.winsor_lims[1,:],[X.shape[0],1]),np.where(X<self.winsor_lims[0,:],np.tile(self.winsor_lims[0,:],[X.shape[0],1]),X))return X_
winsorizer = Winsorizer (0.1)
a=np.random.random((10,2))
print("转化前: ", a)
winsorizer.train(a)
print("上界和下界: ", winsorizer.winsor_lims)
b = winsorizer.trim(a)
print("转化后: ", b)

在这里插入图片描述

4.总结

这篇文章只总结了EDA的常用做法,实际应用过程中还需要根据具体业务来做调整。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/115363.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【zookeeper】zk选举、使用与三种节点简介,以及基于redis分布式锁的缺点的讨论

这里我准备了4台虚拟机&#xff0c;从node1到node4&#xff0c;其myid也从1到4. 一&#xff0c;zk server的启动和选举 zk需要至少启动3台Server&#xff0c;按照配置的myid&#xff0c;选举出参与选举的myid最大的server为Leader。&#xff08;与redis的master、slave不同&a…

uqrcode+uni-app 微信小程序生成二维码

使用微信小程序需要弹出动态二维码的需求&#xff0c;从插件市场选了一个下载次数较多的组件引入到项目中uqrcode&#xff0c;使用步骤如下&#xff1a; 1、从插件市场下载 插件地址&#xff1a;https://ext.dcloud.net.cn/plugin?id1287&#xff0c;若你是跟我一样是用uni-…

八大排序(四)--------直接插入排序

本专栏内容为&#xff1a;八大排序汇总 通过本专栏的深入学习&#xff0c;你可以了解并掌握八大排序以及相关的排序算法。 &#x1f493;博主csdn个人主页&#xff1a;小小unicorn ⏩专栏分类&#xff1a;八大排序汇总 &#x1f69a;代码仓库&#xff1a;小小unicorn的代码仓库…

蓝牙低功耗BLE调研与开发

蓝牙低功耗BLE调研与开发 一&#xff1a; 蓝牙简介 蓝牙是一种近距离无线通信技术&#xff0c;运行在2.4GHz免费频段&#xff0c;它的特性就是近距离通信&#xff0c;典型距离是 10 米以内&#xff0c;传输速度最高可达 24 Mbps&#xff0c;支持多连接&#xff0c;安全性高&a…

在编译源码的环境下,搭建起Discuz!社区论坛和WordPress博客的LNMP架构

目录 一.编译安装nginx 二.编译安装MySQL 三.编译安装PHP 四.安装论坛 五.安装wordpress博客 六.yum安装LNMP架构&#xff08;简要过程参考&#xff09; 一.编译安装nginx 1&#xff09;关闭防火墙&#xff0c;将安装nginx所需软件包传到/opt目录下 systemctl stop fire…

基础算法--前缀和与差分

1、前缀和 前缀和是指某序列的前n项和&#xff0c;可以把它理解为数学上的数列的前n项和&#xff0c;而差分可以看成前缀和的逆运算。合理的使用前缀和与差分&#xff0c;可以将某些复杂的问题简单化。 2、前缀和算法有什么好处&#xff1f; 先来了解这样一个问题&#xff1a;…

STM32 定时器介绍--基本定时器

目录 基本定时器 1.功能框图 1-时钟源 2-控制器 3-时基单元 4-影子寄存器 2.定时时间的计算 3.时基初始化结构体 4.实验设计 1-配置时基初始化结构体 2-开启定时器更新中断&#xff08;即定时时间到了&#xff09; 3-编写main函数 在我之前文章中说过一个系统定时器…

使用Visual Leak Detector排查内存泄漏问题

目录 1、VLD工具概述 2、下载、安装VLD 2.1、下载VLD 2.2、安装VLD 3、VLD安装目录及文件说明 3.1、安装目录及文件说明 3.2、关于32位和64位版本的详细说明 4、在工程中引入VLD 5、内存泄漏检测实例讲解 5.1、程序启动报错 5.2、启动调试&#xff0c;查看内存泄漏报…

推荐几款实用的项目进度管理软件

做好项目的进度管理是项目经理的重要职责&#xff0c;在这个过程中&#xff0c;并非单凭人力就可以把控。项目进度管理软件出现&#xff0c;成为人们在项目管理过程中最需要的工具之一。一个项目无论大小&#xff0c;都需要一款高效且实用的项目管理工具&#xff0c;对项目流程…

actf_2019_babystack

actf_2019_babystack Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x3ff000)64位&#xff0c;只开了nx __int64 __fastcall main(int a1, char **a2, char **a3) {char s[208]; // [rsp0h] [rbp-D…

华为云云耀云服务器L实例评测 |云服务器选购

华为云耀云服务器 L 实例是一款轻量级云服务器&#xff0c;开通选择实例即可立刻使用&#xff0c;不需要用户再对服务器进行基础配置。新用户还有专享优惠&#xff0c;2 核心 2G 内存 3M 带宽的服务器只要 89 元/年&#xff0c;可以点击华为云云耀云服务器 L 实例购买地址去购买…

leetcode25 K个一组反转链表

题目 给你链表的头节点 head &#xff0c;每 k 个节点一组进行翻转&#xff0c;请你返回修改后的链表。 k 是一个正整数&#xff0c;它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍&#xff0c;那么请将最后剩余的节点保持原有顺序。 你不能只是单纯的改变节点内部…