📒
Notes
  • 个人笔记
  • Machine Learning
    • Tensorflow
      • Text
        • Keras构建RNN
        • 字词嵌入
        • 字词嵌入示例程序
      • Data processing
        • tf.data数据加载
      • Tensorflow Tricks
    • 循环神经网络概览
    • Pix2Pix
  • Assembly Language
    • DOS中的Debug模式
    • LOOP指令
    • 8086CPU
    • 标志位寄存器
    • 汇编指令
    • 汇编语言源程序格式
  • Linux System
    • Systemctl 服务脚本
    • Linux端口占用
    • Btrfs文件系统
    • C Socket网络编程细节问题
  • Hexo
    • Hexo下的Tag/Categories栏
    • Git备份博客
    • Hexo博客基本部署
  • Kernel
    • C语言中消息队列实现
    • Linux内核的进程调度函数
    • Linux内核模块的编译
    • Linux Kernel概述
  • Linux Software
    • Linux软件安装与配置
  • Docker
    • OVS+Docker网络构建
    • Docker分层垃圾清理
  • C
    • CMakeList语法
Powered by GitBook
On this page
  • Step 1. 数据载入
  • Step 2. 模型构建
  • Setp 3. 训练模型
  • Step 4. 编码效果可视化
  • 参考

Was this helpful?

  1. Machine Learning
  2. Tensorflow
  3. Text

字词嵌入示例程序

为了对于字词嵌入的实际应用有一个完整的理解,在此继续参照Tensorflow官方文档给出的示例整理一遍字词嵌入的实现过程。

首先导入必要的库:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

import tensorflow_datasets as tfds

Step 1. 数据载入

数据通过tensorflow_datasets这一包来加载:

(train_data, test_data), info = tfds.load(
    'imdb_reviews/subwords8k',
    split = (tfds.Split.TRAIN, tfds.Split.TEST),
    with_info=True, as_supervised=True)

encoder = info.features['text'].encoder

载入之后train_data和test_data是一个tf.data.Dataset,其中就已经是映射成整数值之后的文本数据了,对应的文本可以在info中找到。所以将文本进行编码的过程在此就跳过了。

下一步将数据转换为batch形式。由于文本数据时间不定长的,所以使用padded_batch,注意文档中badded_shaps参数少了要补上。

train_batches = train_data.shuffle(1000).padded_batch(10, ((None,),()))
test_batches = test_data.shuffle(1000).padded_batch(10, ((None,),()))

Step 2. 模型构建

为了训练Embedding layer,我们需要构建一个简单的模型,其中就要用到Embedding layer。在其后,由于Embedding layer的输出仍然是不定长的,为了保证输出的形状一致这样后面才能使用全连接层进行计算,所以采用了简单粗暴的GlobalAveragePooling来把结果变为定长的(简单演示而已)。

embedding_dim=16

model = keras.Sequential([
  layers.Embedding(encoder.vocab_size, embedding_dim),
  layers.GlobalAveragePooling1D(),
  layers.Dense(16, activation='relu'),
  layers.Dense(1)
])

model.summary()

Setp 3. 训练模型

model.compile(optimizer='adam',
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(
    train_batches,
    epochs=10,
    validation_data=test_batches, validation_steps=20)

在这一个训练过程中,Embedding layer也就会一起通过BP算法进行学习,以达到更好的编码效果。

Step 4. 编码效果可视化

将模型的weight提取出来之后,我们将编码结果格式化后写入到文件,上传到Embedding Projector[2]即可查看可视化的结果。

import io

e = model.layers[0]
weights = e.get_weights()[0]
print(weights.shape) # shape: (vocab_size, embedding_dim)

encoder = info.features['text'].encoder

out_v = io.open('vecs.tsv', 'w', encoding='utf-8')
out_m = io.open('meta.tsv', 'w', encoding='utf-8')

for num, word in enumerate(encoder.subwords):
  vec = weights[num+1] # skip 0, it's padding.
  out_m.write(word + "\n")
  out_v.write('\t'.join([str(x) for x in vec]) + "\n")

out_v.close()
out_m.close()

效果如下:

参考

Previous字词嵌入NextData processing

Last updated 5 years ago

Was this helpful?

Word embeddings | TensorFlow Core
Embedding projector
word2vec_sample-visualize