多输入CNN评分预测函数运行报错:'list'对象不可调用排查
错误原因&解决办法
首先看你遇到的 TypeError: 'list' object is not callable,这个问题直接出在 preprocessing 函数的最后一行代码里:words=stems, lemmas(words)。
具体问题点:
- 变量未定义+误用:
stems和lemmas这两个变量在preprocessing函数内部根本没定义过,你可能是把函数外的代码逻辑搞错了位置。而且你把lemmas当成函数去调用lemmas(words)——但lemmas其实是stem_and_lemmatize返回的列表,列表当然不能当函数用,这就是报错的核心原因。 - 逻辑混乱:你先执行了
words= stem_and_lemmatize(words),这已经把words赋值成了包含(stems, lemmas)的元组,结果紧接着又写了一行完全没意义的赋值代码,逻辑完全乱了。
另外,你在函数外写的stems, lemmas = stem_and_lemmatize(words)这行也没用,words在这里没定义,属于无效代码。
修复方案
根据你的需求(应该是想完成文本的词干提取+词形还原处理),我们把 preprocessing 函数的逻辑理顺:
方案1:选择其中一种处理结果返回(比如词形还原)
如果你只需要词干或者词形还原后的结果,直接返回对应的列表就行:
def preprocessing(words): words = remove_non_ascii(words) words = to_lowercase(words) words = remove_punctuation(words) words = remove_stopwords(words) # 直接获取stem_and_lemmatize返回的两个结果 stems, lemmas = stem_and_lemmatize(words) # 根据你的需求选一个返回,这里选lemmas为例 return lemmas
方案2:合并两种处理结果(如果需要同时保留)
要是想把词干和词形还原的结果合并,就这么写:
def preprocessing(words): words = remove_non_ascii(words) words = to_lowercase(words) words = remove_punctuation(words) words = remove_stopwords(words) stems, lemmas = stem_and_lemmatize(words) # 合并两个列表,可选去重避免重复内容 combined_words = stems + lemmas combined_words = list(set(combined_words)) # 去重步骤可选 return combined_words
额外要修正的小问题
prediction_rate函数里有个拼写错误:你定义的是comment1和comment2,但调用predict的时候写的是commentaire1和commentaire2,这个会触发NameError,得改过来。- 你的
Switcher字典完全没必要,直接格式化输出就行,代码更简洁。
修正后的完整代码片段
def preprocessing(words): words = remove_non_ascii(words) words = to_lowercase(words) words = remove_punctuation(words) words = remove_stopwords(words) stems, lemmas = stem_and_lemmatize(words) return lemmas # 按需替换成stems或者combined_words def encoding(text): text = clean_str(text) text = preprocessing(text) vocabulary,vocabulary_inv = build_vocab(text) text = pad_sentences(text,100) x_users = np.array([vocabulary[word] for word in text]) x_test = sequence.pad_sequences(x_users, maxlen=100) return x_test def prediction_rate(model_name): print("welcome ! \nplease enter the first text ! : ") ID1 = input() print("please enter the second text ! : ") rev = input() comment1=encoding(ID1) comment2=encoding(rev) # 修正拼写错误 y=model_name.predict([comment1,comment2]) c = np.argmax(y) # 简化输出逻辑 print(f'Satisfaction Percentage : {:.1f} %'.format( (y[0][c]/5)*100))
内容的提问来源于stack exchange,提问作者Amine
相关产品推荐
相关产品推荐

