library(cairoDevice) drawMatrix <- function(x) { image(matrix(x,16,16)[,16:1],col=rev(gray((0:100)/100)),xaxt="n",yaxt="n",xlab="",ylab="",bty="n") } drawImage <- function() { img <- matrix(0,16,16) if (!is.null(coords)) { coordsI <- ceiling(coords) coordsI[coordsI > 16] <- 16 coordsI[coordsI < 1] <- 1 coordsI[,2] <- 17-coordsI[,2] counts <- table(coordsI[,1],coordsI[,2]) img <- matrix(0,16,16) img[as.numeric(rownames(counts)), as.numeric(colnames(counts))] <- counts mx <- max(img) mn <- min(img) img <- (img-mn) / (mx-mn) * 2 - 1 } drawMatrix(img) img } plotEmpty <- function(a=0,b=1) { plot(c(a,b),c(a,b),type="n",bty="n",xaxt="n",yaxt="n",xlab="",ylab="") } processAndClassify <- function() { dev.set(which=dev.next()) x <- t(matrix(drawImage())) probs <- useNNLogReg(nnet,matrix(x,nrow=1),probs=TRUE) ### make bar plot with probs ### draw digit that is class label of x dev.set(which=dev.next()) } ###################################################################### #### Read zip code data. #### Train neural net to make nnet x11(type="Xlib",width=3,height=3) Cairo(width=2,height=2) ## for drawing par(mar=c(0,0,0,0)) coords <- NULL drawingG <- FALSE plotEmpty(0,16) getGraphicsEvent("Hold left down to draw. Click right to restart. Middle to stop.", onMouseDown = function(buttons,x,y) { if (buttons == 0) { drawingG <<- TRUE NULL } else if (buttons == 2) { coords <<- NULL plotEmpty(0,16) NULL } else if (buttons == 1) { return(TRUE) } }, onMouseUp = function(buttons,x,y) { drawingG <<- FALSE processAndClassify() NULL }, onMouseMove = function(buttons,x,y) { if (drawingG) { px <- grconvertX(x, "ndc", "user") py <- grconvertY(y, "ndc", "user") coords <<- rbind(coords,c(px,py)) points(px,py,pch=19,cex=3) if (nrow(coords) %% 100 == 0) { processAndClassify() } } NULL })