sklearn 用於文本分類__演算法

來源:互聯網
上載者:User

文本挖掘的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])*

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.