# NOT RUN {
if (require("randomForest")) {
# First we fit a machine learning model on the Boston housing data
data("Boston", package = "MASS")
rf = randomForest(medv ~ ., data = Boston, ntree = 50)
X = Boston[-which(names(Boston) == "medv")]
mod = Predictor$new(rf, data = X)
# Then we explain the first instance of the dataset with the Shapley method:
x.interest = X[1,]
shapley = Shapley$new(mod, x.interest = x.interest)
shapley
# Look at the results in a table
shapley$results
# Or as a plot
plot(shapley)
# Explain another instance
shapley$explain(X[2,])
plot(shapley)
# Shapley() also works with multiclass classification
rf = randomForest(Species ~ ., data= iris, ntree=50)
X = iris[-which(names(iris) == "Species")]
predict.fun = function(object, newdata) predict(object, newdata, type = "prob")
mod = Predictor$new(rf, data = X, predict.fun = predict.fun)
# Then we explain the first instance of the dataset with the Shapley() method:
shapley = Shapley$new(mod, x.interest = X[1,])
shapley$results
plot(shapley)
# You can also focus on one class
mod = Predictor$new(rf, data = X, predict.fun = predict.fun, class = "setosa")
shapley = Shapley$new(mod, x.interest = X[1,])
shapley$results
plot(shapley)
}
# }
Run the code above in your browser using DataLab