【发布时间】:2020-03-02 04:19:30
【问题描述】:
我正在尝试构建一个 Keras 模型 model_B,它输出另一个 Keras 模型 model_A 的输出。现在,model_A 的输出是根据来自多个具有不同词汇量的Keras embedding 层的几个张量的串联计算的。型号model_A 和model_B 基本相同。
问题:当我训练 model_A 时,一切正常。但是,当我在同一数据集上训练 model_B 时,出现以下错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[1] = 3 不在 [0, 2) [[{{node model_1/embedding_1/embedding_lookup}}]]
本质上,错误是说单词的索引超出了预期的词汇表,但事实并非如此。有人可以澄清为什么会这样吗?
这是一个可重现的问题示例:
from keras.layers import Input, Dense, Lambda, Concatenate, Embedding
from keras.models import Model
import numpy as np
# Constants
A = 2
vocab_sizes = [2, 4]
# Architecture
X = Input(shape=(A,))
embeddings = []
for a in range(A):
X_a = Lambda(lambda x: x[:, a])(X)
embedding = Embedding(input_dim=vocab_sizes[a],
output_dim=1)(X_a)
embeddings.append(embedding)
h = Concatenate()(embeddings)
h = Dense(1)(h)
# Model A
model_A = Model(inputs=X, outputs=h)
model_A.compile('sgd', 'mse')
# Model B
Y = Input(shape=(A,))
model_B = Model(inputs=Y, outputs=model_A(Y))
model_B.compile('sgd', 'mse')
# Dummy dataset
x = np.array([[vocab_sizes[0] - 1, vocab_sizes[1] - 1]])
y = np.array([1])
# Train models
model_A.fit(x, y, epochs=10) # Works well
model_B.fit(x, y, epochs=10) # Fails
从上面的错误中,不知何故,输入x[:, 1] 似乎被错误地馈送到词汇大小为 2 的第一个嵌入层,而不是第二个。有趣的是,当我交换词汇量(例如设置vocab_sizes = [4, 2])时,它可以工作,支持之前的假设。
【问题讨论】:
标签: python tensorflow keras