我正在尝试使用预训练的嵌入和自定义语料库在 Keras 2 中使用 Tensorflow 后端重新训练 word2vec 模型。
这就是我使用预训练嵌入来初始化嵌入层的方法:
embedding = Embedding(vocab_size, embedding_dim,
input_length=1, name='embedding',
embeddings_initializer=lambda x: pretrained_embeddings)
where pretrained_embeddings
是一个大小很大的矩阵vocab_size
x embedding_dim
只要这样就有效pretrained_embeddings
不太大。
不幸的是,就我而言,情况并非如此 -vocab_size=2270872
and embedding_dim=300
.
初始化嵌入层后,我收到错误:
Cannot create a tensor proto whose content is larger than 2GB.
错误来自于函数add_weight()
in
/opt/r/anaconda3/lib/python3.6/site-packages/keras/engine/base_layer.py
,更具体地说是以下行:
weight = K.variable(initializer(shape),
dtype=dtype,
name=name,
constraint=constraint)
initializer
是上面的 lambda 函数,它返回大矩阵。shape
is (2270872, 300)
正如已经提到的。
是否可以解决这个问题而无需进行低级 Tensorflow 编程?如果我切换到 Theano 作为后端,代码运行良好,但我想使用 Tensorflow 以获得更好的长期前景。
我发现的唯一类似的 Stackoverflow 问题是this https://stackoverflow.com/questions/35394103/initializing-tensorflow-variable-with-an-array-larger-than-2gb,它提出了占位符变量,但我不确定如何在 Keras 级别上应用它们。
多谢
Edit:我非常愿意在 Tensorflow 后端层面解决这个问题。只是我不知道如何在本例中将 Tensorflow 和 Keras 代码组合在同一个应用程序中。大多数例子都是其中之一,而不是两者兼而有之。
例如,当 Keras 中 Embeddings 层的初始化将不可避免地调用 add_weight() 函数并导致问题时,Tensorflow 占位符变量有什么用?
解决方案:
正如 @blue-phoenox 的评论所暗示的,我重写了代码,如下所示:
embedding = Embedding(vocab_size, embedding_dim,
input_length=1,
name='embedding')
embedding.build(input_shape=(1,)) # the input_shape here has no effect in the build function
embedding.set_weights([pretrained_embeddings])
就这样做到了。再次感谢@blue-phoenix。