CNTK:从文件加载预训练词嵌入的解决方法
CNTK: Workaround for loading pretrained word embeddings from file
似乎无法将预训练嵌入加载到层中。参见 here
我的解决方法如下:
model = create_model()
E = [p for p in model.parameters if p.name == 'E'][0]
emb = np.asarray(np.loadtxt('embeddings.txt', delimiter=' '), dtype='float32')
model = model.clone(CloneMethod.clone, { E: constant(emb) })
with embeddings.txt 具有以下格式,其中行数是我使用的词汇表中的单词数,列数是我为嵌入选择的维度:
-0.05952413007617 0.12596195936203 -0.189506858587265 ...
-0.0871662572026253 -0.0454806201159954 -0.126074999570847 ...
...
以上看起来是正确的解决方法吗?
我开始了一个训练课程,与训练嵌入层时相比,参数数量减少了,这可能是一个很好的指示。
您能否尝试:E.value = emb 作为替代解决方法。
您的解决方法将嵌入冻结为常量。如果这是不可接受的,并且您想进一步训练嵌入,则上述方法可能是您的选择。
此问题已修复。例如:
# embedding, initialized from a user-supplied constant weight table
e = Embedding(weights=[[1, 3, 2], [3, 4, 1]])
# (you would get the weights from a file instead)
# test it:
y = Input(2)
dat = np.array([[-1., 1.]], dtype=np.float32)
res = e(y).eval({y: dat})
npout = np.matrix(dat[0]) * e.E.value
np.testing.assert_array_equal(res[0], npout, err_msg='Error in constant embedding layer')
似乎无法将预训练嵌入加载到层中。参见 here
我的解决方法如下:
model = create_model()
E = [p for p in model.parameters if p.name == 'E'][0]
emb = np.asarray(np.loadtxt('embeddings.txt', delimiter=' '), dtype='float32')
model = model.clone(CloneMethod.clone, { E: constant(emb) })
with embeddings.txt 具有以下格式,其中行数是我使用的词汇表中的单词数,列数是我为嵌入选择的维度: -0.05952413007617 0.12596195936203 -0.189506858587265 ... -0.0871662572026253 -0.0454806201159954 -0.126074999570847 ... ...
以上看起来是正确的解决方法吗? 我开始了一个训练课程,与训练嵌入层时相比,参数数量减少了,这可能是一个很好的指示。
您能否尝试:E.value = emb 作为替代解决方法。
您的解决方法将嵌入冻结为常量。如果这是不可接受的,并且您想进一步训练嵌入,则上述方法可能是您的选择。
此问题已修复。例如:
# embedding, initialized from a user-supplied constant weight table
e = Embedding(weights=[[1, 3, 2], [3, 4, 1]])
# (you would get the weights from a file instead)
# test it:
y = Input(2)
dat = np.array([[-1., 1.]], dtype=np.float32)
res = e(y).eval({y: dat})
npout = np.matrix(dat[0]) * e.E.value
np.testing.assert_array_equal(res[0], npout, err_msg='Error in constant embedding layer')