import numpy as np
from keras.utils import to_categorical
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 7]
data = array(data)
print(data)
# [1 2 3 4 5 6 7 8 9 7]
#有普通np数组转换为one-hot
one_hots = to_categorical(data)
print(one_hots)
# [[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
# [ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
# [ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
# [ 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
# [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
# [ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]]
# 由one-hot转换为普通np数组
data = [argmax(one_hot)for one_hot in one_hots]
print(data)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 7]
python numpy数组和one-hot编码相互转换
最新推荐文章于 2024-06-26 11:35:37 发布