特徵工程:將原始數據轉換爲更好地表明預測模型的潛在問題的特徵的過程,從而提供了對未知數據的預測準確性。python
from sklearn.feature_extraction import DictVectorizer def dictver(): """ 字典數據抽取 :return:None """ # 實例化 dict = DictVectorizer(sparse=False) # 調用fit_transform data = dict.fit_transform( [{'city': '北京', 'temperature': 100}, {'city': '上海', 'temperature': 60}, {'city': '深圳', 'temperature': 30}]) print(dict.get_feature_names()) print(dict.inverse_transform(data)) print(data) return None if __name__ == '__main__': dictver()
```mysql
def countvec(): """ 對文本進行特徵值化 :return:None """ cv = CountVectorizer() data = cv.fit_transform(['life is short, i like python','life is too long, i dislike python']) print(cv.get_feature_names()) # print(cv.inverse_transform(data)) print(data.toarray()) return None if __name__ == '__main__': countvec()
import jieba from sklearn.feature_extraction.text import CountVectorizer def cutword(): """ 中文字分割 :return: c1, c2, c3 """ con1 = jieba.cut('今天很殘酷,明天更殘酷,後天很美好,' '但絕對大多數是死在明天晚上,因此每一個人不要放棄今天') con2 = jieba.cut('咱們看到的從很遠星系來的光是在幾百萬年前發出的,' '這樣當咱們看到宇宙時,咱們是在看它的過去') con3 = jieba.cut('若是隻用一種方式瞭解某樣事物,你就不會真正的瞭解它。' '瞭解事物真正含義的祕密取決於如何將其與咱們所瞭解的事物相聯繫') # 轉換成列表 content1 = list(con1) content2 = list(con2) content3 = list(con3) # 把列表轉換成字符串 # join(iterable) 以指定字符串做爲分隔符,將content1中全部元素合併成一個新的字符串 c1 = ' '.join(content1) c2 = ' '.join(content2) c3 = ' '.join(content3) return c1, c2, c3 def hanzivec(): """ 中文特徵值化 :return: None """ c1, c2, c3 = cutword() cv = CountVectorizer() # 實例化 data = cv.fit_transform([c1, c2, c3]) print(cv.get_feature_names()) print(data.toarray()) if __name__ == '__main__': hanzivec()
TF-IDF: 若是某個詞或者短語在一篇文章中出現的機率高,而且在其餘文章中不多出現,則認爲此詞或短語具備很好的類別區分能力,適合用來分類。程序員
sklearn.feature_extraction.text.TfidfVectorizer
算法
import jieba from sklearn.feature_extraction.text import TfidfVectorizer def cutword(): """ 中文字分割 :return: c1, c2, c3 """ con1 = jieba.cut('今天很殘酷,明天更殘酷,後天很美好,' '但絕對大多數是死在明天晚上,因此每一個人不要放棄今天') con2 = jieba.cut('咱們看到的從很遠星系來的光是在幾百萬年前發出的,' '這樣當咱們看到宇宙時,咱們是在看它的過去') con3 = jieba.cut('若是隻用一種方式瞭解某樣事物,你就不會真正的瞭解它。' '瞭解事物真正含義的祕密取決於如何將其與咱們所瞭解的事物相聯繫') # 轉換成列表 content1 = list(con1) content2 = list(con2) content3 = list(con3) # 把列表轉換成字符串 # join(iterable) 以指定字符串做爲分隔符,將content1中全部元素合併成一個新的字符串 c1 = ' '.join(content1) c2 = ' '.join(content2) c3 = ' '.join(content3) return c1, c2, c3 def hanzivec(): """ 中文特徵值化 :return: None """ c1, c2, c3 = cutword() tf = TfidfVectorizer() # 實例化 data = tf.fit_transform([c1, c2, c3]) print(tf.get_feature_names()) print(data.toarray()) if __name__ == '__main__': hanzivec()