NLP基础:文本的向量表示

本文深入探讨了自然语言处理中的文本向量表示方法,包括词袋模型和TF-IDF。通过sklearn库与手动计算进行比较,强调实践操作的重要性。同时指出TF-IDF计算公式与《统计学习方法》中的差异,以及高维问题对文本表示的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 词袋模型

1.1 利用sklearn函数

import numpy as np
from collections import Counter
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
corpus = [
     'He is going from Beijing to Shanghai.',
     'He denied my request, but he actually lied.',
     'Mike lost the phone, and phone was in the car.',
]
X = vectorizer.fit_transform(corpus)
print("文本的向量表示:Bag of Words")
print("sklearn函数输出:")
print(X.toarray())

1.2 手动计算

Y = []
word_voc = ['actually', 'and', 'beijing', 'but', 'car', 'denied', 'from', 'going', 'he', 'in', 'is', 'lied', 'lost', 'mike', 'my', 'phone', 'request', 'shanghai', 'the', 'to', 'was']

for sentence_ in corpus:
    sentence = []
    for x in sentence_[:-1].replace(',', '').split():
        sentence.append(x.lower())
    vector = [0]*len(word_voc)
    for word_index in range(len(word_voc)):
        word = word_voc[word_index]
        vector[word_index] = Counter(sentence)[word]
    Y.append(vector)
Y = np.array(Y)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值