python numpy陣列和one-hot編碼相互轉換
阿新 • • 發佈:2018-12-10
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]