sklearn.preprocessing.OneHotEncoder()函数介绍

sklearn.preprocessing.OneHotEncoder()函数介绍

sklearn.preprocessing.OneHotEncoder(categories=‘auto’, drop=None, sparse=True,dtype=np.float64, handle_unknown=‘error’)

本博客主要想对categories参数的使用方法进行说明。

下面对OneHotEncoder()函数的参数进行说行:

categories: 表示特征的取值,该参数取值为list或者默认的’auto’
①categories='auto’时,编码时特征的取值取决于你输入编码数据的特征取值,两者的取值范围是一致的。
②categories取值为list时,编码时特征的取值为你输入的list(eg:list_features)的取值。len(list_features)等于特征的数量,list_features中每个元素(eg:list_feature_values)又是一个list,这个list里面的元素为特征取值的所有枚举,list_feature_values=[feature_values_1,……,feature_values_n],feature_values_n是这个特征的某种取值。

sparse:若为True时,返回稀疏矩阵,否则返回数组,默认为True。

handle_unknown:可以为字符串、error、ignore,在转换过程中,如果出现位置的分类特征时,是抛出错误或直接忽略

以前版本的n_values参数已经被categories代替,categorical_features参数也被取消了,所以已经没有n_values和categorical_features参数了。

example:

from sklearn import preprocessing
import numpy as np
import random
#独热编码的数据,数据7个样本,每个样本的特征数量为2个,
cat_data =[9,3,4,1,7,5,0,9,2,3,4,5,6,7]
cat_data = np.array(cat_data).reshape(-1,2)#cat_data.shape=(7,2)
#特征0,1所有取值的列表,必须升序排列
feature0_list = [9,4,7,0,2,6,16,29,20]#取值范围有9个值
feature1_list = [3,1,5,9,5,7,25,89]#取值范围有8个值
feature0_list.sort()
feature1_list.sort()
#得到编码器
one_hot = preprocessing.OneHotEncoder(sparse=False,
                                      categories=[feature0_list,feature1_list])
random.shuffle(cat_data)
print(cat_data)
print('cat_data.shape:',cat_data.shape)

one_hot_label = one_hot.fit_transform(cat_data)
print(one_hot_label)
print('one_hot_label.shape:',one_hot_label.shape)

编码的结果为:

Connected to pydev debugger (build 191.7479.30)
[[9 3]
 [9 3]
 [4 1]
 [0 9]
 [7 5]
 [7 5]
 [6 7]]
cat_data.shape: (7, 2)
[[0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]]
one_hot_label.shape: (7, 17)

Process finished with exit code 0
发布了5 篇原创文章 · 获赞 5 · 访问量 225

猜你喜欢

转载自blog.csdn.net/weixin_43450885/article/details/104909863