文本型特征提取

1. hash結(jié)構(gòu)

from sklearn.feature_extraction import DictVectorizer

    measurements = [

    {'city':'dubai', 'temperature':33}, {'city':'London', 'temperature':12}, ,{'city':'San Fransisco', 'temperature':18}

]
vec = DictVectorizer()
vec.fit_transform(measurements).toarray()

# output
array([[ 0.,  0.,  1., 33.],
       [ 1.,  0.,  0., 12.],
       [ 0.,  1.,  0., 18.]])

vec.get_feature_names()
>>> ['city=London', 'city=San Fransisco', 'city=dubai', 'temperature']

2. 詞袋模型

from sklearn.feature_extraction.text import CountVectorizer

vectorizer=CountVectorizer(min_df=1) # 至少出現(xiàn)一次
vectorizer

>>> CountVectorizer(analyzer='word', binary=False, decode_error='strict',
        dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
        lowercase=True, max_df=1.0, max_features=None, min_df=1,
        ngram_range=(1, 1), preprocessor=None, stop_words=None,
        strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',
        tokenizer=None, vocabulary=None)

corpus = [
    'This is the first document.',
     'This is the second second document.',
     'And the third one.',
     'Is this the first document?',
]
X=vectorizer.fit_transform(corpus)
X

>>> <4x9 sparse matrix of type '<class 'numpy.int64'>'
    with 19 stored elements in Compressed Sparse Row format>


vectorizer.get_feature_names()
>>> ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']

X.toarray()
>>> array([[0, 1, 1, 1, 0, 0, 1, 0, 1],
                 [0, 1, 0, 1, 0, 2, 1, 0, 1],
                 [1, 0, 0, 0, 1, 0, 1, 1, 0],
                 [0, 1, 1, 1, 0, 0, 1, 0, 1]], dtype=int64)

描述的文檔會完全忽略文檔中單詞的相對位置

analyze("This is a text document to analyze.")
>>> ['this', 'is', 'text', 'document', 'to', 'analyze']

為了保留一些有序的信息经宏,我們可以抽取2-grams的詞匯掌测,而非使用1-grams:

bigram_vectorizer=CountVectorizer(ngram_range=(1,2), token_pattern=r'\b\w+\b', min_df=1)
analyze=bigram_vectorizer.build_analyzer()
analyze('Bi-grams are cool!')

>>> ['bi', 'grams', 'are', 'cool', 'bi grams', 'grams are', 'are cool']

通過該vectorizer抽取的詞匯表潮改,比之前的方式更大止剖,可以以local positioning patterns進行模糊編碼:
X_2 = bigram_vectorizer.fit_transform(corpus).toarray()
X_2
>>> array([[0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0],
                 [0, 0, 1, 0, 0, 1, 1, 0, 0, 2, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0],
                 [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0],
                 [0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1]],
      dtype=int64)

bigram_vectorizer.get_feature_names()

>>> ['and',
 'and the',
 'document',
 'first',
 'first document',
 'is',
 'is the',
 'is this',
 'one',
 'second',
 'second document',
 'second second',
 'the',
 'the first',
 'the second',
 'the third',
 'third',
 'third one',
 'this',
 'this is',
 'this the']

3. TF-IDF item weight

tf表示詞頻(term-frequency)媚值,idf表示inverse document-frequency 红省,tf–idf 表示tf * idf。它原先適用于信息檢索(搜索引擎的ranking)晶疼,同時也發(fā)現(xiàn)在文檔分類和聚類上也很好用酒贬。

from sklearn.feature_extraction.text import TfidfTransformer

transformer = TfidfTransformer()
 transformer   
TfidfTransformer(norm=...'l2', smooth_idf=True, sublinear_tf=False,
                 use_idf=True)

counts = [[3, 0, 1],
...           [2, 0, 0],
...           [3, 0, 0],
...           [4, 0, 0],
...           [3, 2, 0],
...           [3, 0, 2]]
...
tfidf = transformer.fit_transform(counts)
 tfidf               
          
>>> <6x3 sparse matrix of type '<... 'numpy.float64'>'
    with 9 stored elements in Compressed Sparse ... format>

 tfidf.toarray()                        
>>> array([[ 0.85...,  0.  ...,  0.52...],
                 [ 1.  ...,  0.  ...,  0.  ...],
                 [ 1.  ...,  0.  ...,  0.  ...],
                 [ 1.  ...,  0.  ...,  0.  ...],
                 [ 0.55...,  0.83...,  0.  ...],
                 [ 0.63...,  0.  ...,  0.77...]])

4. BOW模型的限制

unigrams集(BOW)不能捕獲句字和多個詞的表示又憨,會丟失掉詞的順序依存。另外锭吨,BOW模型不能解釋可能的誤拼(misspellings)或者詞派生(word derivations)蠢莺。

ngram_vectorizer = CountVectorizer(analyzer='char_wb', ngram_range=(2,2), min_df=1)
counts=ngram_vectorizer.fit_transform(['word', 'wprds'])
counts

>>> <2x9 sparse matrix of type '<class 'numpy.int64'>'
    with 11 stored elements in Compressed Sparse Row format>

ngram_vectorizer.get_feature_names()
[' w', 'd ', 'ds', 'or', 'pr', 'rd', 's ', 'wo', 'wp']

使用’char_wb’分析器,它可以在字符邊界內(nèi)創(chuàng)建n-grams的字符(兩邊使用空格補齊)零如。而‘char’分析器則可以基于詞來創(chuàng)建n-grams躏将。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市考蕾,隨后出現(xiàn)的幾起案子祸憋,更是在濱河造成了極大的恐慌,老刑警劉巖肖卧,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蚯窥,死亡現(xiàn)場離奇詭異,居然都是意外死亡喜命,警方通過查閱死者的電腦和手機沟沙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來壁榕,“玉大人矛紫,你說我怎么就攤上這事∨评铮” “怎么了颊咬?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長牡辽。 經(jīng)常有香客問我喳篇,道長,這世上最難降的妖魔是什么态辛? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任麸澜,我火速辦了婚禮,結(jié)果婚禮上奏黑,老公的妹妹穿的比我還像新娘炊邦。我一直安慰自己,他們只是感情好熟史,可當(dāng)我...
    茶點故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布馁害。 她就那樣靜靜地躺著,像睡著了一般蹂匹。 火紅的嫁衣襯著肌膚如雪碘菜。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天,我揣著相機與錄音忍啸,去河邊找鬼仰坦。 笑死,一個胖子當(dāng)著我的面吹牛吊骤,可吹牛的內(nèi)容都是我干的缎岗。 我是一名探鬼主播静尼,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼白粉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鼠渺?” 一聲冷哼從身側(cè)響起鸭巴,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎拦盹,沒想到半個月后鹃祖,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡普舆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年恬口,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片沼侣。...
    茶點故事閱讀 39,754評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡祖能,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蛾洛,到底是詐尸還是另有隱情养铸,我是刑警寧澤,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布轧膘,位于F島的核電站钞螟,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏谎碍。R本人自食惡果不足惜鳞滨,卻給世界環(huán)境...
    茶點故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蟆淀。 院中可真熱鬧拯啦,春花似錦、人聲如沸扳碍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽笋敞。三九已至碱蒙,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背赛惩。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工伞芹, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人俐芯。 一個月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓肄渗,卻偏偏與公主長得像,于是被迫代替她去往敵國和親季惯。 傳聞我的和親對象是個殘疾皇子吠各,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,654評論 2 354

推薦閱讀更多精彩內(nèi)容