神經(jīng)網(wǎng)絡(luò)模型+進階

PART I 神經(jīng)網(wǎng)絡(luò)模型
  1. 模擬數(shù)據(jù)
set.seed(888)
x1 <- rnorm(1000,0)
set.seed(666)
x2 <- rnorm(1000,0)

logit1 <- 2+3*x1+x1^2-4*x2
logit2 <- 1.5+2*x1-3*x2^2+x2

Denominator <- 1+exp(logit1)+exp(logit2) 
#denominator for probability calculation
vProb <- cbind(1/Denominator,exp(logit1)/Denominator,exp(logit2)/Denominator) 
#calculating the matrix of probabilities for there choices

mChoices <- t(apply(vProb,1,rmultinom,n=1,size=1)) 
#Assigning value 1 to maximum probability and 0 for the rest to get the appropriate choices for the combinations of x1 and x2
data <- cbind.data.frame(y=as.factor(apply(mChoices,1,function(x)which(x==1))),x1,x2) 
#response variable and predictors x1 and x2 and combined together

str(data)
# 'data.frame': 1000 obs. of  3 variables:
#   $ y : Factor w/ 3 levels "1","2","3": 1 1 2 1 2 3 2 2 2 2 ...
# $ x1: num  -1.951 -1.544 0.73 -0.278 -1.656 ...
# $ x2: num  0.753 2.014 -0.355 2.028 -2.217 ...
  1. 查看模擬數(shù)據(jù)
library(ggplot2)
qplot(x1,x2,data=data,geom="point",color=y)
image.png
  1. 神經(jīng)網(wǎng)絡(luò)模型訓(xùn)練
library(nnet)
train <- data[1:700,]
test <- data[701:1000,]
annmod <- nnet(y~x1+x2,train,size=6)
# # weights:  39
# initial  value 1106.979671 
# iter  10 value 325.827182
# iter  20 value 291.472800
# iter  30 value 284.906627
# iter  40 value 282.896526
# iter  50 value 281.619506
# iter  60 value 281.353716
# iter  70 value 280.478852
# iter  80 value 280.026634
# iter  90 value 279.878004
# iter 100 value 278.301294
# final  value 278.301294 
# stopped after 100 iterations

annmod
# a 2-6-3 network with 39 weights
# inputs: x1 x2 
# output(s): y 
# options were - softmax modelling
  1. 可視化訓(xùn)練結(jié)果
library(devtools)

source_url('https://gist.github.com/fawda123/7471137/raw/cd6e6a0b0bdb4e065c597e52165e5ac887f5fe95/nnet_plot_update.r')
plot.nnet(annmod,alpha.val=0.5,pos.col ="green",neg.col="red")
image.png
  1. 神經(jīng)網(wǎng)絡(luò)模型結(jié)果評估
pred <- predict(annmod,test[,-1],type = "class")
table(test[,1],pred)
# pred
#    1   2   3
# 1  45  13   9
# 2   5 163  15
# 3  12  15  23
  1. 平均準(zhǔn)確度(average accuracy)
accuracyCal <- function(N){
  accuracy <- 1
  for (x in 1:N){
    annmod <-nnet(y~.,data = train,size =x,trace = FALSE,maxit=200)
    pred <- predict(annmod,test[,-1],type = "class")
    table <- table(test[,1],pred)
    if (ncol(table)==3){
      table <- table
    }
    else{
      table <- cbind(table,c(0,0,0))
    }
    tp1 <- table[1,1]
    tp2 <- table[2,2]
    tp3 <- table[3,3]
    tn1 <- table[2,2]+table[2,3]+table[3,2]+table[3,3]
    tn2 <- table[1,1]+table[1,3]+table[3,1]+table[3,3]
    tn3 <- table[1,1]+table[1,2]+table[2,1]+table[2,2]
    fn1 <- table[1,2]+table[1,3]
    fn2 <- table[2,1]+table[2,3]
    fn3 <- table[3,1]+table[3,2]
    fp1 <- table[2,1]+table[3,1]
    fp2 <- table[1,2]+table[3,2]
    fp3 <- table[1,3]+table[2,3]
    accuracy <- c(accuracy,(((tp1+tn1/(tp1+fn1+fp1+tn1))+(tp2+tn2)/(tp2+fn2+fp2+tn2))+((tp3+tn3)/(tp3+fn3+fp3+tn3)))/3)}
  return(accuracy[-1])
}

accuracySeri <- accuracyCal(30)

plot(accuracySeri,type = "b",xlab = "Number of units in the hidden layer.",
     ylab = "Average Accuracy")
image.png
  1. 與廣義線性模型比較
model.lin <- multinom(y~.,train)
pred.lin <- predict(model.lin,test[,-1])
table <- table(test[,1],pred.lin)
table
# pred.lin
#    1   2   3
# 1  51  14   2
# 2  12 168   3
# 3  17  31   2

tp1 <- table[1,1]
tp2 <- table[2,2]
tp3 <- table[3,3]
tn1 <- table[2,2]+table[2,3]+table[3,2]+table[3,3]
tn2 <- table[1,1]+table[1,3]+table[3,1]+table[3,3]
tn3 <- table[1,1]+table[1,2]+table[2,1]+table[2,2]
fn1 <- table[1,2]+table[1,3]
fn2 <- table[2,1]+table[2,3]
fn3 <- table[3,1]+table[3,2]
fp1 <- table[2,1]+table[3,1]
fp2 <- table[1,2]+table[3,2]
fp3 <- table[1,3]+table[2,3]

accuracy <- (((tp1+tn1)/(tp1+fn1+fp1+tn1))+((tp2+tn2)/(tp2+fn2+fp2+tn2))+((tp3+tn3)/(tp3+fn3+fp3+tn3)))/3

accuracy
# [1] 0.8244444
PART II 神經(jīng)網(wǎng)絡(luò)模型進階
  1. 導(dǎo)入練習(xí)數(shù)據(jù)
library(MASS)
data(birthwt)
str(birthwt)

# 'data.frame': 189 obs. of  10 variables:
#   $ low  : int  0 0 0 0 0 0 0 0 0 0 ...
# $ age  : int  19 33 20 21 18 21 22 17 29 26 ...
# $ lwt  : int  182 155 105 108 107 124 118 103 123 113 ...
# $ race : int  2 3 1 1 1 3 1 3 1 1 ...
# $ smoke: int  0 0 1 1 1 0 0 0 1 1 ...
# $ ptl  : int  0 0 0 0 0 0 0 0 0 0 ...
# $ ht   : int  0 0 0 0 0 0 0 0 0 0 ...
# $ ui   : int  1 0 0 1 1 0 0 0 0 0 ...
# $ ftv  : int  0 3 1 2 0 0 1 1 1 0 ...
# $ bwt  : int  2523 2551 2557 2594 2600 2622 2637 2637 2663 2665 ...
image.png
  1. 訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型
library(neuralnet)

nn <- neuralnet(low ~ age+lwt+race+smoke+ptl+ht+ui+ftv,data = birthwt,hidden = 2,err.fct = "ce",
                linear.output =FALSE)
plot(nn)
image.png

Error function 用于描述預(yù)測結(jié)果與觀察結(jié)果的差別,差別越大說明模型越差溃睹。
開始時模型隨機選取一個權(quán)重(隨機模型)纸颜,獲得預(yù)測結(jié)果后與實際觀測值比較,比較后再進行調(diào)整權(quán)重奶镶,如此反復(fù)直至獲得最佳模型迟赃。

  1. Generalized weights: 各個變量對模型的貢獻(重要程度)
nn.limited <- neuralnet(
  low ~ age+lwt+race+smoke,
  data = birthwt,hidden = 4,err.fct = "ce",
  linear.output = FALSE)

plot(nn.limited)
image.png
par(mfrow = c(2,2))
gwplot(nn.limited,selected.covariate = "age")
gwplot(nn.limited,selected.covariate = "lwt")
gwplot(nn.limited,selected.covariate = "race")
gwplot(nn.limited,selected.covariate = "smoke")

# 在windows系統(tǒng)里會出現(xiàn)以下報錯
# Error in plot.window(...) : need finite 'ylim' values
image.png
  1. 模型預(yù)測
new.mother <- matrix(c(23,105,3,1,26,111,2,0,31,125,2,1,35,136,1,0),
                     byrow = TRUE,ncol = 4)
new.mother
#       [,1] [,2] [,3] [,4]
# [1,]   23  105    3    1
# [2,]   26  111    2    0
# [3,]   31  125    2    1
# [4,]   35  136    1    0

pred <- compute(nn.limited,new.mother)
pred$net.result
#        [,1]
# [1,] 0.39809269
# [2,] 0.39809269
# [3,] 0.39809269
# [4,] 0.05554679

參考資料
章仲恒教授丁香園課程:神經(jīng)網(wǎng)絡(luò)模型神經(jīng)網(wǎng)絡(luò)模型進階

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市厂镇,隨后出現(xiàn)的幾起案子纤壁,更是在濱河造成了極大的恐慌,老刑警劉巖捺信,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酌媒,死亡現(xiàn)場離奇詭異,居然都是意外死亡迄靠,警方通過查閱死者的電腦和手機秒咨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來掌挚,“玉大人雨席,你說我怎么就攤上這事∫叻蹋” “怎么了舅世?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長奇徒。 經(jīng)常有香客問我雏亚,道長,這世上最難降的妖魔是什么摩钙? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任罢低,我火速辦了婚禮,結(jié)果婚禮上胖笛,老公的妹妹穿的比我還像新娘网持。我一直安慰自己,他們只是感情好长踊,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布功舀。 她就那樣靜靜地躺著,像睡著了一般身弊。 火紅的嫁衣襯著肌膚如雪辟汰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天阱佛,我揣著相機與錄音帖汞,去河邊找鬼。 笑死凑术,一個胖子當(dāng)著我的面吹牛翩蘸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播淮逊,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼催首,長吁一口氣:“原來是場噩夢啊……” “哼扶踊!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起翅帜,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤姻檀,失蹤者是張志新(化名)和其女友劉穎命满,沒想到半個月后涝滴,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡胶台,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年歼疮,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片诈唬。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡韩脏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出铸磅,到底是詐尸還是另有隱情赡矢,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布阅仔,位于F島的核電站吹散,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏八酒。R本人自食惡果不足惜空民,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望羞迷。 院中可真熱鬧界轩,春花似錦、人聲如沸衔瓮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽热鞍。三九已至葫慎,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間碍现,已是汗流浹背幅疼。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留昼接,地道東北人爽篷。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像慢睡,于是被迫代替她去往敵國和親逐工。 傳聞我的和親對象是個殘疾皇子铡溪,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360