在Tensorflow或Keras中,是否有可能出现文本的一个热编码字符?
tf.one_hot
似乎只接受整数。tf.keras.preprocessing.text.one_hot
似乎只把句子编码成单词,但对字符却没有.除此之外,tf.keras.preprocessing.text.one_hot
的工作非常奇怪,因为响应看起来并不是一个热编码,因为下面的代码:
text = "ab bba bbd"
res = tf.keras.preprocessing.text.one_hot(text=text,n=3)
print(res)
导致这一结果:
[1,2,2]
每次我运行这个程序,输出是一个不同的三维矢量,有时是[1,1,1]
或[2,1,1]
。文件上说,统一是没有保证的,但这在我看来是毫无意义的。
发布于 2018-03-21 08:00:17
我在纯python的基础上找到了一个很好的答案,不幸的是我再也找不到源代码了。它首先将每个字符转换为int,然后用一个热数组替换int。它对整个程序具有唯一性,如果字母表长度和顺序相同的话,甚至对所有程序也是如此。
# Is the alphabet of all possible chars you want to convert
alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
def convert_to_onehot(data):
#Creates a dict, that maps to every char of alphabet an unique int based on position
char_to_int = dict((c,i) for i,c in enumerate(alphabet))
encoded_data = []
#Replaces every char in data with the mapped int
encoded_data.append([char_to_int[char] for char in data])
print(encoded_data) # Prints the int encoded array
#This part now replaces the int by an one-hot array with size alphabet
one_hot = []
for value in encoded_data:
#At first, the whole array is initialized with 0
letter = [0 for _ in range(len(alphabet))]
#Only at the number of the int, 1 is written
letter[value] = 1
one_hot.append(letter)
return one_hot
print(convert_to_onehot("hello world"))
https://stackoverflow.com/questions/49370940
复制相似问题