我在使用Jupyter Notebook尝试编写一个使用来自Kaggle的讽刺数据集的讽刺检测模型。我已经将数据集下载到我的电脑上,并将其修改为字典列表。每个字典包含三个键:article_link、is_sarcastic和headline。
我的代码如下,出现了以下错误:
TypeError Traceback (most recent call last) in 7 tokenizer.fit_on_texts(sentences)8—-> 9 my_word_index=tokenizer.word_index()1011 print(len(word_index))
TypeError: ‘dict’对象不可调用
import osimport pandasos.getcwd()import jsonos.chdir('C:/Users/IMALSHA/Desktop/AI content writing/Cousera Deep Neural Networks course/NLP lectures')#加载数据 with open('Sarcasm_Headlines_Dataset.json','r') as json_file: data_set=json.load(json_file)#定义列表sentences=[]labels=[]urls=[]for item in data_set: sentences.append(item['headline']) labels.append(item['is_sarcastic']) urls.append(item['article_link'])import tensorflow as tffrom tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.preprocessing.sequence import pad_sequencestokenizer=Tokenizer(oov_token="<oov>")tokenizer.fit_on_texts(sentences)word_index=tokenizer.word_index()print(len(word_index))print(word_index)sequences=tokenizer.texts_to_sequences(sentences)paded=pad_sequences(sequences)print(paded[2])
回答:
问题出在以下代码:
word_index=tokenizer.word_index()
可能您的意图是将tokenizer的word_index存储到word_index变量中。然而,您却像调用方法/函数一样调用了tokenizer.word_index,但它实际上是一个字典。
因此,我认为您需要进行以下修正:
word_index=tokenizer.word_index