library(keras)
library(BiocManager)
library(imager)
## Loading required package: magrittr
## 
## Attaching package: 'imager'
## The following object is masked from 'package:magrittr':
## 
##     add
## The following objects are masked from 'package:stats':
## 
##     convolve, spectrum
## The following object is masked from 'package:graphics':
## 
##     frame
## The following object is masked from 'package:base':
## 
##     save.image
library(EBImage)
## 
## Attaching package: 'EBImage'
## The following objects are masked from 'package:imager':
## 
##     channel, dilate, display, erode, resize, watershed
library(tensorflow)
setwd('/Users/chipindulovemore/Documents')
pics<-c('cob_1.PNG','cob_2.PNG','cob_3.PNG','cob_4.PNG','cob_5.PNG','cob_6.PNG','cob_7.PNG','cob_8.PNG','cob_9.PNG','cob_10.PNG','cob_11.PNG','cob_12.PNG')

mypic<-list()
for(i in 1:12) {mypic[[i]]<-readImage(pics[i])}
print(mypic[[1]])
## Image 
##   colorMode    : Color 
##   storage.mode : double 
##   dim          : 209 629 4 
##   frames.total : 4 
##   frames.render: 1 
## 
## imageData(object)[1:5,1:6,1]
##           [,1]       [,2]      [,3]       [,4]      [,5]       [,6]
## [1,] 0.1568627 0.14117647 0.1960784 0.03921569 0.1215686 0.06274510
## [2,] 0.1960784 0.10980392 0.2078431 0.04313725 0.1803922 0.08235294
## [3,] 0.1372549 0.09019608 0.1725490 0.09411765 0.1960784 0.10980392
## [4,] 0.1607843 0.12941176 0.1137255 0.25490196 0.2235294 0.21176471
## [5,] 0.1333333 0.14509804 0.1019608 0.32156863 0.2156863 0.25490196
print(mypic[[8]])
## Image 
##   colorMode    : Color 
##   storage.mode : double 
##   dim          : 491 137 4 
##   frames.total : 4 
##   frames.render: 1 
## 
## imageData(object)[1:5,1:6,1]
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
## [1,] 0.8549020 0.8588235 0.8705882 0.8627451 0.8823529 0.8784314
## [2,] 0.8588235 0.8509804 0.8509804 0.8588235 0.8588235 0.8549020
## [3,] 0.8549020 0.8431373 0.8313725 0.8392157 0.8470588 0.8431373
## [4,] 0.8274510 0.8117647 0.8078431 0.8196078 0.8117647 0.8117647
## [5,] 0.8039216 0.8000000 0.8000000 0.7960784 0.8000000 0.8000000
hist(mypic[[8]])

display(mypic[[1]])

hist(mypic[[1]])

str(mypic)
## List of 12
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:209, 1:629, 1:4] 0.157 0.196 0.137 0.161 0.133 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:184, 1:473, 1:4] 0.0706 0.0627 0.0667 0.0784 0.098 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:212, 1:505, 1:4] 0.0392 0.0392 0.051 0.051 0.0627 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:181, 1:605, 1:4] 0.102 0.102 0.102 0.0863 0.0863 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:221, 1:696, 1:4] 0.0941 0.098 0.1255 0.1451 0.1686 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:197, 1:615, 1:4] 0.169 0.212 0.133 0.125 0.129 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:187, 1:523, 1:4] 0.0431 0.0275 0.0235 0.0235 0.0196 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:491, 1:137, 1:4] 0.855 0.859 0.855 0.827 0.804 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:408, 1:141, 1:4] 0.0745 0.0431 0.0431 0.1843 0.0745 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:520, 1:127, 1:4] 0.1059 0.0627 0.0471 0.051 0.0863 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:169, 1:620, 1:4] 0.0431 0.0588 0.0471 0.051 0.0471 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:215, 1:657, 1:4] 0.098 0.102 0.1098 0.0941 0.098 ...
##   .. ..@ colormode: int 2
display(mypic[[1]])

print(mypic[[1]])
## Image 
##   colorMode    : Color 
##   storage.mode : double 
##   dim          : 209 629 4 
##   frames.total : 4 
##   frames.render: 1 
## 
## imageData(object)[1:5,1:6,1]
##           [,1]       [,2]      [,3]       [,4]      [,5]       [,6]
## [1,] 0.1568627 0.14117647 0.1960784 0.03921569 0.1215686 0.06274510
## [2,] 0.1960784 0.10980392 0.2078431 0.04313725 0.1803922 0.08235294
## [3,] 0.1372549 0.09019608 0.1725490 0.09411765 0.1960784 0.10980392
## [4,] 0.1607843 0.12941176 0.1137255 0.25490196 0.2235294 0.21176471
## [5,] 0.1333333 0.14509804 0.1019608 0.32156863 0.2156863 0.25490196
display(mypic[[3]])

summary(mypic[[1]])
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.0000  0.2706  0.6471  0.5949  1.0000  1.0000
hist((mypic[[1]]))

str(mypic)
## List of 12
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:209, 1:629, 1:4] 0.157 0.196 0.137 0.161 0.133 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:184, 1:473, 1:4] 0.0706 0.0627 0.0667 0.0784 0.098 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:212, 1:505, 1:4] 0.0392 0.0392 0.051 0.051 0.0627 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:181, 1:605, 1:4] 0.102 0.102 0.102 0.0863 0.0863 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:221, 1:696, 1:4] 0.0941 0.098 0.1255 0.1451 0.1686 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:197, 1:615, 1:4] 0.169 0.212 0.133 0.125 0.129 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:187, 1:523, 1:4] 0.0431 0.0275 0.0235 0.0235 0.0196 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:491, 1:137, 1:4] 0.855 0.859 0.855 0.827 0.804 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:408, 1:141, 1:4] 0.0745 0.0431 0.0431 0.1843 0.0745 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:520, 1:127, 1:4] 0.1059 0.0627 0.0471 0.051 0.0863 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:169, 1:620, 1:4] 0.0431 0.0588 0.0471 0.051 0.0471 ...
##   .. ..@ colormode: int 2
##  $ :Formal class 'Image' [package "EBImage"] with 2 slots
##   .. ..@ .Data    : num [1:215, 1:657, 1:4] 0.098 0.102 0.1098 0.0941 0.098 ...
##   .. ..@ colormode: int 2
####Row Bind # converting the data set into one
trainx<-NULL
for(i in 1:5){trainx<-rbind(trainx,mypic[[i]])}## using the first five images of perfect maize cob (no abortion)
## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)

## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)

## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)

## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)
str(trainx) # stracture of train x (no abortion)
##  num [1:5, 1:525844] 0.1569 0.0706 0.0392 0.102 0.0941 ...
## they are 12 pic , 6 no abortion and 6 abortions
## 5 pics will be used for training 
## 6th pic will be used to test also the 12 th of abortions

for(i in 7:11){trainx<-rbind(trainx,mypic[[i]])}## using the first five images with abortion
## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)

## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)

## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)

## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)

## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 2)
str(trainx) # stracture of train x (abortion)
##  num [1:10, 1:525844] 0.1569 0.0706 0.0392 0.102 0.0941 ...
## test pic
testx<-rbind(mypic[[6]],mypic[[12]]) # 6th no abortion ,12th abortion
## Warning in rbind2(argl[[i]], r): number of columns of result is not a
## multiple of vector length (arg 1)
trainy<-c(0,0,0,0,0,1,1,1,1,1) # 0=no abortion and 1 = abortion
testy<-c(0,1) # 0= 6 and 1=12  that is no abortion and abortion respectively
## One hot Encoding
trainLabels<-to_categorical(trainy)
testLabels<-to_categorical(testy)  # using tensorflow backened
trainLabels ### print
##       [,1] [,2]
##  [1,]    1    0
##  [2,]    1    0
##  [3,]    1    0
##  [4,]    1    0
##  [5,]    1    0
##  [6,]    0    1
##  [7,]    0    1
##  [8,]    0    1
##  [9,]    0    1
## [10,]    0    1
testLabels ### print
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1
##Model 
model<-keras_model_sequential()
model %>%     ## the operator passes the command to the next line
         layer_dense(units=256,activation ='relu',input_shape= c(525844)) %>%  
         layer_dense(units=128,activation='relu') %>%
          layer_dense (units=2, activation = 'softmax')

summary (model)
## Model: "sequential"
## ___________________________________________________________________________
## Layer (type)                     Output Shape                  Param #     
## ===========================================================================
## dense (Dense)                    (None, 256)                   134616320   
## ___________________________________________________________________________
## dense_1 (Dense)                  (None, 128)                   32896       
## ___________________________________________________________________________
## dense_2 (Dense)                  (None, 2)                     258         
## ===========================================================================
## Total params: 134,649,474
## Trainable params: 134,649,474
## Non-trainable params: 0
## ___________________________________________________________________________
#### compiling the model
model%>%
       compile (loss='binary_crossentropy',
               optimizer=optimizer_rmsprop(),
               metrics=c('accuracy'))
# fit the model

history<-model%>%
         fit(trainx,
             trainLabels,
             epochs=30,
             batch_size=32,
             validation_split=0.3)
plot(history)

####
## Evaluation and pediction-train-data

model %>% evaluate (trainx,trainLabels)
## $loss
## [1] 7.689546
## 
## $acc
## [1] 0.5
pred<-model %>% predict_classes(trainx)
table(Predicted=pred,Actual=trainy) ### confusion matrix
##          Actual
## Predicted 0 1
##         0 5 5
prob <-model%>% predict_proba(trainx)  ###   computing probabilities of belonging to a class

cbind(prob,Predicted=pred,Actual=trainy) ## combining probabilities
##           Predicted Actual
##  [1,] 1 0         0      0
##  [2,] 1 0         0      0
##  [3,] 1 0         0      0
##  [4,] 1 0         0      0
##  [5,] 1 0         0      0
##  [6,] 1 0         0      1
##  [7,] 1 0         0      1
##  [8,] 1 0         0      1
##  [9,] 1 0         0      1
## [10,] 1 0         0      1