在用Pytorch 验证标签的时候,建议使用ont-hot 编码,这样比较容易实现既定的功能。
直接上代码: 字符串类型 本代码将hello world 换做了矩阵
from numpy import argmax
# define input string
data = 'hello world'
print(data)
# define universe of possible input values
alphabet = 'abcdefghijklmnopqrstuvwxyz '
# define a mapping of chars to integers
char_to_int = dict((c, i) for i, c in enumerate(alphabet))
print("char_to_int:",char_to_int,len(char_to_int))
int_to_char = dict((i, c) for i, c in enumerate(alphabet))
print("int_to_char:",int_to_char)
# integer encode input data
integer_encoded = [char_to_int[char] for char in data]
print(integer_encoded,len(integer_encoded)) ## 寻找数据对应的编码
# one hot encode
onehot_encoded = list()
for value in integer_encoded:
letter = [0 for _ in range(len(alphabet))]
letter[value] = 1
onehot_encoded.append(letter)
# print(letter,len(alphabet)
print(onehot_encoded)
#