我正在尝试使用 Word2Vec 和 TF-IDF 评分对包含 160 万条推文的数据集进行基本的推文情感分析,但我的 6 GB 内存的 Nvidia 显卡无法完成此任务。由于这是我第一个涉及机器学习的实践项目,我在想我做错了什么,因为数据集全部是文本,不应该占用这么多的内存,这导致我的笔记本电脑在 tweet2vec 函数中冻结,或者在缩放部分出现内存错误。下面是我代码的一部分,所有问题都出现在这里。最后一点是,我尝试过处理多达 100 万条数据,它可以工作!所以我想知道是什么导致了这个问题
# --------------- 计算单词权重以便稍后在 Word2Vec 模型中使用,并将单词聚合 ---------------
def word_weight(data):
vectorizer = TfidfVectorizer(sublinear_tf=True, use_idf=True)
d = dict()
for index in tqdm(data, total=len(data), desc='为单词分配权重'):
# --------- try except 缓存空索引 ----------
try:
matrix = vectorizer.fit_transform([w for w in index])
tfidf = dict(zip(vectorizer.get_feature_names(), vectorizer.idf_))
d.update(tfidf)
except ValueError:
continue
print("每个单词现在都有权重\n"
"--------------------------------------")
return d
# ------------------- 将带权重的词元重新组合成推文 ----------------
def tweet2vec(tokens, size, tfidf):
count = 0
for index in tqdm(tokens, total=len(tokens), desc='创建句子向量'):
# ---------- size 是 Word2Vec 模型的维度 (200) ---------------
vec = np.zeros(size)
for word in index:
try:
vec += model[word] * tfidf[word]
except KeyError:
continue
tokens[count] = vec.tolist()
count += 1
print("推文向量已准备好进行机器学习算法的缩放\n"
"-------------------------------------------------")
return tokens
dataset = read_dataset('training.csv', ['target', 't_id', 'created_at', 'query', 'user', 'text'])
dataset = delete_unwanted_col(dataset, ['t_id', 'created_at', 'query', 'user'])
dataset_token = [pre_process(t) for t in tqdm(map(lambda t: t, dataset['text']),
desc='清理文本', total=len(dataset['text']))]
print('预处理完成,返回推文词元列表\n'
'--------------------------------------------------------')
X = np.array(tweet2vec(dataset_token, 200, word_weight(dataset_token)))
print('缩放向量 ...')
X_scaled = scale(X)
print('特征已缩放!')
传递给 word_weight 函数的数据是一个形状为 (1599999, 200) 的列表,每个索引由预处理的推文词元组成。提前感谢您的宝贵时间和回答,当然,我也乐于听到处理大数据集的更好方法
回答:
当我将代码(tweet2vec 函数)更改为以下内容时,我的 problema 得到了解决(w 是单词权重)
def tweet2vec(tokens, size, tfidf):
# ------------- size 是 Word2Vec 模型的维度 (200) ---------------
vec = np.zeros(size).reshape(1, size)
count = 0
for word in tokens:
try:
vec += model[word] * tfidf[word]
count += 1
except KeyError:
continue
if count != 0:
vec /= count
return vec
X = np.concatenate([tweet2vec(token, 200, w) for token in tqdm(map(lambda token: token, dataset_token),
desc='创建推文向量',
total=len(dataset_token))]
)
我不知道为什么!!!