CBOW

CBOW(continuous bag of words ):
用来完成word2vec

import tensorflow as tf
import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt




def one_hot(ind, vocab_size):
    rec = np.zeros(vocab_size)
    rec[ind] = 1
    return rec


def create_training_data(corpus_raw, window_size=2):
    words_list = []
    for sent in corpus_raw.split('.'):
        for w in sent.split():
            words_list.append(w)
    words_list = set(words_list)

    word2ind = {}
    ind2word = {}

    vocab_size = len(words_list)

    for i, w in enumerate(words_list):
        word2ind[w] = i
        ind2word[i] = w
    sentence_list = corpus_raw.split('.')
    sentences = []
    for sent in sentence_list:
        sent_array = sent.split()
        sent_array = [s.split('.')[0] for s in sent_array]
        sentences.append(sent_array)

    data_recs = []
    for sent in sentences:
        for ind, w in enumerate(sent):
            rec = []
            for nb_w in sent[max(ind - window_size, 0): min(ind + window_size,  len(sent)) + 1]:
                if nb_w != w:
                    rec.append(nb_w)
                data_recs.append([rec, w])
    x_train = []
    y_train = []

    for rec in data_recs:
        input_ = np.zeros(vocab_size)
        for i in range(window_size - 1):
            input_ += one_hot(word2ind[rec[0][i]], vocab_size)
        input_ = input_ / len(rec[0])
        x_train.append(input_)
        y_train.append(one_hot(word2ind[rec[1]], vocab_size))

    return x_train, y_train, word2ind, ind2word,vocab_size




corpus_raw = "Deep Learning has evolved from Artificial Neural Networks, which has been\
 there since the 1940s. Neural Networks are interconnected networks of processing units\
 called artificial neurons that loosely mimic axons in a biological brain. In a biological\
 neuron, the dendrites receive input signals from various neighboring neurons, typically\
 greater than 1000. These modified signals are then passed on to the cell body or soma of\
 the neuron, where these signals are summed together and then passed on to the axon of the\
 neuron. If the received input signal is more than a specified threshold, the axon will\
 release a signal which again will pass on to neighboring dendrites of other neurons. Figure\
 2-1 depicts the structure of a biological neuron for reference. The artificial neuron units\
 are inspired by the biological neurons with some modifications as per convenience. Much\
 like the dendrites, the input connections to the neuron carry the attenuated or amplified\
 input signals from other neighboring neurons. The signals are passed on to the neuron, where\
 the input signals are summed up and then a decision is taken what to output based on the\
 total input received. For instance, for a binary threshold neuron an output value of 1 is\
 provided when the total input exceeds a pre-defined threshold; otherwise, the output stays\
 at 0. Several other types of neurons are used in artificial neural networks, and their\
 implementation only differs with respect to the activation function on the total input to\
 produce the neuron output. In Figure 2-2 the different biological equivalents are tagged in\
 the artificial neuron for easy analogy and interpretation."


corpus_raw = corpus_raw.lower()
x_train, y_train, word2ind, ind2word, vocab_size = create_training_data(corpus_raw, 2)

emb_dim = 128
learning_rate = 0.001

x = tf.placeholder(tf.float32, shape=[None, vocab_size])
y = tf.placeholder(tf.float32, shape=[None, vocab_size])
W = tf.Variable(tf.random_normal(shape=[vocab_size, emb_dim], mean=0.0, stddev=0.02, dtype=tf.float32))
b = tf.Variable(tf.random_normal(shape=[emb_dim], mean=0.0, stddev=0.02, dtype=tf.float32))
W_outer = tf.Variable(tf.random_normal(shape=[emb_dim, vocab_size], mean=0.0, stddev=0.02, dtype=tf.float32))
b_outer = tf.Variable(tf.random_normal(shape=[vocab_size], mean=0.0, stddev=0.02, dtype=tf.float32))

hidden = tf.add(tf.matmul(x, W), b)
print hidden.shape
logits = tf.add(tf.matmul(hidden, W_outer), b_outer)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)


epochs, batch_size = 100, 10
batch = len(x_train) // batch_size
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(epochs):
        batch_index = 0
        for batch_num in range(batch):
            x_batch = x_train[batch_index: batch_index + batch_size]
            y_batch = y_train[batch_index: batch_index + batch_size]
            sess.run(optimizer, feed_dict={x: x_batch, y: y_batch})
        print ("loss:", sess.run(cost, feed_dict={x: x_batch, y: y_batch}))
        batch_index = batch_index + batch
    W_embed_trained = sess.run(W)


W_embedded = TSNE(n_components=2).fit_transform(W_embed_trained)   #实现降为,将131维数据降低到2维,方便画图展示
plt.figure(figsize=(10,10))
for i in xrange(len(W_embedded)):
    plt.text(W_embedded[i,0],W_embedded[i,1],ind2word[i])
plt.xlim(-150,150)
plt.ylim(-150,150)
plt.show()


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,743评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,296评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,285评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,485评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,581评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,821评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,960评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,719评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,186评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,516评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,650评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,329评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,936评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,757评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,991评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,370评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,527评论 2 349