6 GB RAM无法使用Word2Vec对文本进行矢量化

问题描述

我正在尝试使用word2vec和tfidf-score对包含1,6M条推文的数据集进行一种基本的推文情感分析,但是我的6 GB Gforce-Nvidia无法做到这一点。因为这是我的第一个与机器学习有关的实践项目,所以我想知道我做错了什么,因为数据集是全部文本,因此不应该占用太多RAM,这会使我的笔记本电脑陷入tweet2vec函数的冻结状态,或者在扩展部分时出现内存错误。以下是我的代码的一部分,一切都会崩溃。 最后一件事是,我尝试使用了多达1M的数据,并且该方法有效!所以我很好奇是什么原因造成的

# --------------- calculating word weight for using later in word2vec model & bringing words together ---------------
def word_weight(data):
    vectorizer = TfidfVectorizer(sublinear_tf=True,use_idf=True)
    d = dict()
    for index in tqdm(data,total=len(data),desc='Assigning weight to words'):
        # --------- try except caches the empty indexes ----------
        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("every word has weight Now\n"
          "--------------------------------------")
    return d


# ------------------- bringing tokens with weight to recreate tweets ----------------
def tweet2vec(tokens,size,tfidf):
    count = 0
    for index in tqdm(tokens,total=len(tokens),desc='creating sentence vectors'):
        # ---------- size is the dimension of word2vec model (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("tweet vectors are ready for scaling for ML algorithm\n"
          "-------------------------------------------------")
    return tokens


dataset = read_dataset('training.csv',['target','t_id','created_at','query','user','text'])
dataset = delete_unwanted_col(dataset,['t_id','user'])
dataset_token = [pre_process(t) for t in tqdm(map(lambda t: t,dataset['text']),desc='cleaning text',total=len(dataset['text']))]

print('pre_process completed,list of tweet tokens is returned\n'
      '--------------------------------------------------------')
X = np.array(tweet2vec(dataset_token,200,word_weight(dataset_token)))
print('scaling vectors ...')
X_scaled = scale(X)
print('features scaled!')

给word_weight函数的数据是一个(1599999,200)形列表,每个索引由预处理的tweet令牌组成。 感谢您的时间和事先的答复,当然,我很高兴听到更好的方法来处理大型数据集

解决方法

如果我理解正确,那么它可用于1M条推文,但无法用于160万条推文?这样您就知道代码是正确的。

如果在您认为不应的情况下GPU内存不足,则它可能会在上一个进程中继续运行。使用nvidia-smi检查正在使用GPU的进程以及多少内存。如果(在运行代码之前)发现那里有大块Python进程,则可能是崩溃的进程,或者Jupyter窗口仍然打开,等等。

我发现watch nvidia-smi(不确定是否有Windows窗口)很有用,以查看GPU内存如何随着训练的进行而变化。通常,一开始会保留一个块,然后保持相当恒定。如果您看到它呈线性上升,则代码可能有问题(您是否在每次迭代时重新加载模型,是这样?)。

,

当我将代码(tweet2vec函数)更改为此时,我的问题已解决 (w是字重)

def tweet2vec(tokens,size,tfidf):
    # ------------- size is the dimension of word2vec model (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='creating tweet vectors',total=len(dataset_token))]

我不知道为什么!!!!