tensorflow实战-10.word2vec

源码目录:

tensorflow/examples/tutorials/word2vec/word2vec_basic.py

详细过程

1.下载并载入数据

url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes): 
    # 判断下下载过的就不下了
    if not os.path.exists(filename):    
        filename, _ = urllib.request.urlretrieve(url + filename, filename)  
    statinfo = os.stat(filename)  
    if statinfo.st_size == expected_bytes:    
        print('Found and verified', filename)  
    else:    
        print(statinfo.st_size)    
        raise Exception(        'Failed to verify ' + filename + '. Can you get to it with a browser?')  
    return filename

filename = maybe_download('text8.zip', 31344016)

def read_data(filename):  
    """解压缩并读取数据到数组中"""  
    with zipfile.ZipFile(filename) as f:    
        data = tf.compat.as_str(f.read(f.namelist()[0])).split() 
    return data

words = read_data(filename)
print('Data size', len(words))

2.建立词典

vocabulary_size = 50000
def build_dataset(words):  
    count = [['UNK', -1]]
    """"获取高频词"""
    count.extend(
            collections.Counter(words).most_common(
                   vocabulary_size - 1))  
    dictionary = dict()  
    """给每个高频词一个编号"""
    for word, _ in count:    
        dictionary[word] = len(dictionary)  
    data = list()  
    unk_count = 0  
    for word in words:   
        if word in dictionary:      
            index = dictionary[word]    
        else:      
            index = 0  # dictionary['UNK']      
            unk_count += 1    
    data.append(index)  #data和words对应,把词转换为下标
    count[0][1] = unk_count  #低频词个数,都算同一个字符
    reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))  
    return data, count, dictionary, reverse_dictionary

"""依次为所有词及下标,高频词及词频,高频词及下标,压缩词典"""
data, count, dictionary, reverse_dictionary = build_dataset(words)
del words  # Hint to reduce memory.
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])

3.根据skip-gram模型batch生成训练数据

data_index = 0
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是一维,labels是二维"""
    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个词 
    buffer = collections.deque(maxlen=span)  
    for _ in range(span):    # 依次取span个词
        buffer.append(data[data_index])    
        data_index = (data_index + 1) % len(data)  
    for i in range(batch_size // num_skips):    
        target = skip_window  # 目标词是中间那个
        targets_to_avoid = [ skip_window ]    
        for j in range(num_skips):      #从目标次左右取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])   #deque挤掉最前面的 
        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], reverse_dictionary[batch[i]],      '->', labels[i, 0], reverse_dictionary[labels[i, 0]])

4.构造神经网络

batch_size = 128
embedding_size = 128  # 词向量维度.
skip_window = 1       # 左右窗口大小.
num_skips = 2         #每个窗口取几个词
valid_size = 16     # Random set of words to evaluate similarity on.
valid_window = 100  # Only pick dev samples in the head of the distribution.
valid_examples = np.random.choice(valid_window, valid_size, replace=False)
num_sampled = 64    # Number of negative examples to sample.

graph = tf.Graph()
with graph.as_default():  
    """placeholder用来放置网络使用过程的数据"""
    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) 

    with tf.device('/cpu:0'):  
        """词向量,二维,词典大小*词向量维数"""
        embeddings = tf.Variable(        tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) 
        """根据train_inputs查找embedding"""   
        embed = tf.nn.embedding_lookup(embeddings, train_inputs)    
       """构造网络"""
       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]))  
       """定义lost function,"""
       loss = tf.reduce_mean(      
                tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels,                     num_sampled, vocabulary_size))  
       """定义优化方法"""     
       optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)  
      """norm化,每一行平方求和再开方.  """
      norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))  
      normalized_embeddings = embeddings / norm   
      """找到评估的几个词向量"""
      valid_embeddings = tf.nn.embedding_lookup(      normalized_embeddings, valid_dataset)  
      """相似度矩阵,得到每个待评估的词和所有词的相似度"""
      similarity = tf.matmul(      valid_embeddings, normalized_embeddings, transpose_b=True)  
      # Add variable initializer.  
      init = tf.initialize_all_variables()

5.开始训练

num_steps = 100001
with tf.Session(graph=graph) as session:  
     """初始化所有变量"""
    init.run()  
    print("Initialized")  
    average_loss = 0  
    for step in xrange(num_steps):    
        batch_inputs, batch_labels = generate_batch(        batch_size, num_skips, skip_window)    
        feed_dict = {train_inputs : batch_inputs, train_labels : batch_labels}    
        """运行依次迭代,指定loss函数,训练方法,初始数据"""  
        _,loss_val = session.run([optimizer, loss], feed_dict=feed_dict)    
        average_loss += loss_val    
        if step % 2000 == 0:      
            if step > 0:        
                average_loss /= 2000      
        # The average loss is an estimate of the loss over the last 2000 batches.      
            print("Average loss at step ", step, ": ", average_loss)  
            average_loss = 0    
        # Note that this is expensive (~20% slowdown if computed every 500 steps)    
        if step % 10000 == 0:      
            """计算similarity,结果是[评估个数*词数]"""
            sim = similarity.eval()      
            for i in xrange(valid_size):        
                valid_word = reverse_dictionary[valid_examples[i]]      
                top_k = 8 # number of nearest neighbors  
                """每个词的top_k个最相似词"""      
                nearest = (-sim[i, :]).argsort()[1:top_k+1]        
                log_str = "Nearest to %s:" % valid_word        
                for k in xrange(top_k):          
                    close_word = reverse_dictionary[nearest[k]]
                    log_str = "%s %s," % (log_str, close_word)
                print(log_str)  
    final_embeddings = normalized_embeddings.eval()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,561评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,218评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,162评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,470评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,550评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,806评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,951评论 3 407
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,712评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,166评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,510评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,643评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,306评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,930评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,745评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,983评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,351评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,509评论 2 348

推荐阅读更多精彩内容