tf-idf Sklearn文本數據的處理

#訓練數據
train=[
        '這不是我的問題本來就不該我負責',
        '這個問題解決不了,誰都搞不定',
        '你看,不行了吧,我就說過不行',
        '沒有問題,我處理',
        '好的,馬上處理',
        '太好了'
      ]

target=[0,0,0,1,1,1]
target_names=['負面','積極']

#得到文檔的稀疏矩陣
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(train)

print(X_train_counts)
print(count_vect.vocabulary_)
    
#詞頻和逆向文件頻率    
'''
TF(Term Frequency)表示某個關鍵詞在某文檔中出現的頻率。
    詞頻 = 某個詞在文檔中出現的次數/該文檔的總詞組數
    假設現在有一篇文章《貴州的大數據分析》,這篇文章包含了10000個詞組,其中“貴州”、“大數據”、“分析”各出現100次,“的”出現500次(假設沒有去除停用詞),
    則通過前面TF詞頻計算公式,可以計算得到三個單詞的詞頻,即:
    TF(“貴州”)=100/10000=0.01
    TF(“大數據”)=100/10000=0.01
    TF(“分析”)=100/10000=0.01
    TF(“的”)=500/10000=0.05
    
IDF(InversDocument Frequency)表示逆文檔頻率,
    逆文檔頻率 = log(語料庫中文檔總數/(包含該詞組的文檔個數+1))
    現在語料庫中共存在1000篇文章,其中包含“貴州”的共99篇,包含“大數據”的共19篇,包含“分析”的共“59”篇,包含“的”共“899”篇。則它們的IDF計算如下:
    TF(“貴州”)=1000/(99+1)=1.000
    TF(“大數據”)=1000/(19+1)=1.700
    TF(“分析”)=1000/(59+1)=1.221
    TF(“的”)=1000/(899+1)=0.046
    可以發現,當某個詞在語料庫中各個文檔出現的次數越多,它的IDF值越低,當它在所有文檔中都出現時,其IDF計算結果爲0,
    而通常這些出現次數非常多的詞或字爲“的”、“我”、“嗎”等,它對文章的權重計算起不到一定的作用。
    某個詞的IDF越高,說明這個詞的分類作用越重要
TF-IDF = 詞頻*逆文檔頻率
    通過TF-IDF計算,“大數據”在某篇文章中出現頻率很高,這就能反應這篇文章的主題就是關於“大數據”方向的。如果只選擇一個詞,“大數據”就是這篇文章的關鍵詞。
    所以,可以通過TF-IDF方法統計文章的關鍵詞。同時,如果同時計算“貴州”、“大數據”、“分析”的TF-IDF,將這些詞的TF-IDF相加,可以得到整篇文檔的值,用於信息檢索。
'''
from sklearn.feature_extraction.text import TfidfTransformer
tfidf_transformer =  TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)

print(X_train_tfidf)

#訓練分類器
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB().fit(X_train_tfidf, target)

#新的待預測數據也轉換爲tfidf
docs_new = ['不行', '我做不到','好的','不是我的問題']
X_new_counts = count_vect.transform(docs_new)
X_new_tfidf = tfidf_transformer.transform(X_new_counts)
print(X_train_tfidf)

#預測
predicted = clf.predict(X_new_tfidf)
for doc, category in zip(docs_new, predicted):
    print ('%r => %s'%(doc, target_names[category]))
    
    
#關於稀疏矩陣 https://docs.scipy.org/doc/scipy/reference/sparse.html
#csr_matrix((M, N), [dtype])
#to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype=’d’.
from scipy.sparse import csr_matrix
a=csr_matrix((100000,100))
a[0,0:1]=1
b=a[0:3, 0:7]

#分類特徵編碼 http://sklearn.lzjqsdd.com/modules/preprocessing.html#preprocessing-categorical-features
import numpy as np
train_feature = np.array([
          ["male", "from US", "uses Internet Explorer"],
          ["female", "from Asia", "uses Chrome"],
          ["female", "from CHina", "uses Chrome"]
        ])
        
from sklearn import preprocessing
#文本轉換爲整數
label_encoder = preprocessing.LabelEncoder()
integer_encoded = np.array([label_encoder.fit_transform(v) for v in train_feature.T]).T
print(integer_encoded)
'''
array([[1, 2, 1],
       [0, 0, 0],
       [0, 1, 0]], dtype=int64)
'''
enc = preprocessing.OneHotEncoder()
a=enc.fit_transform(integer_encoded)
print(a)
'''
 (0, 6)        1.0
 (0, 4)        1.0
 (0, 1)        1.0
 (1, 5)        1.0
 (1, 2)        1.0
 (1, 0)        1.0
 (2, 5)        1.0
 (2, 3)        1.0
 (2, 0)        1.0
'''

test_feature = np.array([
          ["female", "from US", "uses Chrome"],
          ["female", "from CHina", "uses Chrome"]
        ])
test_feature_integer_encoded = np.array([label_encoder.transform(v) for v in test_feature.T]).T

b=enc.transform(test_feature_integer_encoded)
print(b)
'''
(0, 5)        1.0
(0, 3)        1.0
(0, 0)        1.0
(1, 5)        1.0
(1, 2)        1.0
(1, 0)        1.0
'''
array = a.toarray()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章