在 Twitter 航空情感数据上应用 TfIdf
现在,您将使用 TfIdf 方法构建特征。我们将继续使用 tweets 数据集。
在本练习中,您将运用前面课程中学到的内容:移除停用词、使用给定的分词模式,并指定 n-grams。
最终输出将是一个 DataFrame,其中的列由 TfidfVectorizer() 生成。这样的 DataFrame 可以直接传入到有监督学习模型中,我们将在下一章中处理这一点。
本练习是课程的一部分
Python 中的情感分析
练习说明
- 导入构建 TfidfVectorizer 所需的包以及
ENGLISH_STOP_WORDS。 - 基于
tweets数据集的text列构建一个 TfIdf 矢量化器:将 n-grams 指定为 uni- 和 bi-grams,使用给定的分词模式仅包含字母数字字符的 token,并将停用词设为ENGLISH_STOP_WORDS。 - 对同一列进行转换,调用矢量化器的 transform,确保与拟合时的列一致。
- 在
DataFrame()函数中指定列名。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the required vectorizer package and stop words list
____
# Define the vectorizer and specify the arguments
my_pattern = r'\b[^\d\W][^\d\W]+\b'
vect = ____(____=(1, 2), max_features=100, ____=my_pattern, ____=ENGLISH_STOP_WORDS).fit(tweets.text)
# Transform the vectorizer
X_txt = vect.____(____.____)
# Transform to a data frame and specify the column names
X=pd.DataFrame(X_txt.toarray(), columns=____.____)
print('Top 5 rows of the DataFrame: ', X.head())