深度學期快速入門

Lesson 1 程式語言介紹

林嶔 (Lin, Chin)

什麼是R語言

  1. R 完全免費,可以直接從網站上下載,且定期更新版本。

  2. R 有許多使用者分享程式套件(packages),囊括先進的統計方法,且不定期更新。

  3. R 具有強大且彈性的繪圖功能。

  4. R 可以讀取各類型的資料。除了其它統計軟體的資料檔,R也可以讀取網頁、媒體或線上資料等。

  5. R 是統計專業人員的研究工具,也是資料科學家經常使用的重要工具之一。

– 截止至2021年4月,R 在TIOBE Index排名第16位。

開始的第一步:安裝R語言(1)

– 以Download R for Windows為例。

F01

– 選base

F02

– 選Download R 4.0.4 for Windows,如要下載先前版本選Previous releases

F03

– 程式安裝位置盡量選擇D槽

開始的第一步:安裝R語言(2)

– 選Free的版本

F04

– 選Download RStudio Desktop

F05

– 網頁往下滑會有其他版本可選擇

F06

開始的第一步:安裝R語言(3)

– 介面概況

F07

– 可以調整介面字體大小,Tools → Global Options → Appearance → Zoom or Editor font size

F08

– 建立一個Project : New Directory → New Project → 輸入Directory name → 選擇儲存位置 → Create Project

F09

F10

F11

第一節:與電腦交談(1)

– 因此,使用R的第一步,請先將他當作一個高級的計算機。

– 請試著在左邊的Console視窗中,輸入下列程式碼,並體會他的計算功能

# 四則運算
123 + 489
145 * 12

# 括弧優先規則
(1 + 2) * 3

# 指數運算
12^4

第一節:與電腦交談(2)

– 『函數』的使用方式是打下特定的字句,並且在『小括號』內輸入參數作為「input」,接著電腦將會根據你的指令進行回答。

  1. 函數「exp()」:負責進行自然指數運算

  2. 函數「sqrt()」:負責進行平方根運算

  3. 函數「log()」:負責(自然)對數運算

exp(2)
sqrt(10)
log(3)

– 有趣的是,『函數』中的『input』不見得只能有1個,如函數「log()」可以額外輸入對數的底數,並以『,』進行分隔:

log(3, base = 3)
log(4, base = 2)

– 需要注意的是,如果我們不告訴電腦哪個是底數,哪個是運算目標,哪個是底數,那他將會依序認為你輸入的第一個數為需要被運算的數,而第二個數為底數:

log(9, 3)
log(8, 2)

第一節:與電腦交談(3)

– 註:物件的屬性有很多種,我們第二節才會對他進行詳細的介紹

– 注意,等號的右邊為「input」,等號的左邊為「output」

x = 2 * 2 * 3
print(x)

– 如果你只是需要查看物件內容,事實上直接輸入物件名稱也可以達到相同效果

x

– 物件強大的地方在於,我們可以將其做為暫存的工具,並且可以直接對「x」物件進行運算

x/4

第一節:與電腦交談(4)

– 函數「c()」中間以逗點為界,此函數可以將不同「數字」合併在同一個物件內

x = c(1, 2, 3, 4, 5)
x
x^3
x = c(1, 2, 3, 4, 5)
y = c(6, 7, 9, 8, 10)
y - x
x * y

第二節:熟悉R裡面的基本物件(1)

  1. 變數(Variable)層:邏輯(logical)向量、整數(integer)向量、因子(factor)向量、數字(numeric)向量、文字(character)向量

  2. 陣列(Array)層:矩陣(matrix)、資料表(data.frame)

  3. 列表(List)層:列表(list)、S3物件(S3 class)、S4物件(S4 class)

第二節:熟悉R裡面的基本物件(2)

  1. 函數「length()」可以查詢該向量的長度
x = c(1, 2, 3, 4, 5)
length(x)
  1. 函數「array()」可以產生一個陣列
x = 1:24
A = array(x, dim = c(3, 2, 4))
A
  1. 函數「dim()」可以查看該陣列的維度數
dim(A)
length(A)
  1. 函數「list()」可以產生一個列表
L = list(x, A)
L

第二節:熟悉R裡面的基本物件(3)

– 這是變數(Variable)層物件的索引方式

x[3]
x[c(3, 5)]

– 這是陣列(Array)層物件的索引方式

A[3,1,2]
A[3,,]

– 這是列表(List)層物件的索引方式

L[[1]]

– 你也可以交叉使用這些索引函數

L[[2]][3,,]

第二節:熟悉R裡面的基本物件(4)

y = c(6, 7, 9, 8, 10)
y[7] = 3 * 5
y
y[3] = -1
y
y[3] = y[1] + y[2]
y[6] = y[4] * y[5]
y

第二節:熟悉R裡面的基本物件(5)

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)

– 在這裡我們需要兩個物件:物件「x」為儲存費波納奇數列的物件,而物件「indexes」代表著隨迴圈變化的物件

x = c(1, 1)

for (i in 1:20) {
  x[i+2] = x[i] + x[i+1]
}

x
##  [1]     1     1     2     3     5     8    13    21    34    55    89   144
## [13]   233   377   610   987  1597  2584  4181  6765 10946 17711

第三節:迴圈與自訂函數(2)

i = 1
x[i+2] = x[i] + x[i+1]
i = 2
x[i+2] = x[i] + x[i+1]
i = 20
x[i+2] = x[i] + x[i+1]

第三節:迴圈與自訂函數(3)

– 函數「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分"

第三節:迴圈與自訂函數(4)

a = 2
b = 4
step = 20

x = c(a, b)

for (i in 1:step) {
  x[i+2] = x[i] + x[i+1]
}

x
##  [1]     2     4     6    10    16    26    42    68   110   178   288   466
## [13]   754  1220  1974  3194  5168  8362 13530 21892 35422 57314

第三節:迴圈與自訂函數(5)

Fibonacci = function (a, b, step) {
  
  x = c(a, b)
  
  for (i in 1:step) {
    x[i+2] = x[i] + x[i+1]
  }
  
  x
  
}
Fibonacci(2, 4, 20)
##  [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)

F12

– 其數據集包含了150個樣本,都屬於鳶尾屬下的三個亞屬,分別是山鳶尾(setosa)、變色鳶尾(versicolor)和維吉尼亞鳶尾(virginica)。四個特徵被用作樣本的定量分析,它們分別是花萼(sepal)和花瓣(petal)的長度和寬度。

第四節:套件使用與讀寫檔案(2)

iris = read.csv('data/iris.csv')
head(iris)
##   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

第四節:套件使用與讀寫檔案(3)

x = iris[,1]
y = iris[,2]
plot(x, y, xlab = 'Sepal Length', ylab = 'Sepal Width')

model = lm(y~x)
print(model)
## 
## Call:
## lm(formula = y ~ x)
## 
## Coefficients:
## (Intercept)            x  
##     3.41895     -0.06188

第四節:套件使用與讀寫檔案(4)

– 請在這裡下載MNIST的手寫數字資料,並讓我們了解一下這筆資料的結構

– 在這裡我們需要學習如何安裝「套件」,安裝後使用方法如下(你可不可以使用「read.csv」讀取?當然可以,但你可以測試看看速度):

library(data.table)

mnist = fread("data/MNIST.csv", data.table = FALSE)
mnist = data.matrix(mnist)
X = mnist[,-1]
X = t(X)
dim(X) = c(28, 28, 1, dim(mnist)[1])

Y = mnist[,1]

第四節:套件使用與讀寫檔案(5)

library(OpenImageR)

imageShow(X[,,,25])

Y[25]
## [1] 2

第四節:套件使用與讀寫檔案(6)

a = array(1:4, dim = c(2, 2))

a
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
t(a)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4
for (i in 1:dim(X)[4]) {
  X[,,,i] = t(X[,,,i] )
}

第四節:套件使用與讀寫檔案(7)

imageShow(X[,,,25])

第五節:讀取圖像(1)

– 讓我們到這裡下載其中的100張貓以及100張狗,最後再用這個分類器預測裡面貓狗各5張測試圖片。

– 讓我們試著把檔案讀進來,並學會畫圖:

library(OpenImageR)

img <- readImage('Dogs vs. Cats/cat.1.jpg')
imageShow(img)

第五節:套件使用與讀取圖像(2)

dim(img)
## [1] 280 300   3
img[1:5,1:5,1: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

第五節:套件使用與讀取圖像(3)

resized_img = resizeImage(img, 224, 224, method = 'bilinear')
dim(resized_img)
## [1] 224 224   3
imageShow(resized_img)

help(resizeImage)

第五節:套件使用與讀取圖像(4)

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
}
imageShow(cat_img[,,,25])

第五節:套件使用與讀取圖像(5)

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
}
imageShow(dog_img[,,,25])

img_array = array(0, dim = c(224, 224, 3, 200))
img_array[,,,1:100] = cat_img
img_array[,,,101:200] = dog_img

第五節:套件使用與讀取圖像(6)

– 當然是可以的,如果你想保留物件的原始在R內的原始格式,你可以用「save」與「load」進行存取及載入:

save(img_array, file = 'img_array.RData')
load('img_array.RData')
imageShow(img_array[,,,75])

第六節:使用R語言做出網頁應用程式(1)

– 應該還記得怎樣安裝套件吧!

F13

F14

第六節:使用R語言做出網頁應用程式(2)

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")
  )
))

F15

第六節:使用R語言做出網頁應用程式(3)

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)
  })
  
})

F16

第六節:使用R語言做出網頁應用程式(4)

F17

F18

第六節:使用R語言做出網頁應用程式(5)

  1. 使用者自ui.R中的給定一個參數。

  2. 這個參數傳到server.R裡面,使用反應函數進行計算。

  3. 反應完成後,再回傳至ui.R輸出反應結果。

第六節:使用R語言做出網頁應用程式(6)

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")
  )
))
  1. headerPanel()用來定義網頁標題

  2. sidebarPanel()用來定義的控制選單內含哪些可控參數,本例中只有一個滑動輸入元件sliderInput(),元件為obs

  3. mainPanle()則是用來定義輸出區域的輸出結果,本例中只有一個圖片輸出元件plotOutput(),元件為distPlot

F19

第六節:使用R語言做出網頁應用程式(7)

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)
        
    })

})

Note:所有的輸入元件都存取在input這個List內;而所有的輸出元件都存取在output這個List內。

小結

– 但要注意一點,僅有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")

– 安裝完成後,用這個語法確認是否有成功!

library(mxnet)