首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >一个热编码字符

一个热编码字符
EN

Stack Overflow用户
提问于 2018-03-19 19:30:14
回答 1查看 3.2K关注 0票数 3

在Tensorflow或Keras中,是否有可能出现文本的一个热编码字符?

  • tf.one_hot似乎只接受整数。
  • tf.keras.preprocessing.text.one_hot似乎只把句子编码成单词,但对字符却没有.

除此之外,tf.keras.preprocessing.text.one_hot的工作非常奇怪,因为响应看起来并不是一个热编码,因为下面的代码:

代码语言:javascript
运行
复制
text = "ab bba bbd"
res = tf.keras.preprocessing.text.one_hot(text=text,n=3)
print(res)

导致这一结果:

代码语言:javascript
运行
复制
[1,2,2]

每次我运行这个程序,输出是一个不同的三维矢量,有时是[1,1,1][2,1,1]。文件上说,统一是没有保证的,但这在我看来是毫无意义的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-21 08:00:17

我在纯python的基础上找到了一个很好的答案,不幸的是我再也找不到源代码了。它首先将每个字符转换为int,然后用一个热数组替换int。它对整个程序具有唯一性,如果字母表长度和顺序相同的话,甚至对所有程序也是如此。

代码语言:javascript
运行
复制
    # 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"))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49370940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档