如何修复 DeprecationWarning: Call to deprecated error

问题描述

在使用 Word2Vec 时,我遇到了这样的错误

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: DeprecationWarning: Call to deprecated __getitem__ (Method将在4.0.0中移除,使用self.wv。getitem() 代替)。 这与 ipykernel 包是分开的,因此我们可以避免在

之前进行导入

为什么我会收到这个错误,我该如何解决

import nltk
nltk.download('punkt')
sentences=sent_tokenize(text)
sentences
nltk.download('stopwords')
sentences_clean=[re.sub(r'[^\w\s]','',sentence.lower()) for sentence in sentences] #noktalama kaldır,küçült 
stop_words = stopwords.words('english')
sentence_tokens=[[words for words in sentence.split(' ') if words not in stop_words] for sentence in sentences_clean] #stop_words'leri kaldır.
sentence_tokens
#SÖZCÜK YERLEŞTİRME
w2v=Word2Vec(sentence_tokens,size=1,min_count=1,iter=1000)
sentence_embeddings=[[w2v[word][0] for word in words] for words in sentence_tokens]
max_len=max([len(tokens) for tokens in sentence_tokens]) #Bir cümlenin max uzunluğunu hesaplama
sentence_embeddings=[np.pad(embedding,(0,max_len-len(embedding)),'constant') for embedding in sentence_embeddings] #Padding işlemi.Bütün cümleleri aynı boyuta getirebilmke için yaplır
#print(sentence_embeddings) #Kelimelerin vektör uzayındaki halleri bulunur 

解决方法

通常,您应该在问题中提供完整的错误消息以及调用堆栈(“回溯”)信息,以帮助准确突出显示哪一行代码触发了错误。

但是,我相信您的错误是由使用 w2v[word] 的代码部分触发的。

A DeprecationWarning 通常表示由于库代码设计的变化,不再推荐您的使用。虽然出现“弃用”警告,但代码可能仍然有效,但在以后的版本中可能会停止工作。

就您的代码而言,在您使用的 Gensim 版本中,不再建议通过 {{1} 上的直接索引访问([…]-下标)访问词向量}} 模型对象本身。相反,这些词向量现在收集在 Word2Vec 类型的附属对象中,该对象保存在 KeyedVectors 对象的 Word2Vec 属性中。

因此,将 .wv 替换为 w2v[word] 应该可以避免出现警告。 (而且,从 w2v.wv[word] 及更高版本开始,可能需要代码才能正常工作。)