2018年6月18日 星期一

Coursera - Applied Data Science with Python 學習筆記 04 - Text Mining

《山林道》-「當初說這裡有天 會由樹變成路 一醒覺經已殺出這條路....
我只盼這裡有天 變回樹 撤回路 疏忽了趕快去補趁還未老... 」

Applied Data Science with Python的第四課-Applied Text Mining in Python,是更多有關文字、語言的處理,可以想像最後一課的social network應該有機會處理網絡社交平台上獲取的資料?

最基本的是文字的 Regular Expression 處理,在第一課時已略有使用過,幾個常用方法包括:

### Regular expression
import re
text = '@UN @UN_Women "Ethics are built right into the ideals and objectives of the United Nations" \
UNSG @NY @NY_Society for Ethical Culture bit.ly/2guVelr'   # 字串
text_list = text.split(' ')   # 分拆字串
[w for w in text_list if re.search('@[A-Za-z0-9_]+', w)]   # 查找吻合的pattern

# Dataframe 的字串處理
time_sentences = ["Monday: The doctor's appointment is at 2:45pm.", 
                  "Tuesday: The dentist's appointment is at 11:30 am.",
                  "Wednesday: At 7:00pm, there is a basketball game!",
                  "Thursday: Be back home by 11:15 pm at the latest.",
                  "Friday: Take the train at 08:10 am, arrive at 09:00am."]
df = pd.DataFrame(time_sentences, columns=['text'])

df['text'].str.split().str.len()   # find the number of tokens for each string in df['text']
df['text'].str.findall(r'(\d?\d):(\d\d)')   # group and find the hours and minutes
df['text'].str.replace(r'\w+day\b', '???')   # replace weekdays with '???'
df['text'].str.extractall(r'((\d?\d):(\d\d) ?([ap]m))')   # extract the entire time, the hours, the minutes, and the perio

然後就開始自然語言處理器 NLTK。課程是英語為主,但香港地更實際的一定是中文的處理,從前在 R 就聽過 Jieba 套件,Python世界似乎也是 Jieba 最廣為人所認識,當然這個 Jieba套件之後也要找機會試試。

所以,還是先溫習課程上所學習對英文的流程。首先是把文章進行分詞 (Tokenization),然後針對英文文法上的不同時態/詞型,分辨詞性 (Noun/Verb/Adj/...) 及縮減成詞根的提取 (Stemming) 或還原Lemmatization)。 這樣以後才可以做一些詞頻統計、Vectorization 後做預測模型、兩篇文章內容的相似度的比較。

2018年6月6日 星期三

Coursera - Applied Data Science with Python 學習筆記 03 - machine learning

第三課, Coursera上的最後一課已經開課,加快記完這篇就要再追一追進度了。機器學習隨著人工智能近年變成流行Buzzword,其實在引入神經網路(Neural Networks)前,一些模型例如Regression, logistics regression, KNN Classifier 等 迴歸 或 分類 模型; K means 的叢集;PCA 的縮減維度方法;Decision Tree的決策指引;很多概念都是統計和數學所已有的,只是一個機械學習的課程會對實作更有重視。

今次只是在有課程框架下去學python。當以<第一課>的技巧處理好數據成合用的格式, <第二課>繪圖後對數據有視覺化的印象, 可以進入第三課建立模型去做數據的形容/預測。其他例子可以參考之前幾篇,例如早期用 R 的:
[R] ML4B 課堂重溫 - 淺談 KNN (K-th Nearest Neighbors) 算法
[R] Show Me The Code - Machine Learning的簡易入門

在課堂的練習中,所有今次用到有關的scikit-learn library。從library的架構中可以留意到model selection, preprocessing, models, metrics幾大類別,對應著建立模型過程中的不同需要:
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import validation_curve

from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import PolynomialFeatures

from sklearn.neighbors import KNeighborsClassifier 
from sklearn.linear_model import LinearRegression, Ridge, Lasso, LogisticRegression
from sklearn.svm import LinearSVC, SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.dummy import DummyClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.neural_network import MLPClassifier

from sklearn.metrics.scorer import SCORERS
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import classification_report
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import mean_squared_error, r2_score

from sklearn.datasets import make_classification, make_blobs, make_friedman1, load_breast_cancer