word2vec_basic代码解析

来源:互联网 发布:盘古数据公司怎么样 编辑:程序博客网 时间:2024/04/28 05:47
import collectionsimport mathimport osimport randomimport zipfileimport numpy as npfrom six.moves import urllibimport tensorflow as tf# 如果下载失败,就手动下载http://mattmahoney.net/dc/text8.zip到sz07.01.py同目录下# http://mattmahoney.net/dc/text8.zipurl = '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 filenamefilename = 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 datawords = read_data(filename)print('Data size', len(words))vocabulary_size = 50000'''建立一个50000大小的词典:输入:read_data(filename)>>wordscount.extend(collections.Counter(words).most_common(vocabulary_size - 1)),这个语句的作用是统计words里17005270个单词每个单词出现的次数,显然words里的这些单词是有很多重复的'''def build_dataset(words):    count = [['UNK', -1]]    '''count.extend(collections.Counter(words).most_common(vocabulary_size - 1)),      这个语句的作用是统计words里17005270个单词每个单词出现的次数,      显然words里的这些单词是有很多重复的,这就是需要这个第二步建立词典的意义了,      并且统计完不同的单词每个单词的次数后选出出现频数最多的49999个词。      其实这个语句还不能保证49999个单词不重复,因此后续语句'''    count.extend(collections.Counter(words).most_common(vocabulary_size - 1))    '''count 中数据如:[['UNK', -1], ('the', 1061396), ('of', 593677), ('and', 416629),     ('one', 411764), ('in', 372201), ...,('efficacious', 9), ('nausica', 9), ('oersted', 9)    , ('bernardi', 9), ('scavenge', 9), ('contorted', 9)]    '''    '''创建了dictionary,它确保了单词是唯一的,但是不能保证它的大小与count(长度是50000个单词)的大小相同,但是代码运行中发现dictionary的大小还是50000 '''    dictionary = dict()    for word, _ in count:        dictionary[word] = len(dictionary)        # print(dictionary[word])    data = list()    unk_count = 0    '''在17005270个单词里取单词,查看取出的单词是不是在那大小为50000的字典里,如果在的话就把这个单词在字典里对应的值放到list类型的data中,如果不在的话,    就默认值为0,并且把这个单词看成是unk,并统计unk单词的个数。由于data是list类型的,因此data的里的数据相同的数据会重复出现,    那么data的长度就等于words的长度即17005270。'''    for word in words:        if word in dictionary:            index = dictionary[word]        else:            index = 0            unk_count += 1        data.append(index)    count[0][1] = unk_count    print(count[0][1])    reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))    return data, count, dictionary, reverse_dictionary    '''接着更新count,更新unk单词的个数,将dictionary的键值调换。最后返回data count dictionary reverse_dictionary'''data, count, dictionary, reverse_dictionary = build_dataset(words)del wordsprint('Most common words (+UNK)', count[:5])print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])data_index = 0'''调用函数:batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)。这一步是用来为skip-gram模型生成train batch数据的。'''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),是用来创建batch,并且这个batch是1行batch_size列,里面是随机数,类型是int32。    batch = np.ndarray(shape=(batch_size), dtype=np.int32)     #labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32),是用来创建于batch对应的label,并且label是batch_size行1列,里面也是int32类型的随机数。    labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)    span = 2 * skip_window + 1    #span在本例中为3,因为skip_window为1.而buffer是一个队列,大小为span,这个buffer是最重要的要处理的数据的存储方式。    buffer = collections.deque(maxlen=span)    #这个for就是对buffer进行初始化赋值,而data_index就是个全局变量用来记录已经从words里拿了多少数据(单词),在本例中span=3,所以每次从words里拿3个单词    for _ in range(span):        buffer.append(data[data_index])        data_index = (data_index + 1) % len(data)    for i in range(batch_size // num_skips):  #batch_size // num_skips是整除的意思    #target=skip_window的意思就是比如说单词序列  a b c d e f g,这里skip_windows=1,    #因为 a b c首先要放到buffer(队列)里,而target=skip_windows=1指向的是单词 b,    #而我们要做的预测就是根据b 预测a和c        target = skip_window        targets_to_avoid = [skip_window]        '''内层的for循环以及 while语句就是利用了一个小技巧,随机的取单词b的前面和后面一个单词,        放到label里面,那么batch里的内容就成了 b ,而label里的内容就成了a c或者c a(因为是随机取的)'''        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)这两个语句就是从data(17005270大小)        数据集里取一个新的单词放到buffer里,而buffer队列的队首的元素就被踢出队列。那么buffer队列里的数据就变成了 b c d。'''        buffer.append(data[data_index])        data_index = (data_index + 1) % len(data)    return batch, labelsbatch, 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]])batch_size = 128embedding_size = 128skip_window = 1num_skips = 2valid_size = 16valid_window = 100valid_examples = np.random.choice(valid_window, valid_size, replace=False)num_sampled = 64graph = tf.Graph()with graph.as_default():    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'):        #vocabulary_size大小为17005270,而embedding_size大小为128,那么embeddings这个占位符,        #所需要的数据就是vocabulary_size * embedding_size大小,且值在-1.0到1.0之间的矩阵。        embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))        #从embeddings结果里取出train_input所指示的单词对应位置的值,把结果存成矩阵embed。        embed = tf.nn.embedding_lookup(embeddings, train_inputs)        #创建NCE  loss需要的权重和偏置。而truncated_normal创建一个服从截断正态分布的tensor作为权重。        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]))    loss = tf.reduce_mean(tf.nn.nce_loss(weights=nce_weights,                                         biases=nce_biases,                                         labels=train_labels,                                         inputs=embed,                                         num_sampled=num_sampled,                                         num_classes=vocabulary_size))    optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)    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)    init = tf.global_variables_initializer()
0 0
原创粉丝点击