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

亚马逊数据集情感分类建模报错:TF-IDF句分词及RFE适配问题

问题解决:情感分类模型的TF-IDF与RFE报错修复

错误核心原因

  1. TF-IDF配置不符合需求:默认的TfidfVectorizer会把句子拆分成单个单词,无法实现「以完整句子为单位」的分词要求。
  2. 特征存储错误:把TF-IDF输出的csr_matrix直接塞进DataFrame的一列,导致该列每个元素都是矩阵对象,而非数值型特征。RFE(递归特征消除)要求输入的特征矩阵是纯数值的二维结构,这种嵌套矩阵会触发类型错误。

修正后的完整代码

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import RFE
from sklearn.preprocessing import OneHotEncoder

# 读取数据集(假设已加载amazon数据)
# amazon = pd.read_csv("your_dataset.csv")

# 1. 定义特征与目标变量
Z = amazon["Product_Description"]
Y = amazon["Sentiment"]
product_type = amazon["Product_Type"]

# 2. 配置TF-IDF:以完整句子为单位生成特征
# tokenizer=lambda x: [x] 强制将整个句子作为单个token
tfidf = TfidfVectorizer(tokenizer=lambda x: [x], lowercase=False)
tfidf_matrix = tfidf.fit_transform(Z)

# 3. 将TF-IDF结果转为DataFrame,合并类别特征
tfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns=tfidf.get_feature_names_out())
# 处理Product_Type:类别特征转数值编码
type_encoder = OneHotEncoder(sparse_output=False, drop='first')
type_encoded = type_encoder.fit_transform(product_type.values.reshape(-1, 1))
type_df = pd.DataFrame(type_encoded, columns=type_encoder.get_feature_names_out())

# 合并所有特征
X = pd.concat([tfidf_df, type_df], axis=1)

# 4. 划分训练集与测试集
test_size = 0.2
seed = 45
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)

# 5. 构建RFE与分类模型
model = LogisticRegression(max_iter=500)
# 注意:若用整句TF-IDF,特征数量等于唯一句子数,n_features_to_select=2需按需调整
rfe = RFE(model, n_features_to_select=2)
fit = rfe.fit(X_train, Y_train)

# 查看结果
print(f"保留特征数量: {fit.n_features_}")
print(f"特征支持状态: {fit.support_}")
print(f"特征排名: {fit.ranking_}")

关键修改说明

  • TF-IDF调整:通过tokenizer=lambda x: [x]实现「整句为单位」的分词,让每个完整句子作为独立特征参与TF-IDF计算。
  • 特征格式修正:将TF-IDF稀疏矩阵转为标准DataFrame,同时把类别特征Product_Type编码为数值型,确保整个特征矩阵是纯数值二维结构。
  • 避免数据泄露:用训练集拟合RFE,而非全量数据,符合机器学习流程规范。

内容的提问来源于stack exchange,提问作者Pankti Satra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:50:41