numpy - 训练 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)
解决方案
展平层得到至少 3 维 numpy 数组,但你给它 2 维
推荐阅读
- ios - Xcode - 使用 AWS 框架的应用程序在模拟器上运行但在设备上崩溃
- regex - 正则表达式处理 Python 中的汉字字符
- c - 当使用 %s 在我的路径中设置文本时,它不会找到它
- string - 如何将 xargs 的输出连接到变量中?
- excel - 计算已关闭工作簿中多个值的总提及次数
- azure - 在 C# .Net 中使用 MSI 访问 Azure Key Vault
- c++ - 如何跟踪递归函数
- python - Jenkins 是实时流式传输管道的正确工具吗?
- python - 初始迁移文件到 virtualenv
- django - Django 表单无效:此字段是必需的