python機器學習及實踐 第三章3.2

  • 自然語言處理包NLTK:進行語言學分析,進行分詞以及詞性標註
#使用詞袋法對文本進行向量化
sent1='The cat is walking in the bedroom.'
sent2='A dog was running across the kitchen.'
from sklearn.feature_extraction.text import CountVectorizer
count_vec=CountVectorizer()
sentences=[sent1,sent2]
print count_vec.fit_transform(sentences).toarray()
print count_vec.get_feature_names()
#首先統計都出現了哪些詞(少了‘A’)然後再建立與詞數等長的向量 對應sent根據詞頻填入相應向量
#CountVectorizer的fit會過濾長度爲1的停用詞 例如 A
#對於一個由字符串構成的數組,每個元素可能是一個以空格分割的句子(sentence),
#CountVectorizer.fit的功能是將它們分割,爲每一個單詞(word)編碼,
#在這個過程中會自動濾除停止詞(stop words),例如英文句子中的”a”,”.”之類的長度爲1的字符串。
#CountVectorizer.transform的功能則是將輸入的數組中每個元素進行分割,然後使用fit中生成的編碼字典,將原單詞轉化成編碼,
##使用NLTK進行語言學分析
import nltk
nltk.download('punkt')
#對句子進行分割
tokens_1=nltk.word_tokenize(sent1)
print(tokens_1)
tokens_2=nltk.word_tokenize(sent2)
print(tokens_2)
#將詞表按照Ascii排列
vocab_1=sorted(set(tokens_1))
vocab_2=sorted(set(tokens_2))
print(vocab_1)
print(vocab_2)
#找到詞彙原始的詞根
stemmer=nltk.stem.PorterStemmer()
stem_1=[stemmer.stem(t) for t in tokens_1]
stem_2=[stemmer.stem(t) for t in tokens_2]
print(stem_1)
print(stem_2)
nltk.download('averaged_perceptron_tagger')
#對詞性進行標註
pos_tag_1=nltk.tag.pos_tag(tokens_1)
pos_tag_2=nltk.tag.pos_tag(tokens_2)
print(pos_tag_1)
print(pos_tag_2)

  • 詞向量分析word2vec:每個連續詞彙片段的最後一個單詞都受前面單詞的制約。
#詞向量訓練
from sklearn.datasets import fetch_20newsgroups
news=fetch_20newsgroups(subset='all')
X,y=news.data,news.target
from bs4 import BeautifulSoup
import nltk,re
#把新聞中的句子剝離出來 並且形成列表
def news_to_sentences(news):
    news_text=BeautifulSoup(news).get_next()
    tokenizer=nltk.data.load('tokenizers/punk/english.pickle')
    raw_sentences=tokenizer.tokenize(news_text)
    sentences=[]
    for sent in raw_sentences:
        sentences.append(re.sun('[^a-zA-Z]',' ',sent.lower().strip()).split())
    return sentences


sentences=[]
#將長篇新聞中的句子剝離出來
#import news_to_sentences
for x in X:
    sentences=sentences+news_to_sentences(x)
    
from gensim.models import word2vec
num_features=300
min_word_count=20
num_workers=2
context=5
downsampling=le-3

model=word2vec.Word2Vec(sentences,workers=num_workers,size=num_features,min_count=min_word_count,window=context,sample=downsampling)
model.init_sims(replaces=True)
model.most_similar('morning')
  • 沒有跑出結果,也沒有理解問題(先放着,後面會專門寫一篇填坑。)

xgboost:自動利用cpu的多線程進行並行,全稱是eXtreme Gradient Boosting.

#Xgboost模型
import pandas as pd
titanic=pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
y=titanic['survived']
X=titanic.drop(['row.names','name','survived'],axis=1)
X['age'].fillna(X['age'].mean(),inplace=True)
X.fillna('UNKNOWN',inplace=True)
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=33)
from sklearn.feature_extraction import DictVectorizer
vec=DictVectorizer()
X_train=vec.fit_transform(X_train.to_dict(orient='record'))
X_test=vec.transform(X_test.to_dict(orient='record'))
print( len(vec.feature_names_))

#使用隨機森林進行預測
from sklearn.ensemble import RandomForestClassifier
rfc=RandomForestClassifier()
rfc.fit(X_train,y_train)
print('RandomForestClassifier:',rfc.score(X_test,y_test))
#使用Xgboost進行預測
from xgboost import XGBClassifier
xgbc=XGBClassifier()
xgbc.fit(X_train,y_train)
print('XGBClassifier:',xgbc.score(X_test,y_test))
  • Tensorflow:利用會話來執行計算任務,初步進行了使用以及逐步進行了一個機器學習的基本任務。
#tensorflow會話執行
import tensorflow as tf
import numpy as np
greeting=tf.constant("Hello FangFang")
#啓動一個會話
sess=tf.Session()
#使用會話執行計算模塊
result=sess.run(greeting)
print(result)
sess.close()
#使用tensorflow完成一次線性計算
#matrix1爲1*2的行向量
matrix1=tf.constant([[3.,3.]])
#matrix2爲2*1的列向量
matrix2=tf.constant([[2.],[2.]])
#兩個向量相乘
product=tf.matmul(matrix1,matrix2)
#將乘積結果和一個標量拼接
linear=tf.add(product,tf.constant(2.0))
#直接在會話中執行linear
with tf.Session () as sess:
    result=sess.run(linear)
    print(result)
import tensorflow as tf
import pandas as pd
import numpy as np
train = pd.read_csv('../python/Datasets/Breast-Cancer/breast-cancer-train.csv')
test = pd.read_csv('../python/Datasets/Breast-Cancer/breast-cancer-test.csv')
X_train=np.float32(train[['Clump Thickness','Cell Size']].T)
y_train=np.float32(train['Type'].T)
X_test=np.float32(test[['Clump Thickness','Cell Size']].T)
y_test=np.float32(test['Type'].T)
#定義一個tensorflow的變量b作爲截距
b=tf.Variable(tf.zeros([1]))
#定義一個變量w作爲線性模型的係數(-1.0在1.0之間的均勻分佈)
w=tf.Variable(tf.random_uniform([1,2],-1.0,1.0))
#顯示定義線性函數
y=tf.matmul(w,X_train)+b
#使用reduce_mean獲得均方誤差
loss=tf.reduce_mean(tf.square(y-y_train))
#使用梯隊下降估計w,b,並設計迭代步長
optimizer=tf.train.GradientDescentOptimizer(0.01)
#以最小二乘爲優化目標
train=optimizer.minimize(loss)
#初始化所有變量
init=tf.initialize_all_variables()
#開啓會話
sess=tf.Session()
#執行初始化變量操作
sess.run(init)
#迭代1000次 訓練參數
for step in range(0,1000):
    sess.run(train)
    if step%200==0:
        print(step,sess.run(w),sess.run(b))
test_negative=test.loc[test['Type']==0][['Clump Thickness','Cell Size']]
test_postive=test.loc[test['Type']==0][['Clump Thickness','Cell Size']]
import matplotlib.pyplot as plt
plt.scatter(test_negative['Clump Thickness'],test_negative['Cell Size'],marker='o',s=200,c='red')
plt.scatter(test_postive['Clump Thickness'],test_postive['Cell Size'],marker='x',s=150,c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
lx=np.arange(0,12)
#以0.5爲界 1爲惡 0爲良
ly=(0.5-sess.run(b)-lx*sess.run(w)[0][0])/sess.run(w)[0][1]
plt.plot(lx,ly,color='blue')
plt.show()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章