Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

[系列活動] 手把手教你R語言資料分析實務

16,391 views

Published on

在此課程中將帶領對資料分析感到陌生卻又充滿興趣的您,完整地學會運用 R 語言從最初的蒐集資料、探索性分析解讀資料,並進行文字探勘,發現那些肉眼看不見、隱藏在資料底下的意義。此課程主要設計給對於 R 語言有基本認識,想要進一步熟悉實作分析的朋友們,希望在課程結束後,您能夠更熟悉 R 語言這個豐富的分析工具。透過蘋果日報慈善捐款的資料集,了解如何從頭解析網頁,撰寫爬蟲自動化收集資訊;取得資料後,能夠靈活處理資料,做清洗、整合及探索;並利用現成的套件進行文字探勘、文本解析;我們將一步步實際走一回資料分析的歷程,處理、觀察、解構資料,試著看看人們在捐款的決策過程中,究竟是什麼因素產生了影響,以及這些結果又是如何從資料中挖掘而出的呢?

Published in: Data & Analytics
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Sex in your area is here: www.bit.ly/sexinarea
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

[系列活動] 手把手教你R語言資料分析實務

  1. 1. 游為翔, 張鈞閔 中央研究院資訊科學研究所 手把手教你R 語言資料分析實務 1
  2. 2. 事前準備 (請助教協助) 下載課程投影片、程式碼與資料  程式碼 : https://goo.gl/65QPyM  投影片 : https://goo.gl/JKHJAE 並確認檔案打開是否完整,有沒有亂碼問題 (R, RStudio應該都已安裝好囉……) 2
  3. 3. 事前準備 (請助教協助) 將下載的資料夾解壓縮 安裝需要的工具包 請打開 session_00_install_packages.R 執行檢查 3
  4. 4. FAQ.1: 打開程式碼後出現亂碼 解決辦法: 重新以 UTF-8 開啟程式碼
  5. 5. FAQ.2: 找不到檔案 解決辦法: 工作路徑不對, 用setwd指定到上課用的資料夾
  6. 6. FAQ.3: Rtools版本錯誤 解決辦法: 手動安裝後, 重新執行session00.R 至 https://cran.r-project.org/bin/windows/Rtools/ 下載對應你電腦中的R版本
  7. 7. Pkg “installr” # installing/loading the package: if(!require(installr)) { install.packages("installr"); require(installr)} # using the package: updateR() 7 FAQ.3: Rtools版本錯誤 (解法2) 解決辦法: 直接把 R 的版本升級!!!
  8. 8. FAQ.4: 缺少某些 dependent package 解決辦法: 手動安裝後, 重新執行安裝 Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) : there is no package called ‘Rcpp’ > install.package(“Rcpp”, dep = T)
  9. 9. FAQ.5: Mac 畫圖時的中文亂碼 解決辦法: 1) 在繪圖前, 執行 par(family = 'STHeiti') 2) 直接在繪圖時指定字型, plot( …, family = “STHeiti”)
  10. 10.  台大心理所畢  中研院資訊所研究助理  研究專長  網路數據探勘  消費及使用者行為分析  台大電機所畢  中研院資訊所研究助理  研究專長  線上平台定價自動化  線上平台使用者分析  計算社會學 10 Lecturers
  11. 11. 課程簡介 11
  12. 12. 今天的進行方式 課程內容說明 實作講解 (demo) 練習 公佈參考解答 課程投影片及需要的 data 與 code 皆可下載 12
  13. 13. 圖例 請打開 session_00_install_R_packages.R 代表在 Rstudio 工作 代表開啟網頁 Ex. http://www.appledaily.com.tw/appledaily/article/headline/2 0170112/37516585 另外課程有任何問題, 可以在 Sli.do 上進行提問  我們會盡可能的在課堂小結時回答 13
  14. 14. Outline A. 取得資料 & 清理 --- 資料收集與清整 B. 檢視資料與建立特徵 --- 探索性資料分析 C. 以不同面相建立更多特徵 --- 文字探勘 D. 解釋與預測 --- 建立模型 14
  15. 15. Session A 資料收集 Data Collection
  16. 16. 蘋果(日報)基金會公益捐款公開資料 資料:蘋果日報暖流版 16
  17. 17. 蘋果暖流新聞 17 http://www.appledaily.com.tw/appledaily/article/he adline/20160624/37280888
  18. 18. download.file 請打開 session_A_DataCollection.R 抓取網頁 資料收集 - 講解 A-01 18
  19. 19. 抓取網頁 # Article url url <- “http://www.appledaily.com.tw/appledaily/article/headl ine/20160704/37293645” # save the page download.file(url, “data/test.html”) 資料收集 - 講解 A-01 19 • 是否一定要把網頁 download 下來? • 看狀況, 如果你要爬的頁面很多, 但你還沒確定格式 (或還在測試), 或是已知該網站有 request 次數限制 … -> 建議把原始檔 (整個頁面) 抓下來
  20. 20. 存好檔案,如何把資訊擷取出來? 20
  21. 21. 先利其器 知己知彼瞭解檔案格式,如: xml, csv, json 載入資料前 站在巨人的肩膀上 -- 尋找合適的 R packages 21
  22. 22. 網頁架構及語法 HTML <標籤 屬性> 內容 </標籤> <html> <head> </head> <body> <h1 id=“title”> Title </h1> <p> Paragraph </p> <ol> <li> Item 1 </li> <li> Item 2 </li> </ol> </body> </html> <html> <head> <body> <h1 id=‘title’> <p> <ol> Title Paragraph <li> <li> Item 1 Item 2 22
  23. 23. 利用瀏覽器檢查原始碼 在 Chrome/Firefox 按下 F12
  24. 24. 讀取網頁資訊 (pkg xml2) xml2  讀取網頁:read_html; read_xml  選擇節點:xml_find_all; xml_find_first  擷取資訊:xml_text; xml_attr <html> <head> <body> <h1 id=‘title’> <p> <ol> Title Paragraph <li> <li> Item 1 Item 2 如何找到需要的節點? Xpath <標籤 屬性> 內容 </標籤> 24
  25. 25. XPath: a path of XML Tree 標記 意義 / 選取某標籤的根節點 (children) // 選取某標籤所有節點 (descendant) [@] 選取屬性 (attribute) * 任何標籤的節點 | OR 25 A book 目錄 第一章 第二章 … 段落1 段落2 段落1 段落2
  26. 26. XPath: a path of XML Tree 標記 意義 / 選取某標籤的根節點 (children) // 選取某標籤所有節點 (descendant) [@] 選取屬性 (attribute) * 任何標籤的節點 | OR 26 A book 目錄 第一章 第二章 … 段落1 段落2 段落1 段落2 先來個簡單的例子 簡單的網頁: https://goo.gl/jNHmDH 使用Xpath的解析範例: https://goo.gl/OcfO0O
  27. 27. Xpath = “//*[@id=‘inquiry3’]/table//tr[4]/td[1]”
  28. 28. 讀取網頁資訊 (pkg xml2) library(xml2) # set your target url doc <- read_html(url) # set the xpath of info needed xpath <- “//*[@id=‘inquiry3’]/table//tr[4]/td[1]” xml_text(xml_find_all(doc, xpath)) 資料收集 - 講解 A-01 28
  29. 29. 擷取資訊 xml_text(doc): <標籤 屬性> 內容 </標籤> xml_attr(doc, attr): <標籤 屬性> 內容 </標籤> 29 <html> <head> <body> <h1 id=‘title’> <p> <ol> Title Paragraph <li> <li> Item 1 Item 2 <html> <head> </head> <body> <h1 id=“title”> Title </h1> <p> Paragraph </p> <ol> <li> Item 1 </li> <li> Item 2 </li> </ol> </body> </html>
  30. 30. 練習 A-01 (8 mins) 請觀察網頁,寫出可以擷取正確資訊的 Xpath 1-1: 編號 1-2: 欄位名稱 1-3: 捐款文章連結 bonus: 共計頁數 資料收集 - 練習 A-01 30
  31. 31. 練習 A-01 (8 mins) 1-1 1-2 1-3 資料收集 - 練習 A-01 31
  32. 32. 練習 A-01 (8 mins) 請觀察網頁,寫出可以擷取正確資訊的 Xpath 1-1: 編號 1-2: 欄位名稱 1-3: 捐款文章連結 bonus: 共計頁數 bonus 資料收集 - 練習 A-01 32
  33. 33. 練習 A_ex01 (參考解答) 請觀察網頁,寫出可以擷取正確資訊的 Xpath 1-1: 編號:"//*[@id='inquiry3']/table//tr/td[1]" 1-2: 欄位名稱: "//*[@id='inquiry3']//tr[2]/th" 1-3: 捐款明細連結:"//*[@id='inquiry3']//tr/td[6]/a" bonus: 共計頁數: "//*[@id='charity_day']" 資料收集 - 練習 A-01 35
  34. 34. 將爬下來的資料轉存成 data frame # 第一種作法:把抓下來的vector合起來 data.frame(a1=a1, a2=a2, a3=a3, …) # 第二種作法:依特定排列填入二維表格 matrix() 資料收集 - 講解 A-02 36
  35. 35. 練習 A-02 (13 mins) 請將捐款進度報告頁面轉存成 csv 檔 # 學員自行隨機取第n 頁 page <- sample(1:n.page, 1) 資料收集 - 練習 A-02 df_article_raw.csv 37
  36. 36. 欄位 aid title date.published case.closed donation url.article url.detail 練習 A-02 (13 mins) 資料收集 - 練習 A-02 df_article_raw.csv # 學員自行隨機取第 n 頁 page <- sample(1:n.page, 1) 38
  37. 37. 欄位 aid title date.published case.closed donation url.article url.detail (需要特別處理) 練習 A-02 (13 mins) 資料收集 - 練習 A-02 df_article_raw.csv Xpath 39
  38. 38. 練習 A_ex02 (參考解答) 資料收集 - 練習 A-02 40
  39. 39. 練習 A-03 (Optional) 請規劃如何分析蘋果公益捐款資料,依設定的 目標將需要的網頁資訊擷取轉存下來。 資料收集 - 練習 A-03 41
  40. 40. 練習 A-03 (Optional) Outcome df_article_raw.csv 文章.txt 捐款明細.txt 資料收集 - 練習 A-03 42
  41. 41. 抓取該文章的Facebook讚數 – Facebook Graph API http://graph.facebook.com/?fields=share&id=htt p://www.appledaily.com.tw/appledaily/article/he adline/20170113/37517808 43
  42. 42. 小結 網頁爬蟲 觀察網頁 (靜態) 抓取所需資訊 (結構 / 非結構化資料處理) 轉成結構化形式儲存 進階知識 (動態網頁……) 44
  43. 43. 小結 練習 A-01 了解 Xpath 運作方式 練習 A-02 把捐款進度報告頁抓下來 (大表) 練習 A-03 把捐款明細抓下來 (每則捐款細目) 把原文抓下來 45
  44. 44. 原本就有的欄位 aid (文章代號) case.closed (是否結案) date.published (文章日期) donation (捐款金額) title (文章標題) url.article (文章連結) url.detail (捐款明細) 文章內容抓取欄位 journalist (撰文記者) n.image (圖片數量) n.word (文章字數) 捐款明細抓取欄位 donor (捐款人數) date.funded (結案日期) 下一堂課需要用到的資料欄位 df_article_raw → df_article 46 A - 02 A - 03
  45. 45. Next session starts at AM 11:00 Stay Tuned…… We’ll be back soon!! 47
  46. 46. 練習 A-03 解答 48
  47. 47. 練習 A_ex03 (參考解答) 資料收集 - 練習 A-03 df_article_raw.csv 49
  48. 48. Session B探索式資料分析 Explanatory Data Analysis
  49. 49. Data Manipulation 51
  50. 50. 現有資料 Outcome 文章總表 (df_article_raw.csv) 文章.txt (data/db_article_txt/) 捐款明細.txt (data/db_detail_txt/) EDA- 講解 B-01 52
  51. 51. df_article.csv 欄位 aid case.closed date.published donation title url.article url.detail donor date.funded journalist n.image n.word df_article.csv df_article_raw.csv 53
  52. 52. df_article.csv 範例 54
  53. 53. df_donation.csv In db_detail_txt.rar df_donation.csv 55
  54. 54. 練習 B-01 (10 mins) 請將 crawl 下來的所有專案捐款明細表,整合 成一張大表 df_donation.csv 取出必要資訊計算 各篇捐款總人數 各篇捐款總金額 各篇每人平均捐款金額 各篇捐款人捐款金額的中位數 EDA - 練習 B-01 56
  55. 55. Character Encoding Problem (Mac) 如果 read.csv 讀取中文出現亂碼 透過 Sys.getlocale() 確認 locale 預設語言 設定成英文 system("defaults write org.R-project.R force.LANG en_US.UTF-8") 設定成繁體中文 system("defaults write org.R-project.R force.LANG zh_TW.UTF-8") 或是透過 read.csv 的 parameters 設定 fileEncoding = "UTF-8" 57
  56. 56. 探索式資料分析 58
  57. 57. 什麼是 EDA ? EDA (Exploratory Data Analysis) 初步透過視覺化方法進行分析,達到三個主要 的目的  最大化對資料的了解  找出重要的變數  發現 outliers 或異常數值 不做過度假設地從原始數據看出隱含意義 59
  58. 58. 資料分析流程 資料收集 資料清理 決策應用 60 1 2 4 資料分析 特徵值萃取 建立模型 模型驗證 資料視覺化 3
  59. 59. 觀察資料與初步處理 61
  60. 60. Summary Functions in R Function Description 白話文 names() Functions to get or set the names of an object 看欄位名稱 head(), tail() Returns the first or last parts of a vector, matrix, table, data frame or function 看 前/(後) 幾筆資料 str() Compactly display the internal structure of an R object 物件屬性 summary() Produce result summaries 物件的基本數值狀態 dim() Retrieve or set the dimension of an object 矩陣大小 length() Get or set the length of vectors 向量長度 complete.cases() Return a logical vector indicating which cases are complete, i.e., have no missing values 回傳各元素 NA 邏輯值 as.Date() Convert between character representations and objects of class "Date" representing calendar dates 轉成日期型態 Function name and parameter 的縮寫解釋: http://jeromyanglim.blogspot.tw/2010/05/abbreviations-of-r-commands-explained.html 62
  61. 61. Visualization Functions in R Function Description 白話文 plot() Generic function for plotting of R objects 畫圖 (散布圖 or R object) boxplot() Produce box-and-whisker plot(s) of the given (grouped) values 盒鬚圖 hist() Computes a histogram of the given data values 分布圖 barplot() Creates a bar plot with vertical or horizontal bars 長條圖 arrows() Draw arrows between pairs of points 加箭頭 (x0, y0, x1, y1) abline() a, b: the intercept and slope, single values. y = [A] + [B]x 加一條截距為a, 斜率為b的直線 lines() Join the corresponding points with line segments. 折線圖 Function name and parameter 的縮寫解釋: http://jeromyanglim.blogspot.tw/2010/05/abbreviations-of-r-commands-explained.html 63
  62. 62. session_B_eda.R 讀入資料與看一看變數 # load in apple daily article > d <- read.csv(“df_article.csv”, fileEncoding = “utf-8”) # use dim() to know data frame dimension > dim(d) [1] 3779 12 # check the column names > names(d) [1] "aid" "case.closed" "date.funded" "date.published" [5] "donation" "donor" "journalist" "n.image" "n.word" [10] "title" "url.article" "url.detail" EDA - 講解 B-02 64
  63. 63. 檢視欄位 檢查每個欄位的屬性 (character, integer, date …) > typeof(d$date.published) > sapplay(d, typeof) # 懶惰一點, 一次看全部 將欄位轉換至適當格式 > d$date.published <- as.Date(d$date.published) > d$title <- as.character(d$title) EDA - 講解 B-02 65
  64. 64. # use str() to have a brief data summary > str(d) 利用 str() 迅速了解資料格式 EDA - 講解 B-02 66
  65. 65. 用 summary() 找出 NA EDA - 講解 B-02 67
  66. 66. 缺失值 (NA) 處理 判斷重要性 填補刪除 找出缺失值 (NA) 替換 1. which() + is.na() 2. !complete.case() 3. summary() 1. 變數是否重要 2. NA 所佔比例 1. 各別刪除 2. na.omit() 1. 比例法 2. 中位數 3. 內差法 尋找新資料 68
  67. 67. 練習 B-02 (Later) 處理 NA 值 將 n.word 的 NA 值補以平均數 將 n.image 的 NA 值補以眾數 EDA - 練習 B-02 69
  68. 68. 資料視覺化 70
  69. 69. 畫圖 - 畫什麼 - 怎麼畫 透過各種圖表檢視資料中各個變項間的關係 取決於你的核心問題是什麼  捐款總金額 vs. 捐款總人數  捐款的 總金額 / 總人數 vs. 特定的 議題 / 撰寫者 / 關鍵字 適合用什麼樣的圖表達  Box plot  Scatter plot  Bar plot  Line chart  Density plot  …… 71
  70. 70. EDA 常用的視覺化方式 箱型圖 (Box-plot) 直方圖 (Histogram) 散佈圖 (Scatter-plot) 折線圖 (Line-chart) 72
  71. 71. 問題 每篇文章獲得多少捐款?  一個 分布 問題 73
  72. 72. # use hist() to check donation distribution > hist(d$donation, breaks = 100) hist() EDA - 講解 B-02 74
  73. 73. EDA - 講解 B-02 Question : 捐款金額的整體分布長怎樣
  74. 74. 問題 捐款金額和人數的關係?  兩變數間的 散佈 問題 76
  75. 75. # use plot to check relationship between numbers of donors and total donation (and draw a linear line) > plot(d$donor, d$donation, pch = ‘.’, cex = 2) > y <- lm(donation ~ donor, data = d) > abline(y, col = ‘red’, lwd = 1.5) plot() EDA - 講解 B-02 77
  76. 76. EDA - 講解 B-02 Question : 單篇的捐款人數跟總金額的關係
  77. 77. 問題 不同記者寫的文章獲得的捐款金額是否相同?  一個 比較性 的問題 79
  78. 78. # check received donation of each journalist > n <- length(unique(d$journalist)) > b <- boxplot(d$donation ~ d$journalist, col = heat.colors(n), las = 2, ylim = c(0,2e6)) > abline(h = mean(d$donation), lty = 2, cex = 2) > text(1:n, (b$stats[3,]+b$stats[4,])/2, b$n, cex = 0.8) boxplot() EDA - 講解 B-02 80
  79. 79. Question : 記者的文筆有差? -> 每個記者的文章得到的捐款金額分布
  80. 80. 索爾好棒棒!!
  81. 81. 問題 為什麼不同記者的捐款金額有大差異? 可能是文筆特別好? 先確認其他面向 捐款人數 & 捐款金額  平均捐款金額 時間 83
  82. 82. 練習 B-02 (10 mins) 處理 NA 值 將 n.word 的 NA 值補以平均數 將 n.image 的 NA 值補以眾數 問問題,嘗試用各種圖觀察其他面向 捐款金額 / 捐款人數是否隨時間有變化? 捐款人平均捐款金額是否逐年增加? 捐款人捐給不同記者所寫的文章平均金額不同? … EDA - 練習 B-02 84
  83. 83. 練習 B_ex02 (參考解答) 85
  84. 84. 捐款金額隨時間的變化 86
  85. 85. EDA - 講解 B-02 Question : 越來越多台灣人有愛心? -> 單篇捐款人數隨年份的關係
  86. 86. EDA - 練習 B-02
  87. 87. A FINDING! 平均捐款金額隨時間稍微改變 捐款人數隨時間增加 得到的捐款金額隨時間增加!! 不同記者的文章獲得的捐款金額 是否亦受時間因素影響? EDA – 講解 B-02 89
  88. 88. EDA - 練習 B-02
  89. 89. 此時間趨勢可能造成… 誤解變數的影響力或遮蔽變數的效果 以為索爾很厲害,寫出了高質量文章… 但可能只是因為生逢其時? EDA – 講解 B-02 91
  90. 90. Detrending 92
  91. 91. 時間序列資料的 Detrending 透過統計或數學的操作,移除時間上的趨勢, 才能夠看清楚索爾的真正實力 或許貓女比較強 ? 基本的方法 線性回歸 LOWESS 局部加權散點平滑法  Locally weighted scatterplot smoothing  取一定比例的局部樣本做多項式回歸曲線  查看二維變量之間關係的有力工具 93
  92. 92. # 用 lm() 與 lowess() 看 donation vs date.published > plot(d$published, d$donation, pch = ‘.’, cex = 2) > lines(lowess(d$published, d$donation), col = ‘red’) > abline(lm(d$published, d$donation), col = ‘blue’) lm 與 lowess EDA – 講解 B-02 94
  93. 93. # 利用 R 內建的 lowess() 做 detrending > l <- lowess(d$donation ~ d$date.published) > d$donation.de <- d$donation - l$y + mean(l$y) > plot(d$published, d$donation.de, pch = ‘.’, cex = 3) 利用 lowess() 做 detrending EDA – 講解 B-02 95
  94. 94. > n <- len(unique(d$journalist)) > b <- boxplot(d$donation.de ~ d$journalist, col = heat.colors(n), las = 3, ylim = c(0, 1e6)) > abline(h = mean(d$donation.de), lty = 2, cex = 2) > title(‘journalist vs. donation.de’, ylab = ‘donation.de’) > text(1:n, 0, b$n, cex = 0.8, col = ‘blue’) 重新看一次 journalist 的表現 EDA – 講解 B-02 96
  95. 95. 練習 B-03 (Later) 以文章發行時間對捐款人數做 detrend EDA - 練習 B-03 98
  96. 96. 有沒有更多變數可以拿來解釋”捐款”? 爬新的資料 外部資料, for example  經濟指標  年度大事 從既有的資料挖出更多東西 文章本身 EDA – 講解 B-03 101
  97. 97. i <- grep('夫|父|男|翁|公|爸|漢', d$title) d$ttl.male <- 0 d[i, ]$ttl.male <- 1 i <- grep('妻|母|女|婆|嬤|媽|婦', d$title) d$ttl.female <- 0 d[i, ]$ttl.female <- 1 i <- grep('憂', d$title) d$ttl.anxiety <- 0 d[i, ]$ttl.anxiety <- 1 i <- grep('瞎|盲|失明', d$title) d$ttl.eye <- 0 d[i, ]$ttl.eye <- 1 找出標題內的資訊 EDA – 講解 B-03 102
  98. 98. EDA – 講解 B-03
  99. 99. EDA – 講解 B-03
  100. 100. 練習 B-03 以文章發行時間對捐款人數做 detrend 觀察資料特徵並創造新變數 利用 donation & donor 創造新變數 創造2 ~3 個新的標題相關變數 創造至少 2 個時間相關變數 EDA – 練習 B-03 105
  101. 101. 練習 B_ex03 (參考解答) EDA – 練習 B-03 106
  102. 102. 練習 B_ex03 (參考解答) EDA – 練習 B-03 107
  103. 103. EDA 總結 基本函數運用 釐清問題與視覺化 資料變形 (data transformation) 時間序列的 detrending 創造新變數 (variable creation) 找到彼此之間擁有最高相關性的變數組合 並且有合理的解釋 EDA – 總結 108
  104. 104. Next session starts at 13:50 Stay Tuned…… We’ll be back soon!! 109
  105. 105. Session C 90 分鐘的文字礦工 Text Mining in 90 minutes
  106. 106. 透過 Text Mining 了解文章的遣詞用字 如何影響人們的捐款行為
  107. 107. 中文好難 中文需要斷詞 每個英文單字 (word / term) 都用空格分開 下雨天留客,天留我不留 斷完詞,電腦還是看不懂 爬蟲是什麼?可以吃嗎? 建立詞庫 瞭解詞義 113
  108. 108. 詞庫、詞義 _______ 是最炎熱的季節 季節:春季、夏季、秋季、冬季 哪個比較適合? 詞與詞之間的距離 同義字:溫拿  人生勝利組 反義字:溫拿  魯蛇 詞的特徵化 (word embeddings) 114
  109. 109. 建立詞庫 詞庫:所有看過的字詞的集合, 通常用 V 表示 V: vocabulary 詞庫內的詞可以用 1 x |V| 的向量表示 稱為 one-hot vector 可視為索引 彼此獨立,沒有詞意 利用 jiebaR 斷詞和 text2vec 建立詞庫吧! 0 : 0 : 1 : 0 : 0 1 x |V| 1 2 : : k k+1 : : |V| 115
  110. 110.  db_article_txt.rar  df_article_after_eda.csv 需要的材料? 資料礦工- 講解 C-01 116
  111. 111.  $A2719 [1] "火燒厝 男寒夜睡破車初春乍暖還寒,55歲的單親爸 爸阿水(周正水)窩在報廢廂型車裡準備就寢,雖已蓋上兩 層被,還是冷得直發抖。阿水無奈地說,去年底住處鐵皮屋 慘遭祝融,「現在我最擔心的,是住校讀高二兒子放假回來 沒地方睡。」多年來,單親爸爸阿水靠著山區林務零工掙錢 撫養17歲的獨生子小傑,去年12月中,住處鐵皮屋被無名 火燒毀,家當付之一炬,並波及隔壁姪女一家,「害姪女一 家4口沒地方住,很對不起他們。」阿水說:「至今重建的 錢不知到哪兒去找?」蘋果基金會獲悉後,已先撥款襄助阿 水父子短期生活窘迫,並聯繫幫貧困家庭修屋的寶島行善義 工團協力修繕,義工團評估,兩屋重建材料費用約需70萬元 。當地村長說,目前已有縣府補助款共20萬元。疑老舊電線 走火望著火場殘垣灰燼,阿火說,那天傍晚,他結束工作返 家,一進門,便見屋後廚房濃煙不斷竄出,急忙打電話叫消 防隊,住家位於偏遠山區,過了半個多小時消防車才趕到, 一切都來不及了。當地村長說,鄰居趕緊拿出自家滅火器幫 忙滅火,但當天風勢強助長火舌,用掉20多個滅火器卻沒用 ,「火災鑑定是老舊電線走火,沒人受傷已是不幸中的大幸 。」姪女家境也不好阿水33歲的姪女阿菁說,她與33歲的 丈夫阿元育有6歲、4歲的子女,平時她在家帶孩子,家計由 阿元打零工維持,日子只能勉強餬口。火災當時,「聽到外 面有人叫『失火了』,我趕緊拉著兩個孩子往外衝。」阿菁 說,目前一家暫住附近大伯家,屋子太小,只能在客廳打地 舖,「我也知道二伯阿水沒錢,我們手頭也不寬裕,不知何 時房子才能重建。」阿水說,他現暫時睡在報廢廂型車中, 並在車外搭上帆布充當煮飯、作息空間,向鄰居借廁所大小 便、洗澡。「住在車裡,就當作野外露營,前幾波寒流來時 ,整晚冷到睡不著,春節也只能在哥哥家裡過。」阿水17歲 的兒子小傑說:「車子空間小,我短期可借住同學家,久了 不好意思。」" 資料礦工- 講解 C-01 117
  112. 112. # get all article names > files = list.files('data/db_articles_txt/db_articles_txt/', pattern = ‘txt', full.names = T) > file.name = gsub('.txt', '' ,basename(files)) # read the first 100 articles > file.len = 100 > article_txt = list() > for(i in 1:file.len) { a = readLines(files[i], encoding = ‘UTF-8’) article_txt[[file.name[i]]] = paste(a, collapse =‘’) } # check if all are correctly read in > fivenum(nchar(article_txt)) 讀入蘋果暖流文章 資料礦工- 講解 C-01 session_C_01_separate_words.R 118
  113. 113. $A2719 [1] "火燒厝 男寒夜睡破車初春乍暖還寒,55歲的單親爸爸阿水(周正水)窩在報廢廂型車裡準備就寢,雖已蓋上兩層被, 還是冷得直發抖。阿水無奈地說,去年底住處鐵皮屋慘遭祝融,「現在我最擔心的,是住校讀高二兒子放假回來沒地方睡。」 多年來,單親爸爸阿水靠著山區林務零工掙錢撫養17歲的獨生子小傑,去年12月中,住處鐵皮屋被無名火燒毀,家當付之一炬 ,並波及隔壁姪女一家,「害姪女一家4口沒地方住,很對不起他們。」阿水說:「至今重建的錢不知到哪兒去找?」蘋果基 金會獲悉後,已先撥款襄助阿水父子短期生活窘迫,並聯繫幫貧困家庭修屋的寶島行善義工團協力修繕,義工團評估,兩屋重 建材料費用約需70萬元。當地村長說,目前已有縣府補助款共20萬元。疑老舊電線走火望著火場殘垣灰燼,阿火說,那天傍晚 ,他結束工作返家,一進門,便見屋後廚房濃煙不斷竄出,急忙打電話叫消防隊,住家位於偏遠山區,過了半個多小時消防車 才趕到,一切都來不及了。當地村長說,鄰居趕緊拿出自家滅火器幫忙滅火,但當天風勢強助長火舌,用掉20多個滅火器卻沒 用,「火災鑑定是老舊電線走火,沒人受傷已是不幸中的大幸。」姪女家境也不好阿水33歲的姪女阿菁說,她與33歲的丈夫阿 元育有6歲、4歲的子女,平時她在家帶孩子,家計由阿元打零工維持,日子只能勉強餬口。火災當時,「聽到外面有人叫『失 火了』,我趕緊拉著兩個孩子往外衝。」阿菁說,目前一家暫住附近大伯家,屋子太小,只能在客廳打地舖,「我也知道二伯 阿水沒錢,我們手頭也不寬裕,不知何時房子才能重建。」阿水說,他現暫時睡在報廢廂型車中,並在車外搭上帆布充當煮飯 、作息空間,向鄰居借廁所大小便、洗澡。「住在車裡,就當作野外露營,前幾波寒流來時,整晚冷到睡不著,春節也只能在 哥哥家裡過。」阿水17歲的兒子小傑說:「車子空間小,我短期可借住同學家,久了不好意思。」" [1] "火燒" "厝" "男" "寒夜" "睡" "破車" "初春" "乍暖還寒" "55" "歲" "的" "單親" "爸爸“ [14] "阿水" "周正" "水" "窩" "在" "報廢" "廂型" "車裡" "準備" "就寢" "雖" "已" "蓋" [27] "上" "兩層" "被" "還是" "冷得" "直發抖" "阿水" "無奈" "地說" "去年底" "住處" "鐵皮屋" "慘遭" [40] "祝融" "現在" "我" "最" "擔心" "的" "是" "住校" "讀高二" "兒子" "放假" "回來" "沒" [53] "地方" "睡" "多" "年來" "單親" "爸爸" "阿水靠" "著" "山區" "林務" "零工" "掙錢" "撫養" [66] "17" "歲" "的" "獨生子" "小傑" "去年" "12" "月" "中" "住處" "鐵皮屋" "被" "無名" [79] "火燒" "毀" "家當" "付之一炬" "並" "波及" "隔壁" "姪" "女" "一家" "害" "姪" "女" [92] "一家" "4" "口" "沒" "地方" "住" "很" "對不起" "他們" "阿" "水" "說" "至今" [105] "重建" "的" "錢" "不知" "到" "哪兒" "去找" "蘋果" "基金會" "獲悉" "後" "已先" "撥款" [118] "襄助" "阿水" "父子" "短期" "生活" "窘迫" "並" "聯繫" "幫" "貧困家庭" "修屋" "的" "寶島" [131] "行善" "義工" "團" "協力" "修繕" "義工" "團" "評估" "兩屋" "重建" "材料" "費用" "約" [144] "需" "70" "萬元" "當地" "村長" "說" "目前" "已有" "縣府" "補助款" "共" "20" "萬元" [157] "疑老舊" "電線走火" "望著" "火場" "殘垣" "灰燼" "阿火" "說" "那天" "傍晚" "他" "結束" "工作" [170] "返家" "一" "進門" "便" "見" "屋後" "廚房" "濃煙" "不斷" "竄出" "急忙" "打電話" "叫" [183] "消防隊" "住家" "位於" "偏遠" "山區" "過了" "半個" "多" "小時" "消防車" "才" "趕到" "一切" [196] "都" "來不及" "了" "當地" "村長" "說" "鄰居" "趕緊" "拿出" "自家" "滅火器" "幫忙" "滅火" 119
  114. 114. 文章斷詞 jiebaR https://qinwenfeng.com/jiebaR/ 號稱最好的 Python 中文斷詞組件的 R 語言版本 支持四種斷詞引擎  最大概率法、隱式馬爾科夫模型、混和模型、索引模型 可以標註詞性 中研院斷詞系統 http://ckipsvr.iis.sinica.edu.tw/ 號稱地表最強中文斷詞系統 (96% 精準度) 自動標註詞性 需要申請…… 120
  115. 115. library(jiebaR) # initiate segmentation engine cutter = worker(bylines = T) # traditional way article_words = sapply(article_txt, function(x) segment(x, cutter)) # cooler way to do segmentation article_words = sapply(article_txt, function(x) cutter <= x) # check if all got segmented print(length(article_words)) 利用 jiebaR 斷詞 資料礦工- 講解 C-01 session_C_01_separate_words.R 121
  116. 116. a = article_words library(text2vec) # an iterator to access tokens in each article a.token <- itoken(a) # to create vocabulary based on the above tokens a.vocab <- create_vocabulary(a.token, ngram = c(1, 1)) # 詞(terms), 次數(terms count), 文章佔比(doc_counts) head(a.vocab$vocab) 利用 text2vec 建立詞庫 資料礦工- 講解 C-01 session_C_01_separate_words.R 122
  117. 117. 練習 C-01 (8 mins)  讀入 1000 篇文章並用 jiebaR 斷詞 jiebaR 可標註詞性  格式:夫(n) 肺癌(n) 末期(f)… text2vec 建立詞庫 123
  118. 118. 教電腦從文章中解讀詞意 word2vec Tomas Mikolov et.al 2013 年於 Google 開發 Prediction-based method reference Glove Jeffrey Pennington et al. 2015 年開發 (Stanford) Count-based method reference Dmitriy Selivanov 開發其 R 套件 text2vec  https://cran.r-project.org/web/packages/text2vec/index.html 124
  119. 119. 淺談 word2vec 語意相近的字較常出現在一起 Local window 讓電腦玩克漏字填空學習 word embedding Skip-gram Continuous bag of words 最熱的夏天 季節 Word,wt Context words …… Wt-1 Wt+1 125
  120. 120. Skip-gram 模型  藉由 current word 推測 context words  Neural network model  Stochastic gradient descend (SGD) 126 |V|:詞庫內所有的字詞數量 d :字詞向量化的維度 1 x |V| 0.2 : : 0.5 : 0.1 0 0 : 1 : : 0 0 0.1 : : 0.6 : 0.1 0 : : : : |V| x d W C d x |V| C d x |V| 1 x d wt 最熱的 Wt-1 夏天 Wt+1 季節 0 : : 1 : 0 0 0 : : 1 : 0 0 - - 126
  121. 121. Continuous Bag of Words 模型  由 context words 推測 current word 127 0.2 0.1 0 : 0.5 : 0 1 x |V| d x |V| W C|V| x d C|V| x d : : : : : 1 x d 0 1 : 0 : 0 0 0 0 : 1 : 0 0 wt 最熱的 Wt-1 夏天 Wt+1 季節 0 0 0 : 1 : 0 - 127
  122. 122. 詞向量 訓練結束後,將1 x |V| 字詞轉換成 d 維向量的 矩陣 |V| x d W |V| x d 1 2 : i : : |V| 1 2 … … … (d-2) (d-1) d 第 i 個詞的詞向量 128
  123. 123. 淺談 text2vec Global corpus statistics + local window Count-based method Term co-occurrence matrix, X Xij: 詞-i 和詞-j 共同出現次數 最熱的夏天 季節 Word,wt Context words Wt-1 Wt+1 1 2 ⁞ i ⁞ |V| 1 … j … k … |V| 最熱的 夏 天 季 節 +1 Term Co-occurrence Matrix +1 129
  124. 124. GloVe 模型  目標:訓練出一個詞矩陣 W 最能表示 term co-occurrence statistics  使用 AdaGrad, a variant of stochastic gradient descend |V| x d W 𝑤𝑖 𝑇 𝑤𝑗 + 𝑏𝑖 + 𝑏𝑗 = log 𝑋𝑖𝑗1. 對於一組詞向量 𝑤𝑖 和 𝑤𝑗,我們希望: 3. 𝑓(𝑋𝑖𝑗) 為加權函數,減少常見詞: 𝑓 𝑋𝑖𝑗 = 𝑋𝑖𝑗 𝑥 𝑚𝑎𝑥 𝛼 , 𝑋𝑖𝑗 < 𝑥 𝑚𝑎𝑥 1 , 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒 𝐽 = 𝑖=1 𝑉 𝑗=1 𝑉 𝑓(𝑋𝑖𝑗)(𝑤𝑖 𝑇 𝑤𝑗 + 𝑏𝑖 + 𝑏𝑗 − log 𝑋𝑖𝑗)2 2. 目標函數:最小化 130
  125. 125. 計算詞之間的距離 同義、反義 Cosine-similarity 計算字詞間的關係 老鼠跟大米 神奇的詞向量 在你(U)身上看見部份的自己(I) I U 老鼠 大米 我 你 找出你我之間的關係 131
  126. 126. # an iterator to help us a.token <- itoken(a) # vectorization of words a.vectorizer <- vocab_vectorizer(a.vocab, grow_dtm = FALSE, skip_grams_window = 5) # construct term co-occurrence matrix, tcm a.tcm <- create_tcm(a.token, a.vectorizer) 計算 TCM 資料礦工- 講解 C-02 session_C_02_create_glove.R 132
  127. 127. # glove fitting model fit <- glove(a.tcm, word_vectors_size = 100, x_max = 10, learning_rate = 0.2, num_iters = 15) # word_vectors$w_i = word vectors # word_vectors$w_j = context vectors word.vec <- fit$word_vectors$w_i + fit$word_vectors$w_j rownames(word.vec) = rownames(a.tcm) Encoding(rownames(word.vec)) = 'UTF-8' 向量化字詞組 資料礦工- 講解 C-02 session_C_02_create_glove.R 133 Text2vec version = 0.3 Check package version – Session_info()  找到 text2vec的數字就是你安裝的版本
  128. 128. 如果你裝的是 text2vec 0.4 134 glove = GlobalVectors$new(word_vectors_size = 100, vocabulary = a.vocab, x_max = 30) glove$fit(a.tcm, n_iter = 15) word.vec <- glove$get_word_vectors() rownames(word.vec) = rownames(a.tcm) Encoding(rownames(word.vec)) = "UTF-8" View(word.vec) Text2vec version = 0.4
  129. 129. 練習 C-02 (15 mins) 用 text2vec 做出 2 種不同的詞向量結果 向量長度 word_vectors_size 字詞頻率限制 x_max 將 word vectors 和 context vectors 的兩種詞向 量相加,給下一個部分使用 資料礦工- 練習 C-01,02 135
  130. 130. 練習 C-03 (15 mins) 寫出 get_analogy function 測試 get_analogy("女兒","爸爸","媽媽") 測試 get_analogy("房子","孝順","不孝") 從頭一次! 改成讀入 1500 篇文章  file.len <- 1500  source(“session_C_02_create_glove.R”) 再測試一次  get_analogy("女兒","爸爸","媽媽")  get_analogy("房子","孝順","不孝") 資料礦工- 練習 C-03 session_C_03_get_analogy.R 136 <Note> Text2vec version 在 v0.3, v0.4的 code不同唷!
  131. 131. # calculate unit vector > word.vec.norm = sqrt(rowSums(word.vec^2)) # build the function > get_analogy = function(king, man, woman) { queen = word.vec[king, , drop = F] – word.vec[man, , drop = F] + word.vec[woman, , drop = F] cos.dist = text2vec:::cosine(queen, word.vec, word.vec.norm) head(sort(cos.dist[1, ], decreasing = T,10) } get_analogy 資料礦工- 練習 C-03 session_C_03_get_analogy.R 139 <Note> Text2vec version 在 v0.3, v0.4的 code不同唷! Text2vec version = 0.3
  132. 132. 如果你裝的是 text2vec 0.4 140 get_analogy = function(king, man, woman) { # HINT: establish an analogy logic, vec(queen) = vec(king) - vec(man) + woman queen = word.vec[king, , drop = F] - word.vec[man, , drop = F] + word.vec[woman, , drop = F] # HINT: calculte the cosine-similarity among vec(queen) and other word vectors cos.dist = text2vec:::sim2(x = queen, y = word.vec, method = "cosine", norm = "l2") # please show the top-10 words for this analogy task head(sort(cos.dist[1,], decreasing = T), 10) } Text2vec version = 0.4
  133. 133. 使用 100篇文章 > get_analogy('女兒', '爸爸', '媽媽') 女兒 媽媽 的 歲 了 大 0.6894198 0.5624501 0.4997210 0.4710033 0.4637007 0.4396069 先生 著 為 好 0.4341230 0.4339599 0.4281633 0.4276368 > get_analogy('房子','孝順','不孝') 不孝 房子 支才 精緻 離職 現況 0.5783372 0.4811721 0.3316755 0.3299203 0.3294964 0.3214770 斷藥 供水 外面 靠的還 0.3096872 0.3076579 0.3048728 0.3018286 141
  134. 134. 使用 1500篇文章 > get_analogy('女兒','爸爸','媽媽') 女兒 兒子 兩個 弟弟 孫子 媽媽 0.9166055 0.7407315 0.7194995 0.6973939 0.6941895 0.6889858 歲 孩子 她 和 0.6829127 0.6699260 0.6691248 0.6688349 > get_analogy('房子','孝順','不孝') 房子 拍 抵押 貸款 租 老家 0.6921786 0.4567163 0.4464729 0.4350123 0.4319352 0.4130161 賣掉 房貸 田地 犛 0.3984212 0.3918540 0.3888297 0.3665320 > get_analogy('肝癌','爸爸','媽媽') 肝癌 罹患 乳癌 末期 口腔癌 肺癌 0.8684388 0.6630712 0.6099472 0.5853218 0.5523871 0.5438197 罹 那年 癌症 父親 0.5383895 0.5241434 0.5236973 0.5022830 142
  135. 135. 在字詞向量化後 相似的字詞之間距離較相近 將相似的詞做分群 (Clustering) 資料礦工- 練習 C-04
  136. 136. k-means clustering 資料分類 資料礦工- 練習 C-04 146
  137. 137. k-means clustering 步驟  隨機選取 k 個中心點 (cluster center)  計算所有點與中心點的距離  歸類到最近的中心  重新計算 k 個群的中心點,做為新的群中心點  重複上面三步驟,直到群中心點收斂(不改變) 資料礦工- 練習 C-04 147
  138. 138. Source: http://simplystatistics.orgwp-content/uploads/2014/02/kmeans.gif 資料礦工- 練習 C-04
  139. 139. Source: http://simplystatistics.orgwp-content/uploads/2014/02/kmeans.gif 資料礦工- 練習 C-04
  140. 140. k = 200  donor.de vs k133 (死亡用詞), cor = 0.203  donor.de vs k180 (食物用詞), cor = 0.1008 > w[w$k == 133,]$V1 [1] "走(Vi)" "病逝(Vi)" "逝(Vi)" "留下(Vt)" "死(Vi)" "去世(Vi)" "生前(N)" "喪葬(N)" "喪葬費(N)" "往生(Vi)" [11] "猝(ADV)" "交代(Vt)" "後事(N)" "留(Vt)" "驟(ADV)" "心肌(N)" "梗塞(Vi)" "來不及(ADV)" "身亡(Vi)" "悲傷(Vi)" [21] "喪夫(Vi)" "喪事(N)" "遺照(N)" "送走(Vt)" "突然(Vi)" "出殯(Vi)" "辦妥(Vt)" "靈堂(N)" "猝死(Vi)" "喪子(Vi)" [31] "程(N)" "國民(N)" "不敵(Vt)" "白髮人(N)" "黑髮人(N)" "臨終(Vi)" "病故(Vi)" "含淚(Vi)" "溺斃(Vi)" "辦好(Vt)" [41] "撒手(Vi)" "遺體(N)" "辭世(Vi)" "老幼(N)" "人世(N)" "辦完(Vt)" "斷氣(Vi)" "殯儀館(N)" "冰櫃(N)" "悲慟(Vi)" [51] "桂圓(N)" "奠儀(N)" "睡夢(N)" "繼(P)" "葬儀社(N)" "離世(Vi)" "紙錢(N)" "再見(Vi)" "黑髮(N)" "平復(Vt)" [61] "小晟(N)" "喪禮(N)" "林美琴(N)" "遺言(N)" "棺木(N)" "葬(Vt)" "積勞成疾(Vi)" "遽逝(Vi)" "享年(Vt)" "陳芷涵(N)" [71] "孤(Vi)" "安葬(Vt)" "永隔(N)" "杜氏(N)" "火化(Vt)" "薛(N)" "葉榮進(N)" "含悲(Vi)" "悲痛(Vi)" "遺書(N)" [81] "處理完(Vt)" "周麗珠(N)" "江鎧安(N)" "莫惠萍(N)" "自焚(Vi)" "莊台(N)" "阿治(N)" "李瑪美(N)" "忠正(N)" "悲(Vi)" > w[w$k == 180,]$V1 [1] "吃(Vt)" "餐(M)" "飯(N)" "晚餐(N)" "煮(Vt)" "便當(N)" "青菜(N)" "餓(Vi)" "省錢(Vi)" "配(Vt)" [11] "罐頭(N)" "飯菜(N)" "泡麵(N)" "早餐(N)" "稀飯(N)" "炒(Vt)" "熱(Vt)" "白飯(N)" "麵(N)" "肉(N)" [21] "餓肚子(Vi)" "飽(Vi)" "包(M)" "鍋(M)" "碗(M)" "拌(Vt)" "果腹(Vi)" "粥(N)" "碗(N)" "吃飽(Vi)" [31] "瓶(M)" "頓(M)" "好吃(Vi)" "吃完(Vt)" "一口(ADV)" "蛋(N)" "醬油(N)" "麵包(N)" "湯(N)" "加菜(Vi)" [41] "餐桌(N)" "道(M)" "鍋(N)" "樣(M)" "麵線(N)" "煎(Vt)" "剩菜(N)" "饅頭(N)" "弄(Vt)" "麵條(N)" [51] "開水(N)" "澆(Vt)" "鹹(Vi)" "填飽(Vt)" "煮好(Vt)" "鹽(N)" "肉鬆(N)" "炒飯(N)" "盤(M)" "蛋炒飯(N)" [61] "加熱(Vi)" "荷包蛋(N)" "苦瓜(N)" "吃到(Vt)" "水餃(N)" "營養(Vi)" "滷肉(N)" "豆漿(N)" "菜色(N)" "年夜飯(N)" [71] "放進(Vt)" "自助餐(N)" "省下來(Vi)" "扒(Vt)" "舀(Vt)" "吃剩(Vi)" "醬瓜(N)" "餓死(Vt)" "打發(Vt)" "蒸(Vt)" [81] "充飢(Vi)" "燙(Vt)" "滷(Vt)" "菜肉(N)" "匙(M)" "攪拌(Vt)" "絲瓜(N)" "會兒(N)" "豆腐(N)" "配上(Vt)" [91] "罐(N)" "飯桌(N)" "包子(N)" "白開水(N)" "津津有味(Vi)" "食量(N)" "吐司(N)" "熱騰騰(Vi)" "醬菜(N)" "用餐(Nv)" [101] "填(Vt)" "湯汁(N)" "配飯(N)" "吃光(Vt)" "大鍋(N)" "菜葉(N)" "湯麵(N)" "午飯(N)" "食欲(N)" "菜湯(N)" 資料礦工- 練習 C-04 155
  141. 141. Text mining in R 總結 jiebaR 文章斷詞 text2vec 建立詞庫、TCM 與 GloVe 字詞向量化 類比函數 get_analogy 運用 k-means clustering 將字詞向量分群 資料礦工- 練習 C-04 160
  142. 142. Next session starts at 15:50 Stay Tuned…… We’ll be back soon!! 161
  143. 143. Session D建立模型 & 預測 Model Building & Prediction
  144. 144. 模型要幹嘛, 能吃嗎? 163
  145. 145. 建立模型  目標 : 找到一個方法 f(x) 來盡可能地解釋/預測我們有興趣的東西 y 164 y ≈ f( )
  146. 146. 建立模型 以文本資料建立模型 – 預測文章是哪位記者寫的 以所有資訊建立模型 – 預測每篇的捐款金額 / 捐款人數 165
  147. 147. 驗證模型 Continuous Variable Pearson correlation coefficient = 𝑐𝑜𝑣(𝑋,𝑌) 𝜎 𝑥 𝜎 𝑦 Coefficient of determination (R2) = 1 − 𝑆𝑆 𝑟𝑒𝑔 𝑆𝑆𝑡𝑜𝑡 RMSE (Root mean square error) = 𝑡=1 𝑛 ( 𝑦𝑡−𝑦𝑡) 𝑛 Categorical Variable Accuracy = 𝑇𝑃+ 𝑇𝑁 𝑃+𝑁 F1-score = 2 ⋅ 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛∙𝑟𝑒𝑐𝑎𝑙𝑙 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛+𝑟𝑒𝑐𝑎𝑙𝑙 = 2𝑇𝑃 2𝑇𝑃+𝐹𝑃+𝐹𝑁 SStot SSreg 166 預測值 1 0 實際值 1 TP FN 0 FP TN
  148. 148. 以文本資料建立模型 167
  149. 149. 核心問題 我們有文章的資訊,機器是否可以判讀出這篇 文章是哪一位 Hero 記者寫的呢? 168
  150. 150. 詞向量 計算文章向量 上一堂課我們計算了每個文詞的詞向量,並且 利用向量來看各個文詞之間的關係。 文章內的每個詞向量加總起來,可以用來代表 每篇文章的屬性。 文章 169
  151. 151. 計算文章向量 (cont’d) 詞向量 文章 170
  152. 152. 資料欄位 # read in the data load('data/w2v_name_clustering(k=200).Rdata') # subset the column by names ch <- which(sapply(d, is.factor)) ttl<- names(d)[grep("^ttl", colnames(d))] fb <- names(d)[grep("fb", colnames(d))] kg <- names(d)[grep('^g', names(d))] time <- names(d)[grep('day|month', names(d))] yns <- names(d)[grep('^don', names(d))] rest <- names(d)[!names(d)%in%c(ttl, fb, k, kg, yns, time)] 預測模型 - 講解 D-01 171
  153. 153. 預測文章是哪位記者寫的 172
  154. 154. 決策樹的簡單版概念 在空間中找到一些線(rule)讓這些點可以被分開 173
  155. 155. Decision Tree set.seed(904) # Control random sample sample_index <- sample(1:nrow(data), nrow(data) * 0.95) dta_trn <- data[sample_index, ] dta_tst <- data[-sample_index, ] dt.fit <- rpart(form, data=dta_trn) printcp(dt.fit) plot(dt.fit, uniform=T) text(dt.fit, use.n=T, cex=0.75) pred <- predict(dt.fit, newdata = dta_tst) 預測模型 – 講解 D-01 174
  156. 156. 練習 D-01 (15 mins) 決策樹練習 改變 training /testing set 的比例 嘗試丟新的文章進去預測該篇文章的記者是誰, 並計算正確率 預測模型 – 練習 D-01 session_D_ex01.R 176
  157. 157. 捐款金額 / 捐款人數 受到哪些因素影響 ? 核心問題 177 y ≈ f( )
  158. 158. 線性模型 178
  159. 159. 線性迴歸模型 179
  160. 160. 線性迴歸模型 (Multiple regression model) 目標: 在空間中找到一條線, 讓誤差項總和最小化 Model evaluation: 1. R-square (解釋量) = SSreg/SStot 2. n SSE n   1 2 RMSE 180
  161. 161. 手上有哪些材料? 原始資料:每篇文章的 時間、捐款金額、捐款人數 標題、內文、字數、圖片、撰文者 萃取資訊 數字轉化  mean, med, log…… 文本  標題是否含有男女、單親、小孩、癌症、死亡……  文章內文的用字、結構、語意 (詞向量) 預測模型 - 講解 D-02 181
  162. 162. 資料欄位 選定應變數 (Response variables, or Y) donor.de (or detrended donation, donation.mean, etc.) 選定自變數 (Features, or Xs) 文章的 meta info  時間、文章標題資料 文章的詞向量  GloVe  Word2vec 文章的分群詞比例 (n 群)  “k-ratio” 預測模型 - 講解 D-02 182
  163. 163. 篩選資料 變數間相關性 Mutual-correlation check 共線性診斷 變異數膨脹因素 VIF (Variance Inflation Factor) 預測模型 - 講解 D-02 183
  164. 164. 篩選資料 (cont’d) # pseudo code # feature-feature correlation data <- cor(data, use=“complete”) # variance inflation fraction source(“func/vif.R”) vif(data, th=10) 預測模型 - 講解 D-02 184
  165. 165. 線性迴歸模型 # pseudo code lm.fit <- lm(y ~ x1 + x2 + x3……, data=data) 預測模型 - 講解 D-02 185
  166. 166. 練習 D-02 (8 mins) 資料修整 請讀取 “w2v_name_clustering(k=200).Rdata” 去除 outliers (保留約 95%資料) 取近一年資料  從 2015-01-01 到 2016-06-03 設定 Response Variable  捐款人數 donor.de 檢查 mutual correlation 和 VIF 練習檢查lm結果 預測模型 – 練習 D-02 session_D_ex02.R 186
  167. 167. 好多變項啊! 到底要挑哪些?  Step Function # pseudo code lm.select <- step(lm.fit) 預測模型 - 講解 D-02 187
  168. 168. 好多變項啊! 到底要挑哪些? (Cont.) 1. 比較 Adjusted R2 2. 簡單的用 ANOVA 做模型比較 (看是否有差) 個人 Conclusion – 選 Adjusted R2 高的 188
  169. 169. 支持向量機 (support vector machine) 目標: 在空間中找到一條向量, 把海劈開 ,讓兩群樣本分開 Picture from themetapicture.com 189
  170. 170. 支持向量機 (pkg e1071) # pseudo code svm.fit <- svm(y ~ x1 + x2 + x3……, data=data) 預測模型 - 講解 D-03 190
  171. 171. Cross Validation # leave-One-Out i <- 1 testing <- d1[i, c(yn, x.ttl, x.fb, x.t, x.k, x.g)] training <- d1[-i, c(yn, x.ttl, x.fb, x.t, x.k, x.g)] svm.fit <- svm(form, data = training) p <- predict(fit, testing) c(testing[, yn], p) 預測模型 - 講解 D-03 192
  172. 172. 練習 D-03 (8 mins) 請以 leave-one-out 的方式做 SVM 的 cross validation 計算 Pearson Correlation Coefficient 計算 Coefficient Determination (R-squared) 畫圖 預測模型 – 練習 D-03 session_D_ex03.R 193
  173. 173. 練習 D-03 (進階) Bonus: 更換 SVM kernel 看結果有何不同。 預測模型 – 練習 D-03 session_D_ex03_bonus.R 194
  174. 174. 練習 D-03 (解答) 請以 leave-one-out 的方式做 SVM 的 cross validation。 計算 Pearson Correlation Coefficient 計算 Coefficient Determination (R-squared) 畫圖 預測模型 – 練習 D-03 195
  175. 175. Classification 將資料切為前 50% 與後 50% 兩類,做 SVM 的 classification。 預測模型 - 講解 D-04 197
  176. 176. Diagnostic Testing 預測值 1 0 實際值 1 TP FN 0 FP TN Accuracy = 𝑇𝑃+ 𝑇𝑁 𝑃+𝑁 F1-score = 2𝑇𝑃 2𝑇𝑃+𝐹𝑃+𝐹𝑁 預測值 1 0 實際值 1 TP FN 0 FP TN Selected Relevant False Negatives True Negatives False Positives True Positives Precision Recall 198
  177. 177. Classification (cont’d) # pseudo code # cut data in half y <- ifelse(y > median(y), "high", "low") # 做 SVM 並以leave-one-out 檢查 # accuracy acc <- mean(p$actual==p$predict) # f1-score fsc <- 2*TP / (2*TP+FP+FN) 預測模型 - 講解 D-04 199
  178. 178. 練習 D-04 (5 mins) 將資料切為前 25% 與最後 25% 兩類,做 SVM 的 classification 後,計算 accuracy 與 F1-score。 預測模型 – 練習 D-04 200
  179. 179. 練習 D-04 (解答) 將資料切為前 25% 與最後 25% 兩類,做 SVM 的 classification 後,計算 accuracy 與 F1-score。 # 切 upper / lower classes quantile(d1[, yn], c(0.25, 0.75))[c("25%", "75%")] 預測模型 – 練習 D-04 session_D_ex04.R 201
  180. 180. 練習 D-05 (Homework) 請練習找出最好的 method 與 features 做預測 模型,提昇準確率,並做 cross validation。 預測模型 – 練習 D-05 202
  181. 181. 練習 D-05 (參考解答) gratio kratio glv a2v 203
  182. 182. 今天學到了什麼? 204
  183. 183. 資料分析流程 資料收集 資料清理 決策應用 205 1 2 4 資料分析 特徵值萃取 建立模型 模型驗證 資料視覺化 3
  184. 184. Hard work pays off. THANK YOU ALL!! 206

×