简单demo的代码路径在tensorflow\tensorflow\g3doc\tutorials\word2vec\word2vec_basic.py

Sikp gram方式的model思路

http://tensorflow.org/tutorials/word2vec/index.md

另外可以参考cs224d课程的课件。

 
 

窗口设置为左右1个词

对应skip gram模型
就是一个单词预测其周围单词(cbow模型是
输入一系列context词,预测一个中心词)

 
 

Quick -> the quick -> brown

Skip gram的训练目标cost function是

对应

但是这样太耗时了
每一步训练时间代价都是O(VocabularySize)

于是我们采用了 nce(noise-contrastive estimation)的方式,也就是负样本采样,采用某种方式随机生成词作为负样本,比如 quick -> sheep ,sheep作为负样本,假设我们就取一个负样本

 
 

  1. 输入数据
    这里是
    分隔好的单词
  2. 读入单词存储到list中
  3. 统计词频 0号位置给 unknown, 其余按照频次由高到低排列,unknown的获取按照预设词典大小
    比如50000,则频次排序靠后于50000的都视为unknown

    建立好 key->id id->key的双向索引map

4. 产生一组training batch

batch_size = 128

embedding_size = 128 # Dimension of the embedding vector.

skip_window = 1 # How many words to consider left and right.

num_skips = 2 # How many times to reuse an input to generate a label.

 
 

Batch_size每次sgd训练时候扫描的数据大小, embedding_size 词向量的大小,skip_window 窗口大小,

Num_skips = 2 表示input用了产生label的次数限制

demo中默认是2,
可以设置为1 对比下

默认2的时候

batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)

for i in range(8):

print(batch[i], '->', labels[i, 0])

print(reverse_dictionary[batch[i]], '->', reverse_dictionary[labels[i, 0]])

 
 

Sample data [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156]

-> 5239

originated -> anarchism

-> 12

originated -> as

12 -> 6

as -> a

12 -> 3084

as -> originated

6 -> 195

a -> term

6 -> 12

a -> as

195 -> 2

term -> of

195 -> 6

term -> a

3084左侧出现2次,对应窗口左右各1

设置1的时候

batch, labels = generate_batch(batch_size=8, num_skips=1, skip_window=1)

for i in range(8):

print(batch[i], '->', labels[i, 0])

print(reverse_dictionary[batch[i]], '->', reverse_dictionary[labels[i, 0]])

 
 

Sample data [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156]

-> 12

originated -> as

12 -> 3084

as -> originated

6 -> 12

a -> as

195 -> 2

term -> of

2 -> 3137

of -> abuse

3137 -> 46

abuse -> first

46 -> 59

first -> used

59 -> 156

3084左侧只出现1次

 
 

 
 

# Step 4: Function to generate a training batch for the skip-gram model.

def generate_batch(batch_size, num_skips, skip_window):

global data_index

assert batch_size % num_skips == 0

assert num_skips <= 2 * skip_window

batch = np.ndarray(shape=(batch_size), dtype=np.int32)

labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)

span = 2 * skip_window + 1 # [ skip_window target skip_window ]

buffer = collections.deque(maxlen=span)

for _ in range(span):

buffer.append(data[data_index])

data_index = (data_index + 1) % len(data)

for i in range(batch_size // num_skips):

target = skip_window # target label at the center of the buffer

targets_to_avoid = [ skip_window ]

for j in range(num_skips):

while target in targets_to_avoid:

target = random.randint(0, span - 1)

targets_to_avoid.append(target)

batch[i * num_skips + j] = buffer[skip_window]

labels[i * num_skips + j, 0] = buffer[target]

buffer.append(data[data_index])

data_index = (data_index + 1) % len(data)

return batch, labels

 
 

batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)

for i in range(8):

print(batch[i], '->', labels[i, 0])

print(reverse_dictionary[batch[i]], '->', reverse_dictionary[labels[i, 0]])

 
 

 
 

就是对于一个中心词
在window范围
随机选取 num_skips个词,产生一系列的

(input_id, output_id) 作为(batch_instance, label)

这些都是正样本

 
 

训练准备,

Input embedding W

 
 

 
 

Output embedding W^

 
 

后面code都比较容易理解,tf定义了nce_loss来自动处理,每次会自动添加随机负样本

num_sampled = 64 # Number of negative examples to sample.

 
 

graph = tf.Graph()

 
 

with graph.as_default():

 
 

# Input data.

train_inputs = tf.placeholder(tf.int32, shape=[batch_size])

train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])

valid_dataset = tf.constant(valid_examples, dtype=tf.int32)

 
 

# Construct the variables.

embeddings = tf.Variable(

tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))

nce_weights = tf.Variable(

tf.truncated_normal([vocabulary_size, embedding_size],

stddev=1.0 / math.sqrt(embedding_size)))

nce_biases = tf.Variable(tf.zeros([vocabulary_size]))

 
 

# Look up embeddings for inputs.

embed = tf.nn.embedding_lookup(embeddings, train_inputs)

 
 

# Compute the average NCE loss for the batch.

# tf.nce_loss automatically draws a new sample of the negative labels each

# time we evaluate the loss.

loss = tf.reduce_mean(

tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels,

num_sampled, vocabulary_size))

 
 

# Construct the SGD optimizer using a learning rate of 1.0.

optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)

 
 

训练过程利用embedding矩阵的乘法计算了不同词向量的欧式距离
并计算了高频几个词对应的距离最近的词展示

 
 

最后调用 skitlearn的TSNE模块
进行降维到2元,绘图展示。

 
 

Tensorflow 的Word2vec demo解析的更多相关文章

  1. IOS CoreData 多表查询demo解析

    在IOS CoreData中,多表查询上相对来说,没有SQL直观,但CoreData的功能还是可以完成相关操作的. 下面使用CoreData进行关系数据库的表与表之间的关系演示.生成CoreData和 ...

  2. Ionic Demo 解析

    Ionic Demo 解析 index.html 解析 1.引入所需要的类库 <link rel="manifest" href="manifest.json&qu ...

  3. 文本分布式表示(二):用tensorflow和word2vec训练词向量

    看了几天word2vec的理论,终于是懂了一些.理论部分我推荐以下几篇教程,有博客也有视频: 1.<word2vec中的数学原理>:http://www.cnblogs.com/pegho ...

  4. word2vec源代码解析之word2vec.c

    word2vec源代码解析之word2vec.c 近期研究了一下google的开源项目word2vector,http://code.google.com/p/word2vec/. 事实上这玩意算是神 ...

  5. 利用 TensorFlow 入门 Word2Vec

    利用 TensorFlow 入门 Word2Vec 原创 2017-10-14 chen_h coderpai 博客地址:http://www.jianshu.com/p/4e16ae0aad25 或 ...

  6. 转:RealThinClient LinkedObjects Demo解析

    这个Demo源码实现比较怪,有点拗脑,原因估是作者想把控件的使用做得简单,而封装太多. 这里说是解析,其实是粗析,俺没有耐心每个实现点都查实清楚,看源码一般也就连读带猜的. 这个Demo表达出的意义, ...

  7. android报表图形引擎(AChartEngine)demo解析与源码

    AchartEngine支持多种图表样式,本文介绍两种:线状表和柱状表. AchartEngine有两种启动的方式:一种是通过ChartFactory.get***View()方式来直接获取到view ...

  8. Tensorflow的CNN教程解析

    之前的博客我们已经对RNN模型有了个粗略的了解.作为一个时序性模型,RNN的强大不需要我在这里重复了.今天,让我们来看看除了RNN外另一个特殊的,同时也是广为人知的强大的神经网络模型,即CNN模型.今 ...

  9. tensorflow lite的demo在android studio上环境搭建

    由于很久没有接触过Android开发,而且最早用的是eclipse,所以这个demo在android studio上的搭建过程,真的是踩了不少坑.记录这篇文章,纯粹是给自己一点收获. 环境搭建的过程, ...

随机推荐

  1. CCActionManager

    当CCnode执行runAction的时候,runAction会调用动作管理类的addAction方法将它自己执行的动作传递给动作管理类,动作管理类再将动作添加到自己的动作序列中. 动过管理类通过定时 ...

  2. sqlmap笔记本

    /* 转载请注明出处 ID:珍惜少年时 */ 相关命令--current-user #当前数据库用户--privileges #查看当前数据库权限--dbms=mssql #指定数据库的类型--os- ...

  3. python的变量作用域问题

    偶然掉进了一个坑里.仔细分析了下原因.原来是变量作用域的问题.简单抽象如下: id=1 #许多行代码 [id for id in range(10)] #许多行代码 if id!=1: #做一些事情 ...

  4. 【GoLang】golang中可以直接返回slice吗?YES

    结论: 可以,slice本质是结构体,返回slice时返回的是结构体的值,结构体的指针.len.cap等信息也全部返回了. 如下: type slice struct { start *uintptr ...

  5. POJ 2676

    http://poj.org/problem?id=2676 深搜的题目. 题意呢就是一个数独的游戏,应该都知道规则. 思路:我的思路很简单,就是用数组来判断某个数字是否可以使用,而每一个数字都由三个 ...

  6. PyCharm 4.0.6 注册码

    Professional Edition版本比Free版本多了很多东西,比如 Web development,Django等等,重新下了Professional版本,虽然是只30天免费,但是到时候重装 ...

  7. struct vs class

    关于默认访问权限class中默认的成员访问权限是private的,而struct中则是public的. 关于继承方式class继承默认是private继承,而struct继承默认是public继承. ...

  8. Unity3D 降低IL2CPP编译可执行文件大小

    项目开始使用IL2CPP编译,后果是可执行文件急剧增加. google后发现国外一大神写的方法,原帖在这http://forum.unity3d.com/threads/suggestion-for- ...

  9. Zookeeper服务常用的操作命令

    Zookeeper服务安装之后,一般会在这个服务的基础之上安装其他的大数据平台,其他的框架一般会提供很多接口对Zookeeper中的内容进行一定的操作,但是功能相对单一,所以有些时候,有必要我们自己登 ...

  10. Pooled Allocation(池式分配)实例——Keil 内存管理

    引言:说到动态申请(Dynamic Allocation)内存的好处,学过C/C++的人可能都有体会.运行时的灵活申请自然要比编码时的猜测好的多.而在内存受限情况下这种灵活性又有特别的好处--能让我们 ...