如何用TensorFlow训练词向量

340 篇文章 0 订阅
6 篇文章 1 订阅

前言

前面在《谈谈谷歌word2vec的原理》文章中已经把word2vec的来龙去脉说得很清楚了,接下去这篇文章将尝试根据word2vec的原理并使用TensorFlow来训练词向量,这里选择使用skip-gram模型。

语料库的准备

这里仅仅收集了网上关于房产新闻的文章,并且将全部文章拼凑到一起形成一个语料库。

skip-gram简要说明

skip-gram核心思想可以通过下图来看,假设我们的窗口大小为2,则对于文本”The quick brown fox jumps over the lazy dog.”,随着窗口的滑动将产生训练样本。比如刚开始是(the,quick)(the,brown)两个样本,右移一步后训练样本为(quick,the)(quick,brown)(quick,fox),继续右移后训练样本为(brown,the)(brown,quick)(brown,fox)(brown,jumps),接着不断右移产生训练样本。skip-gram模型的核心思想即是上面所说。

这里写图片描述

预料加载&分词

  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
以下是使用双向LSTM训练词向量的Python代码示例: ```python import tensorflow as tf from tensorflow.keras.layers import Input, Embedding, Bidirectional, LSTM, Dense from tensorflow.keras.models import Model from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # 构建模型 def build_model(vocab_size, embedding_dim, lstm_units): inputs = Input(shape=(None,)) x = Embedding(vocab_size, embedding_dim)(inputs) x = Bidirectional(LSTM(lstm_units))(x) outputs = Dense(embedding_dim, activation='linear')(x) model = Model(inputs=inputs, outputs=outputs) return model # 训练词向量 def train_word_embeddings(texts, embedding_dim=100, lstm_units=128, batch_size=64, epochs=10): # 构建 Tokenizer tokenizer = Tokenizer() tokenizer.fit_on_texts(texts) # 构建训练数据 sequences = tokenizer.texts_to_sequences(texts) padded_sequences = pad_sequences(sequences) # 构建模型 model = build_model(len(tokenizer.word_index) + 1, embedding_dim, lstm_units) model.compile(loss='mse', optimizer='adam') # 训练模型 model.fit(padded_sequences, padded_sequences, batch_size=batch_size, epochs=epochs) # 获取词向量 embeddings = model.layers[1].get_weights()[0] word_index = tokenizer.word_index word_embeddings = {word: embeddings[idx] for word, idx in word_index.items()} return word_embeddings ``` 使用方法: ```python texts = ['I like to eat apple', 'He hates to eat banana', 'She loves to eat orange'] word_embeddings = train_word_embeddings(texts) ``` 其中`texts`为训练文本,`word_embeddings`为训练得到的词向量

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超人汪小建(seaboat)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值