local interpretable model-凯发k8网页登录
local interpretable model-agnostic explanations (lime)
since r2020b
description
lime explains a prediction of a machine learning model (classification or regression) for a query point by finding important predictors and fitting a simple interpretable model.
you can create a lime
object for a machine learning model with a
specified query point (querypoint
) and a specified number of important
predictors (numimportantpredictors
). the software generates a synthetic
data set, and fits a simple interpretable model of important predictors that effectively
explains the predictions for the synthetic data around the query point. the simple model can
be a linear model (default) or decision tree model.
use the fitted simple model to explain a prediction of the machine learning model locally,
at the specified query point. use the plot
function to
visualize the lime results. based on the local explanations, you can decide whether or not to
trust the machine learning model.
fit a new simple model for another query point by using the fit
function.
creation
syntax
description
creates the results
= lime(blackbox
)lime
object results
using the machine
learning model object blackbox
, which contains predictor data. the
lime
function generates samples of a synthetic predictor data set
and computes the predictions for the samples. to fit a simple model, use the fit
function
with results
.
creates a results
= lime(blackbox
,'customsyntheticdata',customsyntheticdata
)lime
object using the pregenerated, custom synthetic
predictor data set customsyntheticdata
. the
lime
function computes the predictions for the samples in
customsyntheticdata
.
also finds the specified number of important predictors and fits a linear simple model
for the query point results
= lime(___,'querypoint',querypoint
,'numimportantpredictors',numimportantpredictors
)querypoint
. you can specify
querypoint
and numimportantpredictors
in
addition to any of the input argument combinations in the previous syntaxes.
specifies additional options using one or more name-value arguments. for example,
results
= lime(___,name,value
)'simplemodeltype','tree'
specifies the type of simple model as a
decision tree model.
input arguments
blackbox
— machine learning model to be interpreted
regression model object | classification model object | function handle
machine learning model to be interpreted, specified as a full or compact regression or classification model object or a function handle.
full or compact model object — you can specify a full or compact regression or classification model object, which has a
predict
object function. the software uses thepredict
function to compute the predictions for the query point and the synthetic predictor data set.if you specify a model object that does not contain predictor data (for example, a compact model), then you must provide predictor data using
x
orcustomsyntheticdata
.lime
does not support a model object trained with a sparse matrix. when you train a model, use a full numeric matrix or table for the predictor data where rows correspond to individual observations.
regression model object
supported model full or compact regression model object ensemble of regression models , regressionbaggedensemble
,gaussian kernel regression model using random feature expansion gaussian process regression regressiongp
,generalized additive model , linear regression for high-dimensional data regressionlinear
neural network regression model , regression tree regressiontree
,compactregressiontree
support vector machine regression regressionsvm
,compactregressionsvm
classification model object
supported model full or compact classification model object binary decision tree for multiclass classification , compactclassificationtree
discriminant analysis classifier , ensemble of learners for classification , , gaussian kernel classification model using random feature expansion classificationkernel
generalized additive model , k-nearest neighbor model classificationknn
linear classification model classificationlinear
multiclass model for support vector machines or other classifiers classificationecoc
,compactclassificationecoc
naive bayes model , compactclassificationnaivebayes
neural network classifier , support vector machine for binary classification classificationsvm
,compactclassificationsvm
function handle — you can specify a function handle that accepts predictor data and returns a column vector containing a prediction for each observation in the predictor data. the prediction is a predicted response for regression or a classified label for classification. you must provide the predictor data using
x
orcustomsyntheticdata
and specify the'type'
name-value argument.
x
— predictor data
numeric matrix | table
predictor data, specified as a numeric matrix or table. each row of
x
corresponds to one observation, and each column corresponds
to one variable.
x
must be consistent with the predictor data that trained
blackbox
,
stored in blackbox.x
. the specified value must not contain a
response variable.
x
must have the same data types as the predictor variables (for example,trainx
) that trainedblackbox
. the variables that make up the columns ofx
must have the same number and order as intrainx
.if you train
blackbox
using a numeric matrix, thenx
must be a numeric matrix.if you train
blackbox
using a table, thenx
must be a table. all predictor variables inx
must have the same variable names and data types as intrainx
.
lime
does not support a sparse matrix.
if blackbox
is a model object that does not contain predictor
data or a function handle, you must provide x
or customsyntheticdata
. if blackbox
is a full machine
learning model object and you specify this argument, then lime
does not use the predictor data in blackbox
. it uses the
specified predictor data only.
data types: single
| double
| table
customsyntheticdata
— pregenerated, custom synthetic predictor data set
[]
(default) | numeric matrix | table
pregenerated, custom synthetic predictor data set, specified as a numeric matrix or table.
if you provide a pregenerated data set, then lime
uses the
provided data set instead of generating a new synthetic predictor data set.
customsyntheticdata
must be consistent with the predictor
data that trained blackbox
,
stored in blackbox.x
. the specified value must not contain a
response variable.
customsyntheticdata
must have the same data types as the predictor variables (for example,trainx
) that trainedblackbox
. the variables that make up the columns ofcustomsyntheticdata
must have the same number and order as intrainx
if you train
blackbox
using a numeric matrix, thencustomsyntheticdata
must be a numeric matrix.if you train
blackbox
using a table, thencustomsyntheticdata
must be a table. all predictor variables incustomsyntheticdata
must have the same variable names and data types as intrainx
.
lime
does not support a sparse matrix.
if blackbox
is a model object that does not contain predictor
data or a function handle, you must provide x
or
customsyntheticdata
. if blackbox
is a full
machine learning model object and you specify this argument, then
lime
does not use the predictor data in
blackbox
; it uses the specified predictor data only.
data types: single
| double
| table
querypoint
— query point
row vector of numeric values | single-row table
query point at which lime
explains a prediction, specified as
a row vector of numeric values or a single-row table. querypoint
must have the same data type and number of columns as x
,
customsyntheticdata
, or the predictor data in blackbox
.
if you specify numimportantpredictors
and querypoint
, then the
lime
function fits a simple model when creating a
lime
object.
querypoint
must not contain missing values.
example: blackbox.x(1,:)
specifies the query point as the first
observation of the predictor data in the full machine learning model
blackbox
.
data types: single
| double
| table
numimportantpredictors
— number of important predictors to use in simple model
positive integer scalar value
number of important predictors to use in the simple model, specified as a positive integer scalar value.
if
'simplemodeltype'
is'linear'
(default), then the software selects the specified number of important predictors and fits a linear model of the selected predictors.if
'simplemodeltype'
is'tree'
, then the software specifies the maximum number of decision splits (or branch nodes) as the number of important predictors so that the fitted decision tree uses at most the specified number of predictors.
if you specify numimportantpredictors
and querypoint
,
then the lime
function fits a simple model when creating a
lime
object.
data types: single
| double
specify optional pairs of arguments as
name1=value1,...,namen=valuen
, where name
is
the argument name and value
is the corresponding value.
name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
before r2021a, use commas to separate each name and value, and enclose
name
in quotes.
example:
specifies the query point as lime
(blackbox
,'querypoint'
,q,'numimportantpredictors'
,n,'simplemodeltype','tree')q
, the number of important predictors to
use for the simple model as n
, and the type of simple model as a
decision tree model. lime
generates samples of a synthetic predictor
data set, computes the predictions for the samples, and fits a decision tree model for the
query point using at most the specified number of predictors.
datalocality
— locality of synthetic data for data generation
'global'
(default) | 'local'
locality of the synthetic data for data generation, specified as the
comma-separated pair consisting of 'datalocality'
and
'global'
or 'local'
.
'global'
— the software estimates distribution parameters using the whole predictor data set (x
or the predictor data inblackbox
). the software generates a synthetic predictor data set with the estimated parameters and uses the data set for simple model fitting of any query point.'local'
— the software estimates the distribution parameters using the k-nearest neighbors of a query point, where k is the'numneighbors'
value. the software generates a new synthetic predictor data set each time it fits a simple model for the specified query point.
for more details, see lime.
example: 'datalocality','local'
data types: char
| string
numneighbors
— number of neighbors of query point
1500 (default) | positive integer scalar value
number of neighbors of the query point, specified as the comma-separated pair
consisting of 'numneighbors'
and a positive integer scalar
value. this argument is valid only when 'datalocality'
is 'local'
.
if you specify a value larger than the number of observations in the predictor
data set (x
or the
predictor data in blackbox
), then lime
uses all observations.
example: 'numneighbors',2000
data types: single
| double
numsyntheticdata
— number of samples to generate for synthetic data set
5000 (default) | positive integer scalar value
number of samples to generate for the synthetic data set, specified as the
comma-separated pair consisting of 'numsyntheticdata'
and a
positive integer scalar value.
example: 'numsyntheticdata',2500
data types: single
| double
kernelwidth
— kernel width
0.75 (default) | numeric scalar value
kernel width of the squared exponential (or gaussian) kernel function, specified as the comma-separated pair consisting of 'kernelwidth'
and a numeric scalar value.
the lime
function computes distances between the query point and
the samples in the synthetic predictor data set, and then converts the distances to weights
by using the squared exponential kernel function. if you lower the
'kernelwidth'
value, then lime
uses
weights that are more focused on the samples near the query point. for details, see lime.
example: 'kernelwidth',0.5
data types: single
| double
simplemodeltype
— type of simple model
'linear'
(default) | 'tree'
type of the simple model, specified as the comma-separated pair consisting of 'simplemodeltype'
and 'linear'
or 'tree'
.
'linear'
— the software fits a linear model by usingfitrlinear
for regression orfitclinear
for classification.'tree'
— the software fits a decision tree model by usingfitrtree
for regression orfitctree
for classification.
example: 'simplemodeltype','tree'
data types: char
| string
categoricalpredictors
— categorical predictors list
vector of positive integers | logical vector | character matrix | string array | cell array of character vectors | 'all'
categorical predictors list, specified as the comma-separated pair consisting of
'categoricalpredictors'
and one of the values in this
table.
value | description |
---|---|
vector of positive integers | each entry in the vector is an index value indicating that the corresponding predictor
is categorical. the index values are between 1 and
if
|
logical vector | a |
character matrix | each row of the matrix is the name of a predictor variable. the names must match the variable names of the predictor data in the form of a table. pad the names with extra blanks so each row of the character matrix has the same length. |
string array or cell array of character vectors | each element in the array is the name of a predictor variable. the names must match the variable names of the predictor data in the form of a table. |
'all' | all predictors are categorical. |
if you specify
blackbox
as a function handle, thenlime
identifies categorical predictors from the predictor datax
orcustomsyntheticdata
. if the predictor data is in a table,lime
assumes that a variable is categorical if it is a logical vector, unordered categorical vector, character array, string array, or cell array of character vectors. if the predictor data is a matrix,lime
assumes that all predictors are continuous.if you specify
blackbox
as a regression or classification model object, thenlime
identifies categorical predictors by using thecategoricalpredictors
property of the model object.
lime
does not support an ordered categorical
predictor.
example: 'categoricalpredictors','all'
data types: single
| double
| logical
| char
| string
| cell
type
— type of machine learning model
'regression
| 'classification'
type of the machine learning model, specified as the comma-separated pair
consisting of 'type'
and 'regression
or
'classification'
.
you must specify this argument when you specify blackbox
as a function handle. if you specify blackbox
as a regression
or classification model object, then lime
determines the
'type'
value depending on the model type.
example: 'type','classification'
data types: char
| string
distance
— distance metric
character vector | string scalar | function handle
distance metric, specified as the comma-separated pair consisting of 'distance'
and a character vector, string scalar, or function handle.
if the predictor data includes only continuous variables, then
lime
supports these distance metrics.value description 'euclidean'
euclidean distance.
'seuclidean'
standardized euclidean distance. each coordinate difference between observations is scaled by dividing by the corresponding element of the standard deviation,
s = std(pd,'omitnan')
, wherepd
is the predictor data or synthetic predictor data. to specify different scaling, use the'scale'
name-value argument.'mahalanobis'
mahalanobis distance using the sample covariance of
pd
,c = cov(pd,'omitrows')
. to change the value of the covariance matrix, use the'cov'
name-value argument.'cityblock'
city block distance.
'minkowski'
minkowski distance. the default exponent is 2. to specify a different exponent, use the
'p'
name-value argument.'chebychev'
chebychev distance (maximum coordinate difference).
'cosine'
one minus the cosine of the included angle between points (treated as vectors).
'correlation'
one minus the sample correlation between points (treated as sequences of values).
'spearman'
one minus the sample spearman's rank correlation between observations (treated as sequences of values).
@
distfun
custom distance function handle. a distance function has the form
wherefunction d2 = distfun(zi,zj) % calculation of distance ...
zi
is a1
-by-t
vector containing a single observation.zj
is ans
-by-t
matrix containing multiple observations.distfun
must accept a matrixzj
with an arbitrary number of observations.d2
is ans
-by-1
vector of distances, andd2(k)
is the distance between observationszi
andzj(k,:)
.
if your data is not sparse, you can generally compute distance more quickly by using a built-in distance metric instead of a function handle.
if the predictor data includes both continuous and categorical variables, then
lime
supports these distance metrics.value description 'goodall3'
modified goodall distance
'ofd'
occurrence frequency distance
for definitions, see distance metrics.
the default value is 'euclidean'
if the predictor data
includes only continuous variables, or 'goodall3'
if the
predictor data includes both continuous and categorical variables.
example: 'distance','ofd'
data types: char
| string
| function_handle
cov
— covariance matrix for mahalanobis distance metric
positive definite matrix
covariance matrix for the mahalanobis distance metric, specified as the
comma-separated pair consisting of 'cov'
and a
k-by-k positive definite matrix, where
k is the number of predictors.
this argument is valid only if 'distance'
is 'mahalanobis'
.
the default 'cov'
value is
cov(pd,'omitrows')
, where pd
is the
predictor data or synthetic predictor data. if you do not specify the
'cov'
value, then the software uses different covariance
matrices when computing the distances for both the predictor data and the synthetic
predictor data.
example: 'cov',eye(3)
data types: single
| double
p
— exponent for minkowski distance metric
2
(default) | positive scalar
exponent for the minkowski distance metric, specified as the comma-separated
pair consisting of 'p'
and a positive scalar.
this argument is valid only if 'distance'
is 'minkowski'
.
example: 'p',3
data types: single
| double
scale
— scale parameter value for standardized euclidean distance metric
nonnegative numeric vector
scale parameter value for the standardized euclidean distance metric, specified
as the comma-separated pair consisting of 'scale'
and a
nonnegative numeric vector of length k, where
k is the number of predictors.
this argument is valid only if 'distance'
is 'seuclidean'
.
the default 'scale'
value is
std(pd,'omitnan')
, where pd
is the predictor
data or synthetic predictor data. if you do not specify the
'scale'
value, then the software uses different scale
parameters when computing the distances for both the predictor data and the
synthetic predictor data.
example: 'scale',quantile(x,0.75) -
quantile(x,0.25)
data types: single
| double
properties
specified properties
you can specify the following properties when creating a lime
object.
blackboxmodel
— machine learning model to be interpreted
regression model object | classification model object | function handle
this property is read-only.
machine learning model to be interpreted, specified as a regression or classification model object or a function handle.
the blackbox
argument sets this property.
categoricalpredictors
— categorical predictor indices
vector of positive integers | []
this property is read-only.
categorical predictor
indices, specified as a vector of positive integers. categoricalpredictors
contains index values indicating that the corresponding predictors are categorical. the index
values are between 1 and p
, where p
is the number of
predictors used to train the model. if none of the predictors are categorical, then this
property is empty ([]
).
if you specify
blackbox
using a function handle, thenlime
identifies categorical predictors from the predictor datax
orcustomsyntheticdata
. if you specify the'categoricalpredictors'
name-value argument, then the argument sets this property.if you specify
blackbox
as a regression or classification model object, thenlime
determines this property by using thecategoricalpredictors
property of the model object.
lime
does not support an ordered categorical
predictor.
if 'simplemodeltype'
is 'linear'
(default), then
lime
creates dummy variables for each identified
categorical predictor. lime
treats the category of the
specified query point as a reference group and creates one less dummy variable than
the number of categories. for more details, see dummy variables with reference group.
data types: single
| double
datalocality
— locality of synthetic data for data generation
'global'
| 'local'
this property is read-only.
locality of the synthetic data for data generation, specified as
'global'
or 'local'
.
the 'datalocality'
name-value argument sets this property.
numimportantpredictors
— number of important predictors to use in simple model
positive integer scalar value
this property is read-only.
number of important predictors to use in the simple model (simplemodel
), specified as a positive integer scalar value.
the numimportantpredictors
argument of lime
or the
numimportantpredictors
argument of fit
sets this
property.
data types: single
| double
numsyntheticdata
— number of samples in synthetic data set
positive integer scalar value
this property is read-only.
number of samples in the synthetic data set, specified as a positive integer scalar value.
if you specify
customsyntheticdata
, then the number of samples in the custom synthetic data set sets this property.otherwise, the
'numsyntheticdata'
name-value argument oflime
or the'numsyntheticdata'
name-value argument offit
sets this property.
data types: single
| double
querypoint
— query point
row vector of numeric values | single-row table
this property is read-only.
query point at which lime
explains a prediction using the
simple model (simplemodel
), specified as a row vector of numeric values or single-row
table.
the querypoint
argument of lime
or the querypoint
argument of fit
sets this property.
data types: single
| double
| table
type
— type of machine learning model
'regression
| 'classification'
this property is read-only.
type of the machine learning model (blackboxmodel
), specified as 'regression
or
'classification'
.
x
— predictor data
numeric matrix | table
this property is read-only.
predictor data, specified as a numeric matrix or table.
each row of x
corresponds to one observation, and each column
corresponds to one variable.
if you specify the
x
argument, then the argument sets this property.if you specify the
customsyntheticdata
argument, then this property is empty.if you specify
blackbox
as a full machine learning model object and do not specifyx
orcustomsyntheticdata
, then this property value is the predictor data used to trainblackbox
.
lime
does not use rows that contain missing values and does not
store the rows in x
.
data types: single
| double
| table
computed properties
the software computes the following properties.
blackboxfitted
— prediction for query point computed by machine learning model
scalar
this property is read-only.
prediction for the query point computed by the machine learning model (blackboxmodel
), specified as a scalar. the prediction is a predicted
response for regression or a classified label for classification.
data types: single
| double
| categorical
| logical
| char
| string
| cell
fitted
— predictions for synthetic predictor data computed by machine learning model
vector
this property is read-only.
predictions for synthetic predictor data computed by the machine learning model
(blackboxmodel
), specified as a vector.
data types: single
| double
| categorical
| logical
| char
| string
| cell
importantpredictors
— important predictor indices
vector of positive integers
this property is read-only.
important predictor indices, specified as a vector of positive integers.
importantpredictors
contains the index values corresponding to
the columns of the predictors used in the simple model (simplemodel
).
data types: single
| double
simplemodel
— simple model
regressionlinear
model object | regressiontree
model object | classificationlinear
model object | classificationtree
model object
this property is read-only.
simple model, specified as a regressionlinear
, regressiontree
, classificationlinear
, or model object. lime
determines the
type of simple model object depending on the type of the machine learning model
(type
) and
the type of the simple model ('simplemodeltype'
).
simplemodelfitted
— prediction for query point computed by simple model
scalar
this property is read-only.
prediction for the query point computed by the simple model (simplemodel
), specified as a scalar.
if simplemodel
is classificationlinear
, then the
simplemodelfitted
value is 1 or –1.
the
simplemodelfitted
value is 1 if the prediction from the simple model is the same asblackboxfitted
(prediction from the machine learning model).the
simplemodelfitted
value is –1 if the prediction from the simple model is different fromblackboxfitted
. if theblackboxfitted
value isa
, then theplot
function displays thesimplemodelfitted
value asnot a
.
data types: single
| double
| categorical
| logical
| char
| string
| cell
syntheticdata
— synthetic predictor data
numeric matrix | table
this property is read-only.
synthetic predictor data, specified as a numeric matrix or a table.
if you specify the
customsyntheticdata
input argument, then the argument sets this property.otherwise,
lime
estimates distribution parameters from the predictor datax
and generates a synthetic predictor data set.
data types: single
| double
| table
object functions
examples
explain prediction with decision tree simple model
train a classification model and create a lime
object that uses a decision tree simple model. when you create a lime
object, specify a query point and the number of important predictors so that the software generates samples of a synthetic data set and fits a simple model for the query point with important predictors. then display the estimated predictor importance in the simple model by using the object function plot
.
load the creditrating_historical
data set. the data set contains customer ids and their financial ratios, industry labels, and credit ratings.
tbl = readtable('creditrating_historical.dat');
display the first three rows of the table.
head(tbl,3)
id wc_ta re_ta ebit_ta mve_bvtd s_ta industry rating _____ _____ _____ _______ ________ _____ ________ ______ 62394 0.013 0.104 0.036 0.447 0.142 3 {'bb'} 48608 0.232 0.335 0.062 1.969 0.281 8 {'a' } 42444 0.311 0.367 0.074 1.935 0.366 1 {'a' }
create a table of predictor variables by removing the columns of customer ids and ratings from tbl
.
tblx = removevars(tbl,["id","rating"]);
train a blackbox model of credit ratings by using the fitcecoc
function.
blackbox = fitcecoc(tblx,tbl.rating,'categoricalpredictors','industry');
create a lime
object that explains the prediction for the last observation using a decision tree simple model. specify 'numimportantpredictors'
as six to find at most 6 important predictors. if you specify the 'querypoint'
and 'numimportantpredictors'
values when you create a lime
object, then the software generates samples of a synthetic data set and fits a simple interpretable model to the synthetic data set.
querypoint = tblx(end,:)
querypoint=1×6 table
wc_ta re_ta ebit_ta mve_bvtd s_ta industry
_____ _____ _______ ________ ____ ________
0.239 0.463 0.065 2.924 0.34 2
rng('default') % for reproducibility results = lime(blackbox,'querypoint',querypoint,'numimportantpredictors',6, ... 'simplemodeltype','tree')
results = lime with properties: blackboxmodel: [1x1 classificationecoc] datalocality: 'global' categoricalpredictors: 6 type: 'classification' x: [3932x6 table] querypoint: [1x6 table] numimportantpredictors: 6 numsyntheticdata: 5000 syntheticdata: [5000x6 table] fitted: {5000x1 cell} simplemodel: [1x1 classificationtree] importantpredictors: [2x1 double] blackboxfitted: {'aa'} simplemodelfitted: {'aa'}
plot the lime
object results
by using the object function plot
. to display an existing underscore in any predictor name, change the ticklabelinterpreter
value of the axes to 'none'
.
f = plot(results);
f.currentaxes.ticklabelinterpreter = 'none';
the plot displays two predictions for the query point, which correspond to the blackboxfitted property and the simplemodelfitted property of results
.
the horizontal bar graph shows the sorted predictor importance values. lime
finds the financial ratio variables mve_bvtd
and re_ta
as important predictors for the query point.
you can read the bar lengths by using data tips or . for example, you can find bar
objects by using the findobj
function and add labels to the ends of the bars by using the text
function.
b = findobj(f,'type','bar'); text(b.yendpoints 0.001,b.xendpoints,string(b.ydata))
alternatively, you can display the coefficient values in a table with the predictor variable names.
imp = b.ydata; flipud(array2table(imp', ... 'rownames',f.currentaxes.yticklabel,'variablenames',{'predictor importance'}))
ans=2×1 table
predictor importance
____________________
mve_bvtd 0.088412
re_ta 0.0018061
explain prediction with linear simple model
train a regression model and create a lime
object that uses a linear simple model. when you create a lime
object, if you do not specify a query point and the number of important predictors, then the software generates samples of a synthetic data set but does not fit a simple model. use the object function fit
to fit a simple model for a query point. then display the coefficients of the fitted linear simple model by using the object function plot
.
load the carbig
data set, which contains measurements of cars made in the 1970s and early 1980s.
load carbig
create a table containing the predictor variables acceleration
, cylinders
, and so on, as well as the response variable mpg
.
tbl = table(acceleration,cylinders,displacement,horsepower,model_year,weight,mpg);
removing missing values in a training set can help reduce memory consumption and speed up training for the fitrkernel
function. remove missing values in tbl
.
tbl = rmmissing(tbl);
create a table of predictor variables by removing the response variable from tbl
.
tblx = removevars(tbl,'mpg');
train a blackbox model of mpg
by using the function.
rng('default') % for reproducibility mdl = fitrkernel(tblx,tbl.mpg,'categoricalpredictors',[2 5]);
create a lime
object. specify a predictor data set because mdl
does not contain predictor data.
results = lime(mdl,tblx)
results = lime with properties: blackboxmodel: [1x1 regressionkernel] datalocality: 'global' categoricalpredictors: [2 5] type: 'regression' x: [392x6 table] querypoint: [] numimportantpredictors: [] numsyntheticdata: 5000 syntheticdata: [5000x6 table] fitted: [5000x1 double] simplemodel: [] importantpredictors: [] blackboxfitted: [] simplemodelfitted: []
results
contains the generated synthetic data set. the simplemodel
property is empty ([]
).
fit a linear simple model for the first observation in tblx
. specify the number of important predictors to find as 3.
querypoint = tblx(1,:)
querypoint=1×6 table
acceleration cylinders displacement horsepower model_year weight
____________ _________ ____________ __________ __________ ______
12 8 307 130 70 3504
results = fit(results,querypoint,3);
plot the lime
object results
by using the object function plot
. to display an existing underscore in any predictor name, change the ticklabelinterpreter
value of the axes to 'none'
.
f = plot(results);
f.currentaxes.ticklabelinterpreter = 'none';
the plot displays two predictions for the query point, which correspond to the blackboxfitted property and the simplemodelfitted property of results
.
the horizontal bar graph shows the coefficient values of the simple model, sorted by their absolute values. lime finds horsepower
, model_year
, and cylinders
as important predictors for the query point.
model_year
and cylinders
are categorical predictors that have multiple categories. for a linear simple model, the software creates one less dummy variable than the number of categories for each categorical predictor. the bar graph displays only the most important dummy variable. you can check the coefficients of the other dummy variables using the simplemodel
property of results
. display the sorted coefficient values, including all categorical dummy variables.
[~,i] = sort(abs(results.simplemodel.beta),'descend'); table(results.simplemodel.expandedpredictornames(i)',results.simplemodel.beta(i), ... 'variablenames',{'expanded predictor name','coefficient'})
ans=17×2 table
expanded predictor name coefficient
__________________________ ___________
{'cylinders (5 vs. 8)' } 0.18008
{'model_year (74 vs. 70)'} -0.082499
{'model_year (80 vs. 70)'} -0.052277
{'model_year (81 vs. 70)'} 0.035987
{'model_year (82 vs. 70)'} -0.026442
{'model_year (71 vs. 70)'} 0.014736
{'model_year (76 vs. 70)'} 0.014723
{'model_year (75 vs. 70)'} 0.013979
{'model_year (77 vs. 70)'} 0.012762
{'model_year (78 vs. 70)'} 0.0089647
{'cylinders (6 vs. 8)' } -0.006972
{'model_year (79 vs. 70)'} -0.0058682
{'model_year (72 vs. 70)'} 0.005654
{'cylinders (3 vs. 8)' } -0.0023194
{'horsepower' } -0.00021074
{'cylinders (4 vs. 8)' } 0.00014773
⋮
specify blackbox model as function handle
train a regression model and create a lime
object using a function handle to the predict
function of the model. use the object function fit
to fit a simple model for the specified query point. then display the coefficients of the fitted linear simple model by using the object function plot
.
load the carbig
data set, which contains measurements of cars made in the 1970s and early 1980s.
load carbig
create a table containing the predictor variables acceleration
, cylinders
, and so on.
tbl = table(acceleration,cylinders,displacement,horsepower,model_year,weight);
train a blackbox model of mpg
by using the treebagger
function.
rng('default') % for reproducibility mdl = treebagger(100,tbl,mpg,'method','regression','categoricalpredictors',[2 5]);
lime
does not support a treebagger
object directly, so you cannot specify the first input argument (blackbox model) of lime
as a treebagger
object. instead, you can use a function handle to the predict
function. you can also specify options of the predict
function using name-value arguments of the function.
create the function handle to the predict
function of the treebagger
object mdl
. specify the array of tree indices to use as 1:50
.
mypredict = @(tbl) predict(mdl,tbl,'trees',1:50);
create a lime
object using the function handle mypredict
. when you specify a blackbox model as a function handle, you must provide the predictor data and specify the 'type'
name-value argument. tbl
includes categorical predictors (cylinder
and model_year
) with the double
data type. by default, lime
does not treat variables with the double
data type as categorical predictors. specify the second (cylinder
) and fifth (model_year
) variables as categorical predictors.
results = lime(mypredict,tbl,'type','regression','categoricalpredictors',[2 5]);
fit a linear simple model for the first observation in tbl
. to display an existing underscore in any predictor name, change the ticklabelinterpreter
value of the axes to 'none'
.
results = fit(results,tbl(1,:),4);
f = plot(results);
f.currentaxes.ticklabelinterpreter = 'none';
lime
finds horsepower
, displacement
, cylinders
, and model_year
as important predictors.
more about
distance metrics
a distance metric is a function that defines a distance between two
observations. lime
supports various distance metrics for
continuous variables and a mix of continuous and categorical variables.
distance metrics for continuous variables
given an mx-by-n data matrix x, which is treated as mx (1-by-n) row vectors x1, x2, ..., xmx, and an my-by-n data matrix y, which is treated as my (1-by-n) row vectors y1, y2, ...,ymy, the various distances between the vector xs and yt are defined as follows:
euclidean distance
the euclidean distance is a special case of the minkowski distance, where p = 2.
standardized euclidean distance
where v is the n-by-n diagonal matrix whose jth diagonal element is (s(j))2, where s is a vector of scaling factors for each dimension.
mahalanobis distance
where c is the covariance matrix.
city block distance
the city block distance is a special case of the minkowski distance, where p = 1.
minkowski distance
for the special case of p = 1, the minkowski distance gives the city block distance. for the special case of p = 2, the minkowski distance gives the euclidean distance. for the special case of p = ∞, the minkowski distance gives the chebychev distance.
chebychev distance
the chebychev distance is a special case of the minkowski distance, where p = ∞.
cosine distance
correlation distance
where
and
spearman distance
where
rsj is the rank of xsj taken over x1j, x2j, ...xmx,j, as computed by .
rtj is the rank of ytj taken over y1j, y2j, ...ymy,j, as computed by .
rs and rt are the coordinate-wise rank vectors of xs and yt, that is, rs = (rs1, rs2, ... rsn) and rt = (rt1, rt2, ... rtn).
.
.
distance metrics for a mix of continuous and categorical variables
modified goodall distance
this distance is a variant of the goodall distance, which assigns a small distance if the matching values are infrequent regardless of the frequencies of the other values. for mismatches, the distance contribution of the predictor is 1/(number of variables).
occurrence frequency distance
for a match, the occurrence frequency distance assigns zero distance. for a mismatch, the occurrence frequency distance assigns a higher distance on a less frequent value and a lower distance on a more frequent value.
algorithms
lime
to explain a prediction of a machine learning model using lime [1], the software generates a synthetic data
set and fits a simple interpretable model to the synthetic data set by using
lime
and fit
, as described in steps
1–5.
if you specify the
querypoint
andnumimportantpredictors
values oflime
, then thelime
function performs all steps.if you do not specify
querypoint
andnumimportantpredictors
and specify'datalocality'
as'global'
(default), then thelime
function generates a synthetic data set (steps 1–2), and thefit
function fits a simple model (steps 3–5).if you do not specify
querypoint
andnumimportantpredictors
and specify'datalocality'
as'local'
, then thefit
function performs all steps.
the lime
and fit
functions perform these
steps:
generate a synthetic predictor data set xs using a multivariate normal distribution for continuous variables and a multinomial distribution for each categorical variable. you can specify the number of samples to generate by using the
'numsyntheticdata'
name-value argument.if
'datalocality'
is'global'
(default), then the software estimates the distribution parameters from the whole predictor data set (x
or predictor data inblackbox
).if
'datalocality'
is'local'
, then the software estimates the distribution parameters using the k-nearest neighbors of the query point, where k is the'numneighbors'
value. you can specify a distance metric to find the nearest neighbors by using the'distance'
name-value argument.
the software ignores missing values in the predictor data set when estimating the distribution parameters.
alternatively, you can provide a pregenerated, custom synthetic predictor data set by using the
customsyntheticdata
input argument oflime
.compute the predictions ys for the synthetic data set xs. the predictions are predicted responses for regression or classified labels for classification. the software uses the
predict
function of theblackbox
model to compute the predictions. if you specifyblackbox
as a function handle, then the software computes the predictions by using the function handle.compute the distances d between the query point and the samples in the synthetic predictor data set using the distance metric specified by
'distance'
.compute the weight values wq of the samples in the synthetic predictor data set with respect to the query point q using the squared exponential (or gaussian) kernel function
xs is a sample in the synthetic predictor data set xs.
d(xs,q) is the distance between the sample xs and the query point q.
p is the number of predictors in xs.
σ is the kernel width, which you can specify by using the
'kernelwidth'
name-value argument. the default'kernelwidth'
value is 0.75.
the weight value at the query point is 1, and then it converges to zero as the distance value increases. the
'kernelwidth'
value controls how fast the weight value converges to zero. the lower the'kernelwidth'
value, the faster the weight value converges to zero. therefore, the algorithm gives more weight to samples near the query point. because this algorithm uses such weight values, the selected important predictors and fitted simple model effectively explain the predictions for the synthetic data locally, around the query point.fit a simple model.
if
'simplemodeltype'
is'linear'
(default), then the software selects important predictors and fits a linear model of the selected important predictors.select n important predictors () by using the group orthogonal matching pursuit (omp) algorithm [2][3], where n is the
numimportantpredictors
value. this algorithm uses the synthetic predictor data set (xs), predictions (ys), and weight values (wq).fit a linear model of the selected important predictors () to the predictions (ys) using the weight values (wq). the software uses
fitrlinear
for regression orfitclinear
for classification. for a multiclass model, the software uses the one-versus-all scheme to construct a binary classification problem. the positive class is the predicted class for the query point from theblackbox
model, and the negative class refers to the other classes.
if
'simplemodeltype'
is'tree'
, then the software fits a decision tree model by usingfitrtree
for regression orfitctree
for classification. the software specifies the maximum number of decision splits (or branch nodes) as the number of important predictors so that the fitted decision tree uses at most the specified number of predictors.
references
[1] ribeiro, marco tulio, s. singh, and c. guestrin. "'why should i trust you?': explaining the predictions of any classifier." in proceedings of the 22nd acm sigkdd international conference on knowledge discovery and data mining, 1135–44. san francisco, california: acm, 2016.
[2] świrszcz, grzegorz, naoki abe, and aurélie c. lozano. "grouped orthogonal matching pursuit for variable selection and prediction." advances in neural information processing systems (2009): 1150–58.
[3] lozano, aurélie c., grzegorz świrszcz, and naoki abe. "group orthogonal matching pursuit for logistic regression." proceedings of the fourteenth international conference on artificial intelligence and statistics (2011): 452–60.
version history
introduced in r2020b
see also
plotpartialdependence
| shapley
topics
- (deep learning toolbox)
- interpret machine learning models
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)