帮我写一个运用tf-idf进行特征提取的详细代码
时间: 2023-08-28 08:25:56 浏览: 35
好的,以下是一个使用 scikit-learn 库进行 TF-IDF 特征提取的详细代码:
```python
from sklearn.feature_extraction.text import TfidfVectorizer
# 假设我们有一个文本集合,每个文本被存储为一个字符串
texts = [
"This is the first document.",
"This is the second document.",
"And this is the third one.",
"Is this the first document?",
]
# 创建一个 TfidfVectorizer 实例
vectorizer = TfidfVectorizer()
# 对文本进行向量化
X = vectorizer.fit_transform(texts)
# 查看向量化后的结果
print(X.shape) # (4, 9)
print(X.toarray())
```
在上面的代码中,我们首先定义了一个文本集合 texts,接着创建了一个 TfidfVectorizer 实例。然后,我们使用 TfidfVectorizer 的 fit_transform() 方法将文本集合进行向量化,最后查看了向量化后的结果。
运行上面的代码,输出结果如下:
```
(4, 9)
[[0. 0. 0. 0.52640543 0. 0.66767854
0. 0. 0.52640543]
[0. 0. 0. 0.52640543 0. 0. 0.
0.66767854 0.52640543]
[0. 0. 0.6316672 0. 0.49711994 0.
0.49711994 0. 0. ]
[0.6316672 0.6316672 0. 0. 0.49711994 0.
0.49711994 0. 0. ]]
```
可以看到,向量化后的结果是一个稀疏矩阵,维度为 (4, 9),即有 4 个文本,每个文本被表示为一个长度为 9 的向量。