首页 > 解决方案 > 训练 CBOW 模型时 Keras 中的输入形状出错

问题描述

我正在为单词嵌入训练一个连续的单词模型,其中每个 one-hot 向量的形状是一个形状为 (V, 1) 的列向量。我正在使用生成器根据语料库生成训练示例和标签,但输入形状有误。

(这里 V = 5778)

这是我的代码:

def windows(words, C):
    i = C
    while len(words) - i > C:
        center = words[i]
        context_words = words[i-C:i] + words[i+1:i+C+1]
        i += 1
        yield context_words, center

def one_hot_rep(word, word_to_index, V):
    vec = np.zeros((V, 1))
    vec[word_to_index[word]] = 1
    return vec

def context_to_one_hot(words, word_to_index, V):
    arr = [one_hot_rep(w, word_to_index, V) for w in words]
    return np.mean(arr, axis=0)
def get_training_examples(words, C, words_to_index, V):
    for context_words, center_word in windows(words, C):
        yield context_to_one_hot(context_words, words_to_index, V), one_hot_rep(center_word, words_to_index, V)
V = len(vocab)
N = 50

w2i, i2w = build_dict(vocab)

model = keras.models.Sequential([
    keras.layers.Flatten(input_shape=(V, )),
    keras.layers.Dense(units=N, activation='relu'),
    keras.layers.Dense(units=V, activation='softmax')
])

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

model.fit_generator(get_training_examples(data, 2, w2i, V), epochs=5, steps_per_epoch=20)

我得到的错误

标签: numpykerasnlpword-embedding

解决方案


展平层得到至少 3 维 numpy 数组,但你给它 2 维


推荐阅读