You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

推文情感分析遇KeyError报错,如何处理词嵌入未收录词汇?

解决推文情感分析中未收录词汇导致的KeyError问题

方案1:过滤未收录词汇

直接筛选出存在于embeddings索引中的词汇,避免触发KeyError,仅用已知词汇计算情感得分。修改words_sentiment函数如下:

def words_sentiment(words):
    # 筛选embeddings中存在的词汇
    valid_words = [word for word in words if word in embeddings.index]
    if not valid_words:
        # 无有效词汇时返回中性得分(0)
        return pd.DataFrame({'sentiment': [0]}, index=['neutral'])
    vecs = embeddings.loc[valid_words].dropna()
    log_odds = vector_sentiment(vecs)
    return pd.DataFrame({'sentiment': log_odds}, index=vecs.index)

方案2:为未收录词汇分配默认向量

如果不想丢弃未收录词,可为其分配中性向量(如全0向量),确保所有词汇都参与情感计算:

import numpy as np

def words_sentiment(words):
    valid_words = [word for word in words if word in embeddings.index]
    invalid_words = [word for word in words if word not in embeddings.index]
    
    # 处理有效词汇
    vecs = embeddings.loc[valid_words].dropna()
    log_odds = vector_sentiment(vecs)
    sentiment_df = pd.DataFrame({'sentiment': log_odds}, index=vecs.index)
    
    # 为无效词汇添加中性得分(0)
    if invalid_words:
        invalid_df = pd.DataFrame({'sentiment': [0]*len(invalid_words)}, index=invalid_words)
        sentiment_df = pd.concat([sentiment_df, invalid_df])
    
    return sentiment_df

方案3:优化词汇预处理

通过词形还原、词干提取或网络用语标准化,减少未收录词的数量:

from nltk.stem import WordNetLemmatizer
import re

lemmatizer = WordNetLemmatizer()
# 标准化网络用语(如重复字符压缩)
def normalize_word(word):
    # 把重复3次及以上的字母压缩为2次(如'dooooope'→'dope')
    word = re.sub(r'(.)\1{2,}', r'\1\1', word)
    # 词形还原
    return lemmatizer.lemmatize(word)

# 修改text_sentiment中的token处理逻辑
def text_sentiment(text):
    tokens = [normalize_word(token.casefold()) for token in TOKEN_RE.findall(text)]
    sentiments = words_sentiment(tokens)
    return sentiments['sentiment'].mean()

内容的提问来源于stack exchange,提问作者Shehzadi Aziz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 01:54:25