利用sklearn進行字典&文本的特徵提取

寫在前面

這篇部落格主要內容:

  1. 應用DictVectorizer實現對類別特徵進行數值化、離散化
  2. 應用CountVectorizer實現對文本特徵進行數值化

特徵提取API

sklearn.feature_extraction

字典特徵提取

作用:對字典數據進行特徵值化

  • sklearn.feature_extraction.DictVectorizer(sparse=True,…)
    • DictVectorizer.fit_transform(X) X:字典或者包含字典的迭代器返回值:返回sparse矩陣
    • DictVectorizer.inverse_transform(X) X:array數組或者sparse矩陣 返回值:轉換之前數據格式
    • DictVectorizer.get_feature_names() 返回類別名稱
# 數據
[{'city': '北京','temperature':100}
{'city': '上海','temperature':60}
{'city': '深圳','temperature':30}]
# 程式碼
from sklearn.feature_extraction import DictVectorizer

def dict_demo():
    data = [{'city': '北京','temperature':100}, {'city': '上海','temperature':60}, {'city': '深圳','temperature':30}]
	# 1、實例化一個轉換器類
    transfer  = DictVectorizer(sparse=False)
    # 2、調用fit_transform
    data_new = transfer.fit_transform(data)
    print("data_new:\n",data_new)
    # 列印特徵名字
    print("特徵名字:\n",transfer.get_feature_names())
    
    return None

注意DictVectorizer默認是true,輸出為稀疏矩陣,false輸出為普通矩陣

不指定sparse=False結果

指定sparse=False結果

文本特徵提取

作用:對文本數據進行特徵值化

  • sklearn.feature_extraction.text.CountVectorizer(stop_words=[])

    • 返回詞頻矩陣
  • CountVectorizer.fit_transform(X) X:文本或者包含文本字元串的可迭代對象 返回值:返回sparse矩陣

  • CountVectorizer.inverse_transform(X) X:array數組或者sparse矩陣 返回值:轉換之前數據格

  • CountVectorizer.get_feature_names() 返回值:單詞列表

  • sklearn.feature_extraction.text.TfidfVectorizer

# 數據
["life is short,i like python",
"life is too long,i dislike python"]
# 程式碼
from sklearn.feature_extraction.text import CountVectorizer

def count_demo():
    data = ["life is short,i like like python", "life is too long,i dislike python"]
    transfer  = CountVectorizer()
    data_new = transfer.fit_transform(data)
    print("data_new:\n",data_new.toarray())
    print("特徵名字:\n",transfer.get_feature_names())
    return None

注意程式碼中的使用了toarray(),可以不加這個方法,再運行一下看看📑

運行結果