机器学习——第二次上机——数据预处理基础
机器学习数据预处理基础
1. One-Hot编码
任务介绍
- 使用Pandas中的value_counts()函数,查看data中的特征User continent的取值类型, 并打印输出的内容;
- 使用pandas中的get_dummies()函数对data中的特征User continent进行One-Hot编码,参数prefix为User continent_;
- 将编码后的结果保存在encode_uc中,并输出变量的前5行内容。
预期实验结果
补全代码;
1 | import pandas as pd |
User continent North America 296 Europe 118 Oceania 41 Asia 36
Africa 7 South America 6 Name: count, dtype: int64 User
continent__Africa User continent__Asia User continent__Europe
0 False False False
1 False False False
2 False False False
3 False False True
4 False False False
.. … … …
499 False False True
500 False False False
501 False False False
502 False False False
503 False False False
User continent__North America User continent__Oceania
0 True False
1 True False
2 True False
3 False False
4 True False
.. … …
499 False False
500 True False
501 True False
502 True False
503 True False
User continent__South America
0 False
1 False
2 False
3 False
4 False
.. …
499 False
500 False
501 False
502 False
503 False
[504 rows x 6 columns]
2. 缺失值填补
任务介绍
- 使用pandas中的value_counts()函数打印输出data中的特征Traveler type的取值统计信息, 并查看其是否含有缺失值;
- 如果存在缺失值,将特征Traveler type在其他样本中取值频数最多的值保存在变量freq_v中,并使用freq_v进行缺失值填充;
- 再次打印输出特征Traveler type的取值统计信息。
预期实验结果
补全代码:
1 | import pandas as pd |
3. 特征标准化
任务1:
- 使用sklearn中preprocessing模块下的StandardScaler()函数对data的特征Score进行Z-score标准化;
- 将特征取值的均值保存在变量score_mean中,并打印;
- 将特征取值的方差保存在变量score_var中,并打印。
预期实验结果
补全代码:
1 | import pandas as pd |
[4.12301587] [1.01264487]
array([[ 0.87149149], [-1.11598231], [ 0.87149149], [-0.12224541], [-0.12224541]])
任务2:
- 自定义函数min_max()实现MinMax标准化,输入参数data为要进行标准化的数据,输出为标准化后的数据。
- 使自定义的min_max()函数对data的特征Score进行MinMax标准化,输出结果保存在score_transformed中,并打印变量的前5行内容
预期结果
补全代码:
1 | import pandas as pd |
0 1.00 1 0.50 2 1.00 3 0.75 4 0.75 Name: Score, dtype: float64
任务3:
- 自定义logistic()函数,输入参数为要进行标准化的数据,输出结果为经过标准化后的数据;
- 使用自定义函数对data的特征Member years进行Logsitic标准化,结果保存在member_transformed中,并输出变量的前5行内容。
预期结果:
补全代码
1 | #ogistic 标准化(Logistic Normalization)是一个将数据转换为 (0, 1) 范围的过程, |
0 0.999877 1 0.952574 2 0.880797 3 0.997527 4 0.999089 Name: Member years, dtype: float64
4. 特征离散化
任务介绍
- 使用Pandas的qcut()函数对data中的特征Member years进行等频离散化,结果保存在bins中;
- 使用pd.value_counts()函数统计categorical对象bins的取值信息。
预期结果
补全代码:
1 | import pandas as pd |
Member years (-1806.001, 2.0] 156 (6.0, 13.0] 124 (2.0, 4.0] 123 (4.0, 6.0] 101 Name: count, dtype: int64
5. 离群值检测
任务介绍
- 使用拉依达准则对data的特征Member years进行离群值检测;
- 如果存在离群值,输出离群值的个数outlier_num,并将包含离群值的数据记录保存在变量outeliers中,并打印变量内容。
预期结果
补全代码:
1 | import pandas as pd |
User country User continent Member years Traveler type
75 USA North America -1806 Solo
143 USA North America 13 Couples
Hotel name Hotel stars Nr. rooms Score
75 Treasure Island- TI Hotel & Casino 4.0 2884 5
143 Caesars Palace 5.0 3348 4