ML-数据分析模板

2023-11-14

机器学习-数据分析模板

Objective

我们的任务:预测一个人的收入能否超过五万美元
人口普查数据集: https://archive.ics.uci.edu/ml/datasets/adult

Data Set Information:

Extraction was done by Barry Becker from the 1994 Census database. A set of reasonably clean records was extracted using the following conditions: ((AAGE>16) && (AGI>100) && (AFNLWGT>1)&& (HRSWK>0))

Prediction task is to determine whether a person makes over 50K a year.

Attribute Information:

Listing of attributes:
50K, <=50K.
age: continuous.
workclass: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked.
fnlwgt: continuous.
education: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool.
education-num: continuous.
marital-status: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse.
occupation: Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces.
relationship: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried.
race: White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black.
sex: Female, Male.
capital-gain: continuous.
capital-loss: continuous.
hours-per-week: continuous.
native-country: United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands.

INPUT

# Load Training and Test Data Sets
headers = ['age', 'workclass', 'fnlwgt', 
           'education', 'education-num', 
           'marital-status', 'occupation', 
           'relationship', 'race', 'sex', 
           'capital-gain', 'capital-loss', 
           'hours-per-week', 'native-country', 
           'predclass']
training_raw = pd.read_csv('dataset/adult.data', 
                       header=None, 
                       names=headers, 
                       sep=',\s', 
                       na_values=["?"], 
                       engine='python')
test_raw = pd.read_csv('dataset/adult.test', 
                      header=None, 
                      names=headers, 
                      sep=',\s', 
                      na_values=["?"], 
                      engine='python', 
                      skiprows=1)

header默认是0,即取第零行数据为columns;header=None,即不从数据中取columns
names=headers,即为columns赋值

import pandas as pd
#可以打印说明文档
print (help(pd.read_csv))
# Join Datasets
dataset_raw = training_raw.append(test_raw)
dataset_raw.reset_index(inplace=True)
dataset_raw.drop('index',inplace=True,axis=1)
dataset_raw.head()

由于合并数据,导致index乱了,所以reset_index(inplace=True)
在这里插入图片描述

属性:
age 年龄 double
workclass 工作类型 string
fnlwgt 序号 string
education 教育程度 string
education_num 受教育时间 double
maritial_status 婚姻状况 string
occupation 职业 string
relationship 关系 string
race 种族 string
sex 性别 string
capital_gain 资本收益 string
capital_loss 资本损失 string
hours_per_week 每周工作小时数 double
native_country 原籍 string
income 收入 string

单特征与缺失值展示

关于特征,我们可以分析单特征,也可以分析不同特征之间的关系,首先来看单特征

特征简单分为两种:类别型和数值型

  • Numerical: 都是数
  • Categorical: 种类或者字符串
# 会展示所有数值型的特征
dataset_raw.describe()

在这里插入图片描述

# 展示所有种类型特征,注意是大写的o
dataset_raw.describe(include=['O'])

在这里插入图片描述

# 缺失值显示
missingno.matrix(dataset_raw, figsize = (30,5))

在这里插入图片描述

Feature Cleaning, Engineering

清洗: 数据预处理工作:

  • 缺失值: 对缺失值进行填充
  • 特殊值: 一些错误导致的特殊值,例如 ±Inf, NA NaN
  • 离群点: 这些点可能会对结果产生影响,先把它们找出来
  • 错误值: 比如人的年龄不可能出现负数

特征工程: There are multiple techniques for feature engineering:

  • 特征分解: 比如将时间数据2014-09-20T20:45:40Z 转换成天,小时等信息.
  • 离散化: 我们可以选择离散一些我们所拥有的连续变量,因为一些算法会执行得更快。但是会对结果产生什么样的影响呢?需要比较离散和非离散的建模结果
  • dataset_bin => 连续值被离散化的数据集
  • dataset_con => 非离散化的数据集
  • 特征组合: 将不同的特征组合成一个新特征

缺失值问题: 我们可以填补缺失值,在许多不同的方式::

  • 额外的数据补充: 有点难弄
  • 均值填充: 这样可以不改变当前数据集整体的均值
  • 回归模型预测: 建立一个回归模型去得到预测值

标签转换

如果收入大于 $50K. 那么就是1 反之就是0

# Let's fix the Class Feature
dataset_raw.loc[dataset_raw['predclass'] == '>50K', 'predclass'] = 1
dataset_raw.loc[dataset_raw['predclass'] == '>50K.', 'predclass'] = 1
dataset_raw.loc[dataset_raw['predclass'] == '<=50K', 'predclass'] = 0
dataset_raw.loc[dataset_raw['predclass'] == '<=50K.', 'predclass'] = 0

dataset_bin['predclass'] = dataset_raw['predclass']
dataset_con['predclass'] = dataset_raw['predclass']
#数据不太均衡的
plt.style.use('seaborn-whitegrid')
fig = plt.figure(figsize=(20,1)) 
sns.countplot(y="predclass", data=dataset_bin);

在这里插入图片描述

单变量

Feature: Age
dataset_bin['age'] = pd.cut(dataset_raw['age'], 10) # 将连续值进行切分
dataset_con['age'] = dataset_raw['age'] # non-discretised
#左图是切分后的结果 右图是根据不同的收入等级划分
plt.style.use('seaborn-whitegrid')
fig = plt.figure(figsize=(20,5)) 
plt.subplot(1, 2, 1)
sns.countplot(y="age", data=dataset_bin);
plt.subplot(1, 2, 2)
sns.distplot(dataset_con.loc[dataset_con['predclass'] == 1]['age'], kde_kws={"label": ">$50K"});
sns.distplot(dataset_con.loc[dataset_con['predclass'] == 0]['age'], kde_kws={"label": "<$50K"});

在这里插入图片描述

Feature: Workclas
# 工作的种类
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(20,3)) 
sns.countplot(y="workclass", data=dataset_raw);

在这里插入图片描述

# 种类有些太多了,有些类似的要进行合并
dataset_raw.loc[dataset_raw['workclass'] == 'Without-pay', 'workclass'] = 'Not Working'
dataset_raw.loc[dataset_raw['workclass'] == 'Never-worked', 'workclass'] = 'Not Working'
dataset_raw.loc[dataset_raw['workclass'] == 'Federal-gov', 'workclass'] = 'Fed-gov'
dataset_raw.loc[dataset_raw['workclass'] == 'State-gov', 'workclass'] = 'Non-fed-gov'
dataset_raw.loc[dataset_raw['workclass'] == 'Local-gov', 'workclass'] = 'Non-fed-gov'
dataset_raw.loc[dataset_raw['workclass'] == 'Self-emp-not-inc', 'workclass'] = 'Self-emp'
dataset_raw.loc[dataset_raw['workclass'] == 'Self-emp-inc', 'workclass'] = 'Self-emp'

dataset_bin['workclass'] = dataset_raw['workclass']
dataset_con['workclass'] = dataset_raw['workclass']
plt.style.use('seaborn-whitegrid')
fig = plt.figure(figsize=(20,2)) 
sns.countplot(y="workclass", data=dataset_bin);

在这里插入图片描述

Feature: Occupation职业
# 职业也是同样的问题,重复的太多了
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(20,5)) 
sns.countplot(y="occupation", data=dataset_raw);
# Create buckets for Occupation
dataset_raw.loc[dataset_raw['occupation'] == 'Adm-clerical', 'occupation'] = 'Admin'
dataset_raw.loc[dataset_raw['occupation'] == 'Armed-Forces', 'occupation'] = 'Military'
dataset_raw.loc[dataset_raw['occupation'] == 'Craft-repair', 'occupation'] = 'Manual Labour'
dataset_raw.loc[dataset_raw['occupation'] == 'Exec-managerial', 'occupation'] = 'Office Labour'
dataset_raw.loc[dataset_raw['occupation'] == 'Farming-fishing', 'occupation'] = 'Manual Labour'
dataset_raw.loc[dataset_raw['occupation'] == 'Handlers-cleaners', 'occupation'] = 'Manual Labour'
dataset_raw.loc[dataset_raw['occupation'] == 'Machine-op-inspct', 'occupation'] = 'Manual Labour'
dataset_raw.loc[dataset_raw['occupation'] == 'Other-service', 'occupation'] = 'Service'
dataset_raw.loc[dataset_raw['occupation'] == 'Priv-house-serv', 'occupation'] = 'Service'
dataset_raw.loc[dataset_raw['occupation'] == 'Prof-specialty', 'occupation'] = 'Professional'
dataset_raw.loc[dataset_raw['occupation'] == 'Protective-serv', 'occupation'] = 'Military'
dataset_raw.loc[dataset_raw['occupation'] == 'Sales', 'occupation'] = 'Office Labour'
dataset_raw.loc[dataset_raw['occupation'] == 'Tech-support', 'occupation'] = 'Office Labour'
dataset_raw.loc[dataset_raw['occupation'] == 'Transport-moving', 'occupation'] = 'Manual Labour'

dataset_bin['occupation'] = dataset_raw['occupation']
dataset_con['occupation'] = dataset_raw['occupation']
plt.style.use('seaborn-whitegrid')
fig = plt.figure(figsize=(20,3))
sns.countplot(y="occupation", data=dataset_bin);

在这里插入图片描述

Feature: Native Country
# 同样进行合并
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(20,10)) 
sns.countplot(y="native-country", data=dataset_raw);
Feature: Education
# 教育也进行合并
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(20,5)) 
sns.countplot(y="education", data=dataset_raw);
Feature: Marital Status
Feature: Final Weight
# 同样分成10份
dataset_bin['fnlwgt'] = pd.cut(dataset_raw['fnlwgt'], 10)
dataset_con['fnlwgt'] = dataset_raw['fnlwgt']
Feature: Capital Gain
#资本增益
dataset_bin['capital-gain'] = pd.cut(dataset_raw['capital-gain'], 5)
dataset_con['capital-gain'] = dataset_raw['capital-gain']

plt.style.use('seaborn-whitegrid')
fig = plt.figure(figsize=(20,3)) 
plt.subplot(1, 2, 1)
sns.countplot(y="capital-gain", data=dataset_bin);
plt.subplot(1, 2, 2)
sns.distplot(dataset_con['capital-gain']);

在这里插入图片描述

Feature: Capital Loss
# 资本损失
dataset_bin['capital-loss'] = pd.cut(dataset_raw['capital-loss'], 5)
dataset_con['capital-loss'] = dataset_raw['capital-loss']

plt.style.use('seaborn-whitegrid')
fig = plt.figure(figsize=(20,3)) 
plt.subplot(1, 2, 1)
sns.countplot(y="capital-loss", data=dataset_bin);
plt.subplot(1, 2, 2)
sns.distplot(dataset_con['capital-loss']);

在这里插入图片描述

Features: Race, Sex, Relationship
# 这些就直接用了
dataset_con['sex'] = dataset_bin['sex'] = dataset_raw['sex']
dataset_con['race'] = dataset_bin['race'] = dataset_raw['race']
dataset_con['relationship'] = dataset_bin['relationship'] = dataset_raw['relationship']`

双变量

接下来要看特征之间的关系了

特征编码 Feature Encoding

对特征进行编码,因为机器学习只认识数字
常见编码方式Additional Resources: http://pbpython.com/categorical-encoding.html

两种常见的编码方式:

  • one hot encoding
  • label encoding (如果有10种可能,就编码为0-9)

两种数据集:

  • dataset_bin => 连续值被离散化的数据集
  • dataset_con => 非离散化的数据集

One Hot Encodes

# One Hot Encodes 
one_hot_cols = dataset_bin.columns.tolist()
one_hot_cols.remove('predclass')
dataset_bin_enc = pd.get_dummies(dataset_bin, columns=one_hot_cols)

dataset_bin_enc.head()

pd.get_dummie就能得到one hot编码
在这里插入图片描述

Label Encode

# Label Encode 
dataset_con_test = dataset_con

dataset_con_test['workclass'] = dataset_con['workclass'].factorize()[0]
dataset_con_test['occupation'] = dataset_con['occupation'].factorize()[0]
dataset_con_test['native-country'] = dataset_con['native-country'].factorize()[0]

dataset_con_enc = dataset_con_test.apply(LabelEncoder().fit_transform)

dataset_con_enc.head()

在这里插入图片描述
如果注视掉中间三个语句dataset_con_test[‘workclass’] 、dataset_con_test[‘occupation’] 、dataset_con_test[‘native-country’] ,就会报错
TypeError: ("’<’ not supported between instances of ‘str’ and ‘float’", ‘occurred at index workclass’)
原因是这三个属性中有nan值,所以报错

# Label Encode 
dataset_con_test = dataset_con

# dataset_con_test['workclass'] = dataset_con['workclass'].factorize()[0]
# dataset_con_test['occupation'] = dataset_con['occupation'].factorize()[0]
# dataset_con_test['native-country'] = dataset_con['native-country'].factorize()[0]

dataset_con_enc = dataset_con_test.apply(LabelEncoder().fit_transform)

dataset_con_enc.head()

参考factorize()用法,该函数使作用于series ,factorize()[0]作用类似于label encode,会将nan转为-1(LabelEncoder不能处理空值),如下图
在这里插入图片描述
label encoding 例子
label encoding 例子

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ML-数据分析模板 的相关文章

  • 指针初始化与释放问题

    int p free p 操作释放p指向的空间 但是p的值随机 会产生释放未知区域的问题 释放的不是p的空间 而是p指向的空间 p nullptr free P p nullptr 释放后应让p为空 防止再次释放已经释放的空间
  • 测试过程中印象最深刻的bug

    我就想到在我刚入行不久的时候有一个BUG 当时我们做的是一个CRM客户管理系统 里边有个客户列表 当时按照测试用例去执行的时候 发现出现点击客户删除却无法删除 于是就提了一个单 但是开发后来发现删除客户没问题 又给我打回 后来我去查看服务器
  • “自顶向下,逐步求精”的方法

    1 什么叫做 自顶向下 逐步求精 目前软件开发方法使用最广泛的 当属结构化的方法和面向对象的方法 而其中 结构化程序设计支持 自顶向下 逐步求精 的程序设计方法 自顶向下 的具体内涵是将复杂 大的问题划分为小问题 找出问题的关键 重点所在
  • MYSQL数据库慢查询优化整理

    通常优化SQL的时候都需要查看慢查询日志 先找到查询慢的语句 再去进行优化 MYSQL开启慢查询日志 先查看是否开启了 登录MYSQL 输入以下模糊查询的语句show variables like query 可以看到红线中的三个属性 分别
  • xmind收费与免费的区别_你用什么来做笔记呢 现在聪明的人都开始用Xmind了

    以前读书的时候做笔记是个很麻烦的事情 如果从头写到尾倒还好 一旦发现中间缺漏了什么或者想加进去内容就会发现很可能 很大可能要重新写笔记 那个时候就想 要是能有个做笔记的软件 想加条内容或者减条内容很方便多好 而且不用先算计好要给下级文案留多
  • 【计算机网络】I/O多路转接之poll

    不同与select使用三个位图来表示三个fdset的方式 poll使用一个 pollfd的指针实现 pollfd结构包含了要监视的event和发生的event 不再使用select 参数 值 传递的方式 同时 pollfd并没有最大数量限制
  • CSS图片剪裁与原比例压缩或放大

    在前端网页制作的过程中 图片的处理往往比较头疼 当然不考虑你有很给力的美工后援的情况下 以下将对一些常见的CSS图片处理需求情况进行分析 1 一张图片要放在固定宽高的内容块中 并填充满整个内容块 看起来整齐划一 我们假设要把一张大小为192

随机推荐

  • cmake error:does not appear to contain CMAKEList.txt

    需要检查一下CMAKEList txt文件的权限 我这边在win10主机上git clone下载的代码 copy到ubuntu上 在ubuntu上执行cmake 提示找不到CMAKEList txt文件 排查了一圈 是因为权限问题 将文件权
  • 凯斯轴承数据故障诊断PHM轴承寿命预测深度学习迁移学习元学习开源代码集合

    实打实的开源手撸代码 没错 纯本人打造 保证精确度达到90 以上 可以看到可视化结果如下图所示
  • 这篇文章,让你了解ERC-1155 多代币标准协议

    文章目录 ERC1155 介绍 多代币标准 前提条件 代币标准 ERC 20 ERC 721 构建 ERC1155 代币合约 ERC 1155 的功能和特点 批量传输 批量余额 批量审批 接收钩子 支持非同质化代币 安全转账规则 ERC11
  • mysql 主键 重置_在MySQL中重置主键

    要重置主键 首先使用TRUNCATE表 然后使用ALTER TABLE 让我们首先创建一个表 mysql gt create table DemoTable1929 UserId int NOT NULL AUTO INCREMENT PR
  • JVM调优总结(三)-基本垃圾回收算法

    可以从不同的的角度去划分垃圾回收算法 按照基本回收策略分 引用计数 Reference Counting 比较古老的回收算法 原理是此对象有一个引用 即增加一个计数 删除一个引用则减少一个计数 垃圾回收时 只用收集计数为0的对象 此算法最致
  • dot product【点积】

    1 概念 点积在数学中 又称数量积 dot product scalar product 是指接受在实数R上的两个向量并返回一个实数值标量的二元运算 两个向量a a1 a2 an 和b b1 b2 bn 的点积定义为 a b a1b1 a2
  • 不能安装 64 位版本的 Microsoft Access 2010 数据库引擎,因为您当前已安装 32 位的 Office 产品一例问题的解决

    这个以前遇到过 那次处理的时候是在卸载程序中卸载 Microsoft Office Access database engine 2007 来解决的 但这次 我打开卸载程序界面 找不到office 2007 看到一个有关office 200
  • 有赞前端SP毁约后的日子

    22届双非本 22年3月底前端sp被有赞毁约 5月底重新找到工作 6月底入职 前言 本人不想读研 考公 只想工作 而且想着全国这么多公司 总能找到工作吧 大不了降低要求 山雨欲来风满楼 自从21年11月份拿了offer后 我就开始摆烂了 准
  • Django基础入门⑪:DjangoDjango数据表关联(一对一,一对多,多对多关系)

    Django基础入门 DjangoDjango数据表关联 Django数据表关联 一对一关系类型 语法格式 实例应用 一对多关系类型 必填参数 可选参数 语法格式 实例应用 多对多关系 ManyToManyFiled定义 可选参数 语法格式
  • 西门子1200连接安川伺服的心得

    安川伺服通信注意点 安川的伺服驱动器只支持安川控制系统的通讯协议MECHATROLINK II 和其他厂家的PLC搭配使用目前采用的方式只能是通过脉冲序列来控制 读取绝对值编码器数值方式可以采取自由口通信或高数计数器的方式 1 伺服电机中编
  • 常用的Vue生命周期函数

    Vue生命周期函数 组件挂载 组件更新 组件销毁时触发的一些方法 这些方法就叫做生命周期函数 beforeCreate console log 刚刚创建实例 created console log 实例创建完成 beforeMount co
  • eclipse开发工具技巧之打开内置浏览器

    前言 eclipse是非常强大的java开发工具 java是现在最流行 使用人数最多的语言 虽然现在idea很火 但很多中小公司还是以eclipse为主 用它应付绝大多数项目是没有任何问题 我也建议新手用eclipse入门 因为它确实很简单
  • 【华为OD统一考试B卷

    在线OJ 已购买本专栏用户 请私信博主开通账号 在线刷题 运行出现 Runtime Error 0Aborted 请忽略 华为OD统一考试A卷 B卷 新题库说明 2023年5月份 华为官方已经将的 2022 0223Q 1 2 3 4 统一
  • Cisco交换机配置VTP

    文章目录 1 拓扑图 2 任务描述 3 Sw1配置 4 Sw2配置 5 Sw3配置 6 测试 1 拓扑图 2 任务描述 在 SW1 SW2 和 SW3 上配置 VTP 版本2 Sw1为服务器 Sw2 Sw3为客户端 使用java csdn做
  • Java接口默认实现、接口和抽象类区别

    Java8新特性 Java8接口可添加默认实现 接口和抽象类的区别 设计模式 缺省适配模式 Java8接口可添加默认实现 java8新增了接口默认实现功能 每个接口可以有默认实现 实现类可以根据其需要进行定制化得实现 抽象方法前面添加def
  • 复旦邱锡鹏:深度剖析 ChatGPT 类大语言模型的关键技术

    内容来源 ChatGPT 及大模型专题研讨会 分享嘉宾 复旦大教授 邱锡鹏 分享主题 对话式大型语言模型 转载自CSDN稿件 ChapGPT 自问世以来 便展现出了令世人惊艳的对话能力 仅用两个月时间 ChatGPT 月活跃用户就达一亿 是
  • 网课教程(1) 前言

    什么是脚本 脚本 Script 是使用一种特定的描述性语言 依据一定的格式编写的可执行文件 脚本语言又被称为扩建的语言 或者动态语言 是一种编程语言 用来控制软件应用程序 脚本通常是以文本 ASC 保存 只是在被调用时进行解释或者编译 我们
  • CRM系统基本的模板示例

    CRM SSM总结 1 步骤 1 1 创建WEB项目 1 2 导入JAR lib下 包以及静态资源 css fonts js jsp 2 数据库 CREATE DATABASE crm ssm 客户来源 电话营销 网络营销 推广活动 促销活
  • 模式识别原理(Pattern Recognition)、概念、系统、特征选择和特征

    1 1 模式识别的基本概念 一 广义定义 1 模式 一个客观事物的描述 一个可用来仿效的完善的例子 2 模式识别 按哲学的定义是一个 外部信息到达感觉器官 并被转换成有意义的感觉经验 的过程 例 识别热水 字迹等 二 狭义的定义 1 模式
  • ML-数据分析模板

    文章目录 机器学习 数据分析模板 Objective Data Set Information Attribute Information INPUT 单特征与缺失值展示 Feature Cleaning Engineering 标签转换