Page 1 of 1

T03: Imputación de valores faltantes

Posted: Fri Oct 04, 2019 8:49 am
by AntonioG

Code: Select all

install.packages("DMwR")  # for use of knnImputation.
require(DMwR)

x1<-3*rnorm(100)
x2<-round(abs(x1),2)
y2<-x2
y2[sample(1:100,25)]<-NA
M<-cbind(x1,y2)
sum(complete.cases(M))
https://en.wikipedia.org/wiki/Imputation_(statistics)

Code: Select all

#Central inputation
M1 <- centralImputation(M)
plot(x1,x2,type="p",pch=19)
plot(M1[,1],M1[,2],type="p",pch=19)
cbind(x1,y2,M1[,2])

Code: Select all

#knn imputation
M<-cbind(x1,x1,y2)
sum(complete.cases(M))

M2 <- knnImputation(M, 3)
plot(x1,x2,type="p",pch=19)
plot(M2[,1],M2[,3],type="p",pch=19)
Ind<-is.na(y2)
points(M2[Ind,1],M2[Ind,3],pch=19,col="red")

cbind(x1,y2,M2[,3])

Completar valores de píxeles faltantes

Posted: Fri Oct 04, 2019 8:51 am
by AntonioG

Code: Select all

library(jpeg)
library(DMwR)

plotIm<-function(x){
   x<-(x-min(x,na.rm=TRUE))/(max(x,na.rm=TRUE)-min(x,na.rm=TRUE))
   nr<-dim(x)[1]
   nc<-dim(x)[2]
   par(mai=c(0,0,0,0))
   plot(c(1,nc),c(1,nr), type='n', axes = FALSE, xlab = "", ylab = "")
   rasterImage(x, 0, 0, nc, nr,interpolate=FALSE)
   }

x<-readJPEG(file.choose())
Im<-x[,,1]
plotIm(Im)

nr<-dim(Im)[1]
nc<-dim(Im)[2]

rr<-sample(1:nr,nr*nc*0.10,replace = TRUE)
rc<-sample(1:nc,nr*nc*0.10,replace = TRUE)
Im[cbind(rr,rc)]<-NA

#rr<-sample(1:nr,nr*0.10,replace = TRUE)
#Im[rr,]<-NA

plotIm(Im)
par(bg="blue")
plotIm(Im)

w<-1
M<-rep(0,(2*w+1)^2)

for(i in 1:nr)
for(j in 1:nc){
   v<-rep(0,(2*w+1)^2)
   v[1]<-Im[i,j]
   k<-2
   for(k1 in (-w):w)
   for(k2 in (-w):w){
      if(k1==0 & k2==0) next
      if(i+k1>=1 & i+k1<=nr & k2+j>=1 & j+k2<=nc)
         v[k]<-Im[i+k1,j+k2]
      else
        v[k]<-NA
      k<-k+1
      }
   M<-rbind(M,v)
   }
M<-M[-1,]

M2 <- knnImputation(M, 3)

Im2<-matrix(M2[,1],nrow=nr,byrow=TRUE)
plotIm(cbind(Im,Im2))