文本挖掘的paper沒找到統一的benchmark,只好自己跑程式,走過路過的前輩如果知道20newsgroups或者其它好用的公用資料集的分類(最好要所有類分類結果,全部或取部分特徵無所謂)麻煩留言告知下現在的benchmark,萬謝。
嗯,說本文。20newsgroups官網上給出了3個資料集,這裡我們用最原始的20news-19997.tar.gz。
分為以下幾個過程:
載入資料集 提feature 分類 Naive Bayes KNN SVM 聚類 說明: scipy官網 上有參考,但是看著有點亂,而且有bug。本文中我們分塊來看。
Environment: Python 2.7 + Scipy (scikit-learn)
1.載入資料集
從20news-19997.tar.gz下載資料集,解壓到scikit_learn_data檔案夾下,載入資料,詳見code注釋。 [python] view plain copy #first extract the 20 news_group dataset to /scikit_learn_data from sklearn.datasets import fetch_20newsgroups #all categories #newsgroup_train = fetch_20newsgroups(subset='train') #part categories categories = ['comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x']; newsgroup_train = fetch_20newsgroups(subset = 'train',categories = categories);
可以檢驗是否load好了: [python] view plain copy #print category names from pprint import pprint pprint(list(newsgroup_train.target_names))
結果: ['comp.graphics',
'comp.os.ms-windows.misc',
'comp.sys.ibm.pc.hardware',
'comp.sys.mac.hardware',
'comp.windows.x']
2. 提feature: 剛才load進來的newsgroup_train就是一篇篇document,我們要從中提取feature,即詞頻啊神馬的,用fit_transform
Method 1. HashingVectorizer,規定feature個數
[python] view plain copy #newsgroup_train.data is the original documents, but we need to extract the #feature vectors inorder to model the text data from sklearn.feature_extraction.text import HashingVectorizer vectorizer = HashingVectorizer(stop_words = 'english',non_negative = True, n_features = 10000) fea_train = vectorizer.fit_transform(newsgroup_train.data) fea_test = vectorizer.fit_transform(newsgroups_test.data); #return feature vector 'fea_train' [n_samples,n_features] print 'Size of fea_train:' + repr(fea_train.shape) print 'Size of fea_train:' + repr(fea_test.shape) #11314 documents, 130107 vectors for all categories print 'The average feature sparsity is {0:.3f}%'.format( fea_train.nnz/float(fea_train.shape[0]*fea_train.shape[1])*