我正在尝试拟合 Word2Vec 模型。根据Gensim的Word2Vec的文档,我们在使用它之前不需要调用model.build_vocabulary它。但它却要求我这样做。我尝试过调用这个函数,但没有成功。我之前也装了一个Word2Vec模型,不需要调用model.build_vocabulary。
难道我做错了什么?这是我的代码:
from gensim.models import Word2Vec
dataset = pd.read_table('genemap_copy.txt',delimiter='\t', lineterminator='\n')
def row_to_sentences(dataframe):
columns = dataframe.columns.values
corpus = []
for index,row in dataframe.iterrows():
if index == 1000:
break
sentence = ''
for column in columns:
sentence += ' '+str(row[column])
corpus.append([sentence])
return corpus
corpus = row_to_sentences(dataset)
clean_corpus = [[sentence[0].lower()] for sentence in corpus ]
# model = Word2Vec()
# model.build_vocab(clean_corpus)
model = Word2Vec(clean_corpus, size=100, window=5, min_count=5, workers=4)
Run Code Online (Sandbox Code Playgroud)
非常感谢帮助!我也在使用 macOS Sierra。网上关于将 Gensim 与 Mac D: 一起使用的支持并不多。
假设字典中有 1000 个单词(A1、A2、...、A1000)。据我了解,在单词嵌入或 word2vec 方法中,它的目的是用一个向量表示字典中的每个单词,其中每个元素表示该单词与字典中其余单词的相似度。每个向量应该有 999 个维度,或者每个 word2vec 向量的大小应该是 999,这是否正确?
但是使用 Gensim Python,我们可以修改 Word2vec 的“size”参数的值,在本例中假设 size = 100。那么“size=100”是什么意思呢?如果我们提取 A1 的输出向量,表示为 (x1,x2,...,x100),那么在这种情况下 x1,x2,...,x100 代表什么?
我是 Word2Vec 的新手,我正在尝试根据单词的相似性对单词进行聚类。首先,我使用 nltk 来分隔句子,然后使用生成的句子列表作为 Word2Vec 的输入。然而,当我打印词汇时,它只是一堆字母、数字和符号,而不是单词。具体来说,其中一个字母的示例是“< gensim.models.keyedvectors.Vocab object at 0x00000238145AB438>, 'L':”
# imports needed and logging
import gensim
from gensim.models import word2vec
import logging
import nltk
#nltk.download('punkt')
#nltk.download('averaged_perceptron_tagger')
with open('C:\\Users\\Freddy\\Desktop\\Thesis\\Descriptions.txt','r') as f_open:
text = f_open.read()
arr = []
sentences = nltk.sent_tokenize(text) # this gives a list of sentences
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',level=logging.INFO)
model = word2vec.Word2Vec(sentences, size = 300)
print(model.wv.vocab)
Run Code Online (Sandbox Code Playgroud) 我对 NLP 比较陌生,我正在尝试创建自己的单词嵌入,并在我的个人文档语料库中进行训练。
我正在尝试实现以下代码来创建我自己的单词嵌入:
model = gensim.models.Word2Vec(sentences)
Run Code Online (Sandbox Code Playgroud)
句子是句子列表。由于我无法传递成千上万的句子,所以我需要一个迭代器
# with mini batch_dir a directory with the text files
# MySentences is a class iterating over sentences.
sentences = MySentences(minibatch_dir) # a memory-friendly iterator
Run Code Online (Sandbox Code Playgroud)
我在 gensim 的创建者那里找到了这个解决方案:
class MySentences(object):
def __init__(self, dirname):
self.dirname = dirname
def __iter__(self):
for fname in os.listdir(self.dirname):
for line in open(os.path.join(self.dirname, fname)):
yield line.split()
Run Code Online (Sandbox Code Playgroud)
它对我不起作用。如果我知道如何从每个文档中获取句子列表,如何创建迭代器?
第二个非常相关的问题:如果我的目标是比较特定语料库中的文档相似性,那么从头开始使用该特定语料库的所有文档创建词嵌入总是比使用 GloVec 或 word2vec 更好吗?文档量约为40000篇。
干杯
更多预
我使用 Twitter 的 Sentiment140 数据集进行情感分析
代码:
从推文中获取文字:
tweet_tokens = []
[tweet_tokens.append(dev.get_tweet_tokens(idx)) for idx, item in enumerate(dev)]
Run Code Online (Sandbox Code Playgroud)
从 token 中获取未知单词
words_without_embs = []
[[words_without_embs.append(w) for w in tweet if w not in word2vec] for tweet in tweet_tokens]
len(words_without_embs)
Run Code Online (Sandbox Code Playgroud)
代码的最后一部分,计算向量作为左右单词(上下文)的平均值
vectors = {} # alg
for word in words_without_embs:
mean_vectors = []
for tweet in tweet_tokens:
if word in tweet:
idx = tweet.index(word)
try:
mean_vector = np.mean([word2vec.get_vector(tweet[idx-1]), word2vec.get_vector(tweet[idx+1])], axis=0)
mean_vectors.append(mean_vector)
except:
pass
if tweet == tweet_tokens[-1]: # last iteration
mean_vector_all_tweets = np.mean(mean_vectors, …Run Code Online (Sandbox Code Playgroud) 我正在寻找一个解决一个简单的文本分类问题与tensorflow.我用IMDB数据集建立了一个模型,知道评论是积极的还是消极的.数据是通过word2vec处理的,所以现在我有一堆矢量来分类.我认为我的问题是由于y_labels的形状不好,因为它们是一个维度,我想通过张量流对两个类输出进行分类,或者我错了.最后的信息,该模型运行良好,精度为1.0,也许太好了!谢谢您的帮助 !
X_train called train_vecs = (25000, 300) dtype: float64
X_test called test_vecs = (25000, 300) dtype: float64
y_test = shape (25000, 1) dtype: int64
y_train = shape: (25000, 1) dtype: int64
x = tf.placeholder(tf.float32, shape = [None, 300])
y = tf.placeholder(tf.float32, shape = [None, 2])
# Input -> Layer 1
W1 = tf.Variable(tf.zeros([300, 2]))
b1 = tf.Variable(tf.zeros([2]))
#h1 = tf.nn.sigmoid(tf.matmul(x, W1) + b1)
# Calculating difference between label and output
pred = tf.nn.softmax(tf.matmul(x, W1) + b1)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y)) …Run Code Online (Sandbox Code Playgroud) 我现在正在尝试为基于LSTM的NN准备输入数据.我有一些大量的文本文档,我想要的是为每个文档制作序列向量,以便我能够将它们作为列车数据提供给LSTM RNN.
我糟糕的做法:
import re
import numpy as np
#raw data
train_docs = ['this is text number one', 'another text that i have']
#put all docs together
train_data = ''
for val in train_docs:
train_data += ' ' + val
tokens = np.unique(re.findall('[a-z?-?0-9]+', train_data.lower()))
voc = {v: k for k, v in dict(enumerate(tokens)).items()}
Run Code Online (Sandbox Code Playgroud)
然后brutforce用"voc"词典替换每个doc.
有没有可以帮助完成这项任务的库?
看完这篇文章后,我开始训练自己的模型.问题是,作者没有说清楚的东西sentences中 Word2Vec应该是这样的.
我从维基百科页面下载文本,因为它写的是文章,我从中列出了句子:
sentences = [word for word in wikipage.content.split('.')]
Run Code Online (Sandbox Code Playgroud)
所以,例如,sentences[0]看起来像:
'Machine learning is the subfield of computer science that gives computers the ability to learn without being explicitly programmed'
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用此列表训练模型:
model = Word2Vec(sentences, min_count=2, size=50, window=10, workers=4)
Run Code Online (Sandbox Code Playgroud)
但该模型的字典由字母组成!例如,输出model.wv.vocab.keys()是:
dict_keys([',', 'q', 'D', 'B', 'p', 't', 'o', '(', ')', '0', 'V', ':', 'j', 's', 'R', '{', 'g', '-', 'y', 'c', '9', 'I', '}', '1', 'M', ';', '`', '\n', 'i', 'r', 'a', 'm', …Run Code Online (Sandbox Code Playgroud) 我正在运行下面的代码,但gensim word2vec正在抛出一个词而不是词汇错误.你能让我知道解决方案吗?
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = [["The quick brown fox jumped over the lazy dog"],
["The sun is shining bright"]]
from gensim.models import word2vec
model = word2vec.Word2Vec(sentences, iter=10, min_count=1, size=300, workers=4)
print(model['quick'])
Run Code Online (Sandbox Code Playgroud)
输出:
KeyError: "word 'quick' not in vocabulary"
Run Code Online (Sandbox Code Playgroud)
但如果我用这个
print(model['The quick brown fox jumped over the lazy dog'])
Run Code Online (Sandbox Code Playgroud)
它打印一个列表
[ 1.60348183e-03 -9.17983416e-04 -8.30831763e-04 9.46367683e-04
Run Code Online (Sandbox Code Playgroud) 我已经训练了400万条记录的doc2vec模型.我想从我的数据中找到一个新句子,但是我的结果非常糟糕.
数据样本:
Xolo Era (Black, 8 GB)(1 GB RAM).
Sugar C6 (White, 16 GB)(2 GB RAM).
Celkon Star 4G+ (Black & Dark Blue, 4 GB)(512 MB RAM).
Panasonic Eluga I2 (Metallic Grey, 16 GB)(2 GB RAM).
Itel IT 5311(Champagne Gold).
Itel A44 Pro (Champagne, 16 GB)(2 GB RAM).
Nokia 2 (Pewter/ Black, 8 GB)(1 GB RAM).
InFocus Snap 4 (Midnight Black, 64 GB)(4 GB RAM).
Panasonic P91 (Black, 16 GB)(1 GB RAM).
Run Code Online (Sandbox Code Playgroud)
在传递这些数据之前,我已经完成了预处理,包括1)停止删除单词.2)特殊字符和数值删除.3)小写数据.我也在测试过程中执行了相同的步骤.
我用于培训的代码:
sentences=doc2vec.TaggedLineDocument('training_data.csv') # i have used TaggedLineDocument …Run Code Online (Sandbox Code Playgroud) word2vec ×10
python ×9
gensim ×7
nlp ×4
python-3.x ×2
algorithm ×1
doc2vec ×1
lstm ×1
tensorflow ×1
tokenize ×1