Lesson 1 程式語言介紹
林嶔 (Lin, Chin)
R 完全免費,可以直接從網站上下載,且定期更新版本。
R 有許多使用者分享程式套件(packages),囊括先進的統計方法,且不定期更新。
R 具有強大且彈性的繪圖功能。
R 可以讀取各類型的資料。除了其它統計軟體的資料檔,R也可以讀取網頁、媒體或線上資料等。
R 是統計專業人員的研究工具,也是資料科學家經常使用的重要工具之一。
– 截止至2021年4月,R 在TIOBE Index排名第16位。
– 以Download R for Windows為例。
– 選base
– 選Download R 4.0.4 for Windows,如要下載先前版本選Previous releases
– 程式安裝位置盡量選擇D槽
– 選Free的版本
– 選Download RStudio Desktop
– 網頁往下滑會有其他版本可選擇
– 介面概況
– 可以調整介面字體大小,Tools → Global Options → Appearance → Zoom or Editor font size
– 建立一個Project : New Directory → New Project → 輸入Directory name → 選擇儲存位置 → Create Project
– 因此,使用R的第一步,請先將他當作一個高級的計算機。
– 請試著在左邊的Console視窗中,輸入下列程式碼,並體會他的計算功能
– 『函數』的使用方式是打下特定的字句,並且在『小括號』內輸入參數作為「input」,接著電腦將會根據你的指令進行回答。
函數「exp()」:負責進行自然指數運算
函數「sqrt()」:負責進行平方根運算
函數「log()」:負責(自然)對數運算
– 有趣的是,『函數』中的『input』不見得只能有1個,如函數「log()」可以額外輸入對數的底數,並以『,』進行分隔:
– 需要注意的是,如果我們不告訴電腦哪個是底數,哪個是運算目標,哪個是底數,那他將會依序認為你輸入的第一個數為需要被運算的數,而第二個數為底數:
– 註:物件的屬性有很多種,我們第二節才會對他進行詳細的介紹
– 注意,等號的右邊為「input」,等號的左邊為「output」
– 如果你只是需要查看物件內容,事實上直接輸入物件名稱也可以達到相同效果
– 物件強大的地方在於,我們可以將其做為暫存的工具,並且可以直接對「x」物件進行運算
– 函數「c()」中間以逗點為界,此函數可以將不同「數字」合併在同一個物件內
變數(Variable)層:邏輯(logical)向量、整數(integer)向量、因子(factor)向量、數字(numeric)向量、文字(character)向量
陣列(Array)層:矩陣(matrix)、資料表(data.frame)
列表(List)層:列表(list)、S3物件(S3 class)、S4物件(S4 class)
接著我們將學習利用物件索引叫出物件內的特定內容
在R裡面,「中括號」是索引函數,在物件的後面使用「中括號」,將可以叫出指定位置的內容
– 這是變數(Variable)層物件的索引方式
– 這是陣列(Array)層物件的索引方式
– 這是列表(List)層物件的索引方式
– 你也可以交叉使用這些索引函數
y = c(1, 1)
y[3] = y[1] + y[2]
y[4] = y[2] + y[3]
y[5] = y[3] + y[4]
y[6] = y[4] + y[5]
y[7] = y[5] + y[6]
y
費波納奇數列:起始數列為1、1,之後每個數為前兩個數之和
我們可以利用迴圈函數「for」,來創造費波納奇數列
– 在這裡我們需要兩個物件:物件「x」為儲存費波納奇數列的物件,而物件「indexes」代表著隨迴圈變化的物件
## [1] 1 1 2 3 5 8 13 21 34 55 89 144
## [13] 233 377 610 987 1597 2584 4181 6765 10946 17711
– 函數「paste」的功能是將文字前後連接起來,接著我們能再用「print」輸出在Console視窗中
students = c("小華", "小明", "小王")
scores = c(100, 80, 70)
for (i in 1:3) {
print(paste(students[i], "的考試成績為", scores[i], "分", sep = ""))
}
## [1] "小華的考試成績為100分"
## [1] "小明的考試成績為80分"
## [1] "小王的考試成績為70分"
## [1] 2 4 6 10 16 26 42 68 110 178 288 466
## [13] 754 1220 1974 3194 5168 8362 13530 21892 35422 57314
## [1] 2 4 6 10 16 26 42 68 110 178 288 466
## [13] 754 1220 1974 3194 5168 8362 13530 21892 35422 57314
– 其數據集包含了150個樣本,都屬於鳶尾屬下的三個亞屬,分別是山鳶尾(setosa)、變色鳶尾(versicolor)和維吉尼亞鳶尾(virginica)。四個特徵被用作樣本的定量分析,它們分別是花萼(sepal)和花瓣(petal)的長度和寬度。
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
##
## Call:
## lm(formula = y ~ x)
##
## Coefficients:
## (Intercept) x
## 3.41895 -0.06188
– 請在這裡下載MNIST的手寫數字資料,並讓我們了解一下這筆資料的結構
– 在這裡我們需要學習如何安裝「套件」,安裝後使用方法如下(你可不可以使用「read.csv」讀取?當然可以,但你可以測試看看速度):
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
– 讓我們到這裡下載其中的100張貓以及100張狗,最後再用這個分類器預測裡面貓狗各5張測試圖片。
– 讓我們試著把檔案讀進來,並學會畫圖:
## [1] 280 300 3
## , , 1
##
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0.1529412 0.1529412 0.1568627 0.1607843 0.1607843
## [2,] 0.1568627 0.1568627 0.1568627 0.1607843 0.1607843
## [3,] 0.1568627 0.1568627 0.1568627 0.1568627 0.1568627
## [4,] 0.1529412 0.1490196 0.1490196 0.1450980 0.1450980
## [5,] 0.1490196 0.1450980 0.1372549 0.1333333 0.1294118
##
## , , 2
##
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0.1725490 0.1725490 0.1725490 0.1764706 0.1764706
## [2,] 0.1764706 0.1764706 0.1725490 0.1764706 0.1764706
## [3,] 0.1764706 0.1764706 0.1725490 0.1725490 0.1725490
## [4,] 0.1725490 0.1686275 0.1647059 0.1607843 0.1607843
## [5,] 0.1686275 0.1647059 0.1529412 0.1490196 0.1450980
##
## , , 3
##
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0.1568627 0.1568627 0.1686275 0.1725490 0.1882353
## [2,] 0.1607843 0.1607843 0.1686275 0.1725490 0.1882353
## [3,] 0.1607843 0.1607843 0.1686275 0.1686275 0.1843137
## [4,] 0.1568627 0.1529412 0.1607843 0.1568627 0.1725490
## [5,] 0.1529412 0.1490196 0.1490196 0.1450980 0.1568627
## [1] 224 224 3
cat_img <- array(0, dim = c(224, 224, 3, 100))
for (i in 1:100) {
img = readImage(paste0('Dogs vs. Cats/cat.', i, '.jpg'))
resized_img = resizeImage(img, 224, 224, method = 'bilinear')
cat_img[,,,i] = resized_img
}
dog_img <- array(0, dim = c(224, 224, 3, 100))
for (i in 1:100) {
img = readImage(paste0('Dogs vs. Cats/dog.', i, '.jpg'))
resized_img = resizeImage(img, 224, 224, method = 'bilinear')
dog_img[,,,i] = resized_img
}
– 當然是可以的,如果你想保留物件的原始在R內的原始格式,你可以用「save」與「load」進行存取及載入:
– 應該還記得怎樣安裝套件吧!
library(shiny)
# Define UI for application that plots random distributions
shinyUI(pageWithSidebar(
# Application title
headerPanel("Hello Shiny!"),
# Sidebar with a slider input for number of observations
sidebarPanel(
sliderInput("obs", "Number of observations:", min = 0, max = 1000, value = 500)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
))
library(shiny)
# Define server logic required to generate and plot a random distribution
shinyServer(function(input, output) {
# Expression that generates a plot of the distribution. The expression is
# wrapped in a call to renderPlot to indicate that:
#
# 1) It is 'reactive' and therefore should be automatically re-executed
# when inputs change 2) Its output type is a plot
output$distPlot = renderPlot({
# generate an rnorm distribution and plot it
dist = rnorm(input$obs)
hist(dist)
})
})
前面已經說過,使用shiny(R package)所撰寫的App,他的基本構造是一個包含ui.R(主管使用者介面)以及server.R(主管伺服器端的處理)的資料夾。
Shiny app的基本運作流程為:
使用者自ui.R中的給定一個參數。
這個參數傳到server.R裡面,使用反應函數進行計算。
反應完成後,再回傳至ui.R輸出反應結果。
library(shiny)
# Define UI for application that plots random distributions
shinyUI(pageWithSidebar(
# Application title
headerPanel("Hello Shiny!"),
# Sidebar with a slider input for number of observations
sidebarPanel(
sliderInput("obs", "Number of observations:", min = 0, max = 1000, value = 500)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
))
headerPanel()用來定義網頁標題
sidebarPanel()用來定義的控制選單內含哪些可控參數,本例中只有一個滑動輸入元件sliderInput(),元件為obs
mainPanle()則是用來定義輸出區域的輸出結果,本例中只有一個圖片輸出元件plotOutput(),元件為distPlot
library(shiny)
# Define server logic required to generate and plot a random distribution
shinyServer(function(input, output) {
# Expression that generates a plot of the distribution. The expression is
# wrapped in a call to renderPlot to indicate that:
#
# 1) It is 'reactive' and therefore should be automatically re-executed
# when inputs change 2) Its output type is a plot
output$distPlot = renderPlot({
# generate an rnorm distribution and plot it
dist = rnorm(input$obs)
hist(dist)
})
})
其中是以shinyServer()這個函數為開頭,裡面包含著一個函數function()要求你指定input及output,由於我們只要做一個反應函數,由於我們想要畫一張圖,所以使用renderPlot()函數,在裡面我們指定它畫圖的過程,並且將結果儲存在output裡面的distPlot。
這個畫圖的過程很簡單,就是先指定一個數字(由input$obs提供,也就是剛剛在ui.R中使用者所給定的參數),然後要求R使用rnorm()隨機產生n個平均數為0,標準差為1的數列,而這個數列儲存在dist元件內。接著在以hist(dist)畫出這個數列的直方圖。
因此,在renderPlot()函數內,我們根據使用者指定的參數(input$obs)產生了一張直方圖,而這張直方圖將會儲存在output裡面的distPlot。
接著這個物件distPlot就會回到ui.R中,而根據我們在ui.R中所下的指令,他將會使用plotOutput()函數使這張圖形呈現在輸出區上。
Note:所有的輸入元件都存取在input這個List內;而所有的輸出元件都存取在output這個List內。
上午的課程很快的帶大家了解如何使用R語言,並且學習了一些必要的部分,希望大家可以再多練習並記住我們的語法內容。
索引及迴圈功能是程式語言的兩大支柱,我們能做到許多神奇的事都是依靠這兩個功能的組合而成,請務必記住不同物件的索引方法!
如果你想要進一步了解R語言,請到這裡觀看課程的線上講義。
在進入下午的課程之前,請大家先安裝一個套件「mxnet」,這個套件比較難安裝,可能會花掉很多時間,如果有遇到問題請找助教協助:
– 但要注意一點,僅有64位元的作業系統能安裝MxNet。
– 他的安裝方法比較特別,並且有安裝GPU版本的方法,下面是在WINDOW系統安裝CPU版本的作法:
– 如果是你的R語言是3.5以下的版本,你可能要參考這個語法安裝
cran <- getOption("repos")
cran["dmlc"] <- "https://s3-us-west-2.amazonaws.com/apache-mxnet/R/CRAN/"
options(repos = cran)
install.packages("mxnet")
– 如果是你的R語言是3.6以上的版本,你可能要參考這個語法安裝:
install.packages("https://s3.ca-central-1.amazonaws.com/jeremiedb/share/mxnet/CPU/3.6/mxnet.zip", repos = NULL)
– 或者參考這個語法安裝:
cran <- getOption("repos")
cran["dmlc"] <- "https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/R/CRAN/"
options(repos = cran)
install.packages("mxnet")
– 安裝完成後,用這個語法確認是否有成功!