独热向量编码原理

`# -- coding: utf-8 --
from future import unicode_literals
import numpy as np
import sklearn.preprocessing as sp

raw_samples = np.array([
[1, 3, 2],
[7, 5, 4],
[1, 8, 6],
[7, 3, 9]])
print(raw_samples)

底层原理

code_tables = []
先创建一个字典,来保存原始数据,编译的结果数据,用键值对来表示最好
一个列一个字典,那么就是一个字典列表了
for col in raw_samples.T:
code_table = {}
for val in col:
code_table[val] = None
code_tables.append(code_table)

给字典取值
for code_table in code_tables:
size = len(code_table)
for one, key in enumerate(sorted(code_table.keys())):
code_table[key] = np.zeros(shape=size, dtype=int)
code_table[key][one] = 1
ohe_samples = []
下面用到了列表里面嵌套列表
开始编码
for raw_sample in raw_samples:
ohe_sample = np.array([], dtype=int)
for i, key in enumerate(raw_sample):
ohe_sample = np.hstack(
(ohe_sample, code_tables[i][key]))
对每一行进行编码,
ohe_samples.append(ohe_sample)
把列表转化为数组
ohe_samples = np.array(ohe_samples)
print(ohe_samples)

独热编码器

ohe = sp.OneHotEncoder(sparse=False, dtype=int)
ohe_samples = ohe.fit_transform(raw_samples)
print(ohe_samples)
`
伪代码:
目的是把一个非全0和1 二维数组变化为只有0和1 的一个二维数组
需要用到字典容器
1 3 2 :101001000
7 5 4 :010100100
1 8 6 …
7 3 9
1:10 3:100 2:1000
7:01 5:010 4:0100
8:001 6:0010
9:0001

猜你喜欢

转载自blog.csdn.net/lc574260570/article/details/81625294