如何在python3的keras中称呼one\u hot?

2024-10-02 12:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python3中有以下代码:

docs = ['Well done!',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent!',
        'Weak',
        'Poor effort!',
        'not good',
        'poor work',
        'Could have done better.']
# define class labels
labels = np.array([1,1,1,1,1,0,0,0,0,0])
from keras import backend as K


# integer encode the documents
vocab_size = 50
encoded_docs = [K.one_hot(d, vocab_size) for d in docs]
print(encoded_docs)

基本上,我尝试对列表中的每个单词进行编码,但我遇到了以下错误:

TypeError: Value passed to parameter 'indices' has DataType string not in list of allowed values: uint8, int32, int64 。你知道吗

我的代码有什么问题?这似乎是一个类型错误,但我不明白为什么。你知道吗


Tags: 代码indocssizelabels错误notpython3
2条回答

Kerasone_hot方法要求第一个参数是整数类型(在您的例子中是单词索引)。所以在使用one_hot方法之前,首先需要将每个单词映射到唯一的整数。你知道吗

docs = ['Well done!',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent!',
        'Weak',
        'Poor effort!',
        'not good',
        'poor work',
        'Could have done better.']
all_words = set()
for s in docs:
    for word in s.split():
        all_words.add(word)
all_words = list(all_words)
# define class labels
labels = np.array([1,1,1,1,1,0,0,0,0,0])
from keras import backend as K


# integer encode the documents
vocab_size = len(all_words)
encoded_docs = [[K.one_hot(all_words.index(word), vocab_size) for word in d.split()] for d in docs]
print(encoded_docs)


如果要将标点符号编码为单独的单词,那么可以使用re模块拆分单词。你知道吗

import re
import string

encoded_docs = [[K.one_hot(all_words.index(word), vocab_size) for word in re.findall("[\w]+|["+string.punctuation+"]", d) for d in docs]

在没有任何整数转换的情况下,我使用了:

encoded_docs = [keras.preprocessing.text.one_hot(d,vocab_size)for d in docs]

真管用!你知道吗

相关问题 更多 >

    热门问题