gpt4 book ai didi

python - 从数据框中提取文本特征

转载 作者:行者123 更新时间:2023-12-01 08:49:57 25 4
gpt4 key购买 nike

我有一个带有两个文本字段的数据框和其他功能,例如这种格式:

 message            feature_1      feature_2       score        text
'This is the text' 4 7 10 extra text
'This is more text' 3 2 8 and this is another text

现在我的目标是预测分数,当尝试将此数据帧转换为特征矩阵以将其输入到我的机器学习模型时,这是我所做的:

    # Create vectorizer for function to use
vectorizer = TfidfVectorizer()
# combine the numerical features with the TFIDF generated matrix
X = sp.sparse.hstack( (vectorizer.fit_transform(df.message),
df[['feature_1', 'feature_2']].values, vectorizer.fit_transform(df.text)),
format='csr')

现在,当打印 X 矩阵的形状时,我得到了 2x13,但是当我像这样检查 X_columsn 时:

X_columns = vectorizer.get_feature_names() + df[['feature_1', 'feature_2']].columns.tolist()

我没有得到语料库中的所有单词,它只给我带来了df.text中存在的单词和其他特征属性,而没有df.message中的单词.

['and', 'another', 'extra', 'is', 'text', 'this', 'feature_1', 'feature_2']

如何使 X 包含我所有的数据框功能!!

最佳答案

作为一般规则,将矢量化器适合整个文本语料库以计算词汇量,然后将所有文本转换为矢量。

您要拟合矢量化器两次,因此第二次调用 fit_transform 会覆盖第一次调用并相应地更新词汇表。首先尝试拟合两个文本字段以计算整个语料库的词汇量,然后转换每个文本字段,如下所示:

from sklearn.feature_extraction.text import TfidfVectorizer
import scipy as sp

vectorizer = TfidfVectorizer()
vectorizer.fit(df.message.append(df.text))
X = sp.sparse.hstack( (vectorizer.transform(df.message),
df[['feature_1', 'feature_2']].values, vectorizer.transform(df.text)),
format='csr')

X_columns = vectorizer.get_feature_names() + df[['feature_1', 'feature_2']].columns.tolist()

这给了我:

X_columns
Out[51]: ['and', 'another', 'extra', 'is', 'more', 'text', 'the', 'this', 'feature_1', 'feature_2']

这就是你所追求的吗?

关于python - 从数据框中提取文本特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com