Luc*_*edo 5 python word2vec keras tensorflow word-embedding
我一直在关注 Towards Data Science 关于 word2vec 和 skip-gram 模型的教程,但我偶然发现了一个我无法解决的问题,尽管搜索了几个小时并尝试了很多不成功的解决方案。
由于使用了 keras.layers 中的 Merge 层,它向您展示了如何构建 skip-gram 模型架构的步骤似乎已被弃用。
我似乎对此进行了很多讨论,大多数答案是您现在需要使用 Keras 的功能 API 来合并层。但问题是,我是 Keras 的初学者,不知道如何将我的代码从 Sequential 转换为 Functional,这是作者使用的代码(我复制了):
from keras.layers import Merge
from keras.layers.core import Dense, Reshape
from keras.layers.embeddings import Embedding
from keras.models import Sequential
# build skip-gram architecture
word_model = Sequential()
word_model.add(Embedding(vocab_size, embed_size,
embeddings_initializer="glorot_uniform",
input_length=1))
word_model.add(Reshape((embed_size, )))
context_model = Sequential()
context_model.add(Embedding(vocab_size, embed_size,
embeddings_initializer="glorot_uniform",
input_length=1))
context_model.add(Reshape((embed_size,)))
model = Sequential()
model.add(Merge([word_model, context_model], mode="dot"))
model.add(Dense(1, kernel_initializer="glorot_uniform", activation="sigmoid"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
# view model summary
print(model.summary())
# visualize model structure
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
SVG(model_to_dot(model, show_shapes=True, show_layer_names=False,
rankdir='TB').create(prog='dot', format='svg'))
Run Code Online (Sandbox Code Playgroud)
当我运行块时,显示以下错误:
ImportError Traceback (most recent call last)
<ipython-input-79-80d604373468> in <module>()
----> 1 from keras.layers import Merge
2 from keras.layers.core import Dense, Reshape
3 from keras.layers.embeddings import Embedding
4 from keras.models import Sequential
5
ImportError: cannot import name 'Merge'
Run Code Online (Sandbox Code Playgroud)
我在这里问的是关于如何将这个 Sequential 转换为 Functional API 结构的一些指导。
这确实改变了。对于点积,您现在可以使用dot图层:
from keras.layers import dot
...
dot_product = dot([target, context], axes=1, normalize=False)
...
Run Code Online (Sandbox Code Playgroud)
当然,您必须axis根据您的数据设置参数。如果您设置normalize=True,这将给出余弦接近度。有关更多信息,请参阅文档。
要了解 Keras的函数式 API,文档中有一个很好的函数式 API 指南。如果您已经了解顺序 API,那么切换并不难。
| 归档时间: |
|
| 查看次数: |
10166 次 |
| 最近记录: |