gpt4 book ai didi

python - 在窗口分类上使用 Tensorflow 时嵌入向量未更新

转载 作者:太空宇宙 更新时间:2023-11-03 13:11:50 24 4
gpt4 key购买 nike

我正在尝试使用 tensorflow 实现基于窗口的分类器,

词嵌入矩阵称为 word_vec 并随机初始化(我也试过 Xavier)。

ind 变量是矩阵中单词向量索引的向量。

第一层是config['window_size'] (5) 词向量拼接。

word_vecs = tf.Variable(tf.random_uniform([len(words), config['embed_size']], -1.0, 1.0),dtype=tf.float32)
ind = tf.placeholder(tf.int32, [None, config['window_size']])
x = tf.concat(1,tf.unpack(tf.nn.embedding_lookup(word_vecs, ind),axis=1))
W0 = tf.Variable(tf.random_uniform([config['window_size']*config['embed_size'], config['hidden_layer']]))
b0 = tf.Variable(tf.zeros([config['hidden_layer']]))
W1 = tf.Variable(tf.random_uniform([config['hidden_layer'], out_layer]))
b1 = tf.Variable(tf.zeros([out_layer]))
y0 = tf.nn.tanh(tf.matmul(x, W0) + b0)
y1 = tf.nn.softmax(tf.matmul(y0, W1) + b1)
y_ = tf.placeholder(tf.float32, [None, out_layer])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y1), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(0.5).minimize(cross_entropy)

这就是我运行图表的方式:

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(config['iterations'] ):
r = random.randint(0,len(sentences)-1)
inds=generate_windows([w for w,t in sentences[r]])
#inds now contains an array of n rows on window_size columns
ys=[one_hot(tags.index(t),len(tags)) for w,t in sentences[r]]
#ys now contains an array of n rows on output_size columns
sess.run(train_step, feed_dict={ind: inds, y_: ys})

维度算出来,代码运行

但是,准确度接近于零,我怀疑词向量没有正确更新。

如何使 tensorflow 更新从串联窗口形式返回的词向量?

最佳答案

您的嵌入使用默认可训练的 tf.Variable 进行初始化。他们将被更新。问题可能出在您计算损失的方式上。看看下面这些行

y1 = tf.nn.softmax(tf.matmul(y0, W1) + b1)
y_ = tf.placeholder(tf.float32, [None, out_layer])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y1), reduction_indices=[1]))

这里你正在计算将分数转换为概率的 softmax 函数

softmax equation

如果这里的分母变得太大或者太小那么这个函数就可以去折腾了。为了避免这种数值不稳定性,通常会添加一个小的 epsilon,如下所示。这确保了数值稳定性。

softmax_with_epsilon

您可以看到,即使在添加 epsilon 之后,softmax 函数值仍保持不变。如果您不自行处理此问题,则渐变可能会因渐变消失或爆炸而无法正确更新。

避开三行代码,使用tensorflow版本tf.nn.sparse_softmax_cross_entropy_with_logits

请注意,此函数将在内部计算 softmax 函数。建议使用它而不是手动计算损失。您可以按如下方式使用它

y1 = tf.matmul(y0, W1) + b1
y_ = tf.placeholder(tf.float32, [None, out_layer])
cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y1, labels=y_))

关于python - 在窗口分类上使用 Tensorflow 时嵌入向量未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41840239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com