resmooth {drape} | R Documentation |
Resmooth the predictions of a fitted model
Description
Smooth the predictions of a fitted model by convolving them with a Gaussian kernel along the d'th covariate.
Usage
resmooth(
fit,
X,
d = 1,
bw = exp(seq(-1, 1))/(2 * sqrt(3)) * stats::sd(X[, d]),
n_points = 101,
sd_trim = 5
)
Arguments
fit |
a prediction function taking matrix input and returning a vector. |
X |
matrix of covariates. |
d |
integer index of covariate to be smoothed along. |
bw |
vector of bandwidths for the Gaussian kernel. |
n_points |
integer number of gridpoints to be used for convolution. |
sd_trim |
float number of standard deviations at which to trim the Gaussian distribution. |
Value
List with the following elements. A list "pred" of the same length as "bw". Each element is a vector of predictions which are smooth with respect to the dth column of X, with smoothness corresponding to the respective element of "bw". A similar list "deriv" of corresponding vectors of first derivatives. Vectors "gridpoints" and "prob_weights" of equally spaced gridpoints and corresponding normal density weights. Vector "bw" of bandwidths used.
Examples
# Single bandwidth
X <- matrix(seq(-2,2,by=0.05))
fit <- function(Y){1*(rowMeans(Y)<0)}
sm <- resmooth(fit=fit, X=X, d=1, bw=0.2)
sm$pred[[1]]
# Multiple bandwidths simultaneously
X <- matrix(stats::rnorm(200), ncol=2)
y <- X[,1] + sin(X[,2]) + 0.5 * stats::rnorm(nrow(X))
df <- data.frame(y,X)
lm1 <- stats::lm(y~X1+sin(X2), data=df)
fit <- function(Y){as.vector(stats::predict(lm1, newdata=data.frame(Y)))}
resmooth(fit=fit, X=X, d=2)