Tensorflow是Google提供的一种机器学习框架。它是一个开放源代码框架,与Python结合使用以实现算法,深度学习应用程序等等。它用于研究和生产目的。它具有优化技术,可帮助快速执行复杂的数学运算。
这是因为它使用NumPy和多维数组。这些多维数组也称为“张量”。该框架支持使用深度神经网络。它具有高度的可扩展性,并附带许多流行的数据集。它使用GPU计算并自动进行资源管理。
可以使用下面的代码行在Windows上安装'tensorflow'软件包-
pip install tensorflow
Tensor是TensorFlow中使用的数据结构。它有助于连接流程图中的边缘。该流程图称为“数据流程图”。张量不过是多维数组或列表。
以下代码使用了Wikipedia上的文章来训练模型。它有助于理解单词嵌入。单词嵌入是指能够捕获文档中特定单词的上下文,其与其他单词的关系,其语法相似性等的表示形式。它们是向量的形式。可以使用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("字数为:", len(text_words))
print("独特的词:", len(set(text_words)))
print("词汇量:", vocabulary_size)
print("最常用的词:", count[:8])代码信用-https ://github.com/aymericdamien/TensorFlow-Examples/blob/master/tensorflow_v2/notebooks/2_BasicModels/word2vec.ipynb
输出结果
字数为: 17005207
独特的词: 253854
词汇量: 47135
最常用的词: [('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”。
迭代数据文件中的单词,并在控制台上显示单词的总数,词汇量和常用单词。