如何使用Tensorflow训练‘Word2Vec’算法?
Tensorflow是谷歌提供的机器学习框架。它是一个开源框架,与Python结合使用,可以实现算法、深度学习应用等等。它用于研究和生产目的。它具有优化技术,有助于快速执行复杂的数学运算。
这是因为它使用了NumPy和多维数组。这些多维数组也称为“张量”。该框架支持与深度神经网络一起工作。它具有高度的可扩展性,并附带许多流行的数据集。它使用GPU计算并自动管理资源。
可以使用以下代码行在Windows上安装“tensorflow”包:
pip install tensorflow
张量是TensorFlow中使用的数据结构。它有助于连接数据流图中的边。这个数据流图被称为“数据流图”。张量只不过是多维数组或列表。
下面的代码使用维基百科的一篇文章来训练模型。它有助于理解词嵌入。词嵌入是指能够捕捉文档中特定词的上下文、它与其他词的关系、它的句法相似性等等的表示。它们以向量的形式存在。这些词向量可以使用Word2Vec技术学习。
以下是一个例子:
示例
from __future__ import division, print_function, absolute_import
import collections
import os
import random
import urllib
import zipfile
import numpy as np
import tensorflow as tf
learning_rate = 0.11
batch_size = 128
num_steps = 3000000
display_step = 10000
eval_step = 200000
eval_words = ['eleven', 'the', 'going', 'good', 'american', 'new york']
embedding_size = 200 # Dimension of embedding vector.
max_vocabulary_size = 50000 # Total words in the vocabulary.
min_occurrence = 10 # Remove words that don’t appear at least n times.
skip_window = 3 # How many words to consider from left and right.
num_skips = 2 # How many times to reuse the input to generate a label.
num_sampled = 64 # Number of negative examples that need to be sampled.
url = 'http://mattmahoney.net/dc/text8.zip'
data_path = 'text8.zip'
if not os.path.exists(data_path):
print("Downloading the dataset... (It may take some time)")
filename, _ = urllib.request.urlretrieve(url, data_path)
print("Th data has been downloaded")
with zipfile.ZipFile(data_path) as f:
text_words = f.read(f.namelist()[0]).lower().split()
count = [('RARE', −1)]
count.extend(collections.Counter(text_words).most_common(max_vocabulary_size − 1))
for i in range(len(count) − 1, −1, −1):
if count[i][1] < min_occurrence:
count.pop(i)
else:
break
vocabulary_size = len(count)
word2id = dict()
for i, (word, _)in enumerate(count):
word2id[word] = i
data = list()
unk_count = 0
for word in text_words:
index = word2id.get(word, 0)
if index == 0:
unk_count += 1
data.append(index)
count[0] = ('RARE', unk_count)
id2word = dict(zip(word2id.values(), word2id.keys()))
print("Word count is :", len(text_words))
print("Unique words:", len(set(text_words)))
print("Vocabulary size:", vocabulary_size)
print("Most common words:", count[:8])输出
Word count is : 17005207
Unique words: 253854
Vocabulary size: 47135
Most common words: [('RARE', 444176), (b'the', 1061396), (b'of', 593677), (b'and', 416629), (b'one', 411764), (b'in', 372201), (b'a', 325873), (b'to', 316376)]解释
导入并为所需的包设置别名。
定义学习参数、评估参数和word2vec参数。
加载并解压缩数据。
将稀有词分配标签“−1”。
迭代数据文件中的单词,并在控制台上显示单词总数、词汇量大小和常用词。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP