我在 tflearn 中有一个 lstm 网络,它在给定前面单词的上下文的情况下预测序列中的下一个单词。这些词作为特定大小词汇表的索引输入网络,并以二进制类的形式输出,例如:
上下文:[45, 243, 1, 1906, 4, 2, 0, 0, 0, 0]
标签:[0,0,0.......1,0,0,......0,0,0](VOCAB_SIZE 的长度)
但是,该模型每次都学会预测几乎相同的单词,因为我在回归层中使用了“categorical_crossentropy”目标函数。
我想尝试根据我已经为数据集生成的词嵌入(word2vec)来评估损失。因此,预测“你好”的模型,其中基本事实是“嗨”,其损失将比预测“披萨”低得多。计划是计算两个嵌入向量之间的余弦,以获得单词之间的“相似度”。
我将此自定义损失函数添加到 tflearn 安装中的 objects.py 文件中,但在尝试将预测转换为嵌入向量时遇到了障碍。
tflearn/objectives.py:
vocab = np.loadtxt('/home/vocab.txt',dtype='str')
embedding_model = gensim.models.Word2Vec.load('/home/embedding')
def embedded_similarity(y_pred, y_true):
global vocab, embedding_model
with tf.name_scope("Similarity"):
#convert one-hot format to indices of max values (predictions)
pred_max = tf.argmax(y_pred,dimension=1)
true_max = tf.argmax(y_true,dimension=1)
#convert indices into embedded vectors
pred_vectors = tf.map_fn(lambda x: embedding_model[vocab[x]], pred_max)
true_vectors = tf.map_fn(lambda x: embedding_model[vocab[x]], true_max)
#calc dot product
dot_products = tf.reduce_sum(tf.mul(pred_vectors,true_vectors),axis=1)
#return inverse mean of dot products
return -1*(tf.reduce_mean(dot_products))
返回的错误是:
ValueError: Index out of range using input dim 0; input has only 0 dims for 'Similarity/map/while/strided_slice' (op: 'StridedSlice') with input shapes: [], [1], [1], [1].
这表明我不能使用张量来索引 vocab(一个 numpy 数组)。但是,我不能使用 eval() 来获取张量的值,因为它不是在会话中运行的。所以我需要一种方法来设置索引的一维张量到包含相应词向量的张量的转换,以便计算损失。
非常感谢有关此问题的任何帮助,或评估我的模型的其他方式。