Keras Embedding层

意义:embedding层的意义在于将文字向量化,如有10句话,每句话有5个单词,那么若用简单的one hot进行表示无法体现出单词与单词间的关系,而利用embedding层能够使得一个单词变为一个向量,从而能够利用向量间的计算方法对单词间的关系进行数值化估计

keras中提供了Embedding层,其常用形式如下:

model.add(Embedding(input_dim=10,output_dim=3,input_length=5))

上述代码中参数input_dim表示所输入的数组的最大值所不能超过的界限值,output_dim表示将输入的矩阵中的一个值用长度为多少的向量来表示,input_length表示一个数据所含有的特征数目,即矩阵的列数。若输入为(10,5)的矩阵,则可以理解为输入10句话,每句话有5个单词,每个单词用长度为3的向量来表示,因此输出shape为(10,5,3)。函数测试如下:

from keras.layers import Embedding
from keras import Sequential
import numpy as np

model = Sequential()

model.add(Embedding(input_dim=10,output_dim=2,input_length=7))

model.compile('rmsprop', 'mse')
a=np.array([[1, 1, 0, 1, 1, 0, 0],
            [1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1]]
)

result = model.predict(a)
print('Embedded a:\n', result)
print('shape Embedded a:\n', result.shape)

输出如下:

Embedded a:
 [[[-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.02440189 -0.01358169]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.02440189 -0.01358169]
  [-0.02440189 -0.01358169]]

 [[-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]]

 [[-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]
  [-0.01546042  0.01157654]]]
shape Embedded a:
 (3, 7, 2)

参考博客:Keras里Embedding层的理解

Related post

  1. 网址收藏夹

    2020-07-16

  2. JavaFx常用语句(查阅用)

    2020-09-28

  3. DP问题专项

    2022-11-24

  4. Java 容器

    2020-08-03

There are no comment yet.

COMMENT

Take a Coffee Break

Recommend post

  1. 常用工具指令

    2022-09-18

Category list

ABOUT

Welcome to FullStar, a captivating online destination where the realms of software development and personal reflections intertwine.

April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Life Logs

  1. 回首

    2023-07-14

Return Top