neg: shit. waste my money. waste of money. sb movie. waste of time. a shit movie. pos: nb! nb movie! nb! worth my money. I love this movie! a nb movie. worth it!
# -*- coding: utf-8 -*- import scipy as sp import numpy as np from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer '''''加载数据集,切分数据集80%训练,20%测试''' movie_reviews = load_files('endata') doc_terms_train, doc_terms_test, y_train, y_test\ = train_test_split(movie_reviews.data, movie_reviews.target, test_size = 0.3) '''''BOOL型特征下的向量空间模型,注意,测试样本调用的是transform接口''' count_vec = TfidfVectorizer(binary = False, decode_error = 'ignore',\ stop_words = 'english') x_train = count_vec.fit_transform(doc_terms_train) x_test = count_vec.transform(doc_terms_test) x = count_vec.transform(movie_reviews.data) y = movie_reviews.target print(doc_terms_train) print(count_vec.get_feature_names()) print(x_train.toarray()) print(movie_reviews.target)
运行结果如下:
[b'waste of time.', b'a shit movie.', b'a nb movie.', b'I love this movie!', b'shit.', b'worth my money.', b'sb movie.', b'worth it!']
['love', 'money', 'movie', 'nb', 'sb', 'shit', 'time', 'waste', 'worth']
[[ 0. 0. 0. 0. 0. 0. 0.70710678 0.70710678 0. ]
[ 0. 0. 0.60335753 0. 0. 0.79747081 0. 0. 0. ]
[ 0. 0. 0.53550237 0.84453372 0. 0. 0. 0. 0. ]
[ 0.84453372 0. 0.53550237 0. 0. 0. 0. 0. 0. ]
[ 0. 0. 0. 0. 0. 1. 0. 0. 0. ]
[ 0. 0.76642984 0. 0. 0. 0. 0. 0. 0.64232803]
[ 0. 0. 0.53550237 0. 0.84453372 0. 0. 0. 0. ]
[ 0. 0. 0. 0. 0. 0. 0. 0. 1. ]]
[1 1 0 1 0 1 0 1 1 0 0 0]
python 输出的比较混乱。我这里做了一个表格如下:
从上表可以发现如下几点:
1、停用词的过滤。
初始化count_vec的时候,我们在count_vec构造时传递了stop_words = 'english',表示使用默认的英文停用词。可以使用count_vec.get_stop_words()查看TfidfVectorizer内置的所有停用词。当然,在这里可以传递你自己的停用词list(比如这里的“movie”)
2、TF-IDF的计算。
这里词频的计算使用的是sklearn的TfidfVectorizer。这个类继承于CountVectorizer,在后者基本的词频统计基础上增加了如TF-IDF之类的功能。
我们会发现这里计算的结果跟我们之前计算不太一样。因为这里count_vec构造时默认传递了max_df=1,因此TF-IDF都做了规格化处理,以便将所有值约束在[0,1]之间。
3、count_vec.fit_transform的结果是一个巨大的矩阵。我们可以看到上表中有大量的0,因此sklearn在内部实现上使用了稀疏矩阵。本例子数据较小。如果读者有兴趣,可以试试机器学习科研工作者使用的真实数据,来自康奈尔大学:http://HdhCmsTestcs.cornell.edu/people/pabo/movie-review-data/。这个网站提供了很多数据集,其中有几个2M左右的数据库,正反例700个左右。这样的数据规模也不算大,1分钟内还是可以跑完的,建议大家试一试。不过要注意这些数据集可能存在非法字符问题。所以在构造count_vec时,传入了decode_error = 'ignore',以忽略这些非法字符。
上表的结果,就是训练8个样本的8个特征的一个结果。这个结果就可以使用各种分类算法进行分类了。
相关推荐:
分享Python文本生成二维码实例
Python文本相似性计算之编辑距离详解
实例详解Python实现简单网页图片抓取
以上就是Python文本特征抽取与向量化算法学习实例详解的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于Python文本特征抽取与向量化算法学习实例详解的详细内容...