fit simple model of local interpretable model-凯发k8网页登录
fit simple model of local interpretable model-agnostic explanations (lime)
since r2020b
syntax
description
fits a new simple model for the specified query point (newresults
= fit(results
,querypoint
,numimportantpredictors
)querypoint
) by
using the specified number or predictors (numimportantpredictors
). the
function returns a lime
object
newresults
that contains the new simple model.
fit
uses the simple model options that you specify when you create
the lime
object results
. you can change the options
using the name-value pair arguments of the fit
function.
specifies additional options using one or more name-value pair arguments. for example, you
can specify newresults
= fit(results
,querypoint
,numimportantpredictors
,name,value
)'simplemodeltype','tree'
to fit a decision tree model.
examples
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
⋮
fit simple models for multiple query points
train a classification model and create a lime
object that uses a decision tree simple model. fit multiple models for multiple query points.
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');
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')
blackbox = classificationecoc predictornames: {'wc_ta' 're_ta' 'ebit_ta' 'mve_bvtd' 's_ta' 'industry'} responsename: 'y' categoricalpredictors: 6 classnames: {'a' 'aa' 'aaa' 'b' 'bb' 'bbb' 'ccc'} scoretransform: 'none' binarylearners: {21x1 cell} codingname: 'onevsone' properties, methods
create a lime
object with the blackbox
model.
rng('default') % for reproducibility results = lime(blackbox);
find two query points whose true rating values are aaa
and b
, respectively.
querypoint(1,:) = tblx(find(strcmp(tbl.rating,'aaa'),1),:); querypoint(2,:) = tblx(find(strcmp(tbl.rating,'b'),1),:)
querypoint=2×6 table
wc_ta re_ta ebit_ta mve_bvtd s_ta industry
_____ _____ _______ ________ _____ ________
0.121 0.413 0.057 3.647 0.466 12
0.019 0.009 0.042 0.257 0.119 1
fit a linear simple model for the first query point. set the number of important predictors to 4.
newresults1 = fit(results,querypoint(1,:),4);
plot the lime results newresults1
for the first query point. to display an existing underscore in any predictor name, change the ticklabelinterpreter
value of the axes to 'none'
.
f1 = plot(newresults1);
f1.currentaxes.ticklabelinterpreter = 'none';
fit a linear decision tree model for the first query point.
newresults2 = fit(results,querypoint(1,:),6,'simplemodeltype','tree'); f2 = plot(newresults2); f2.currentaxes.ticklabelinterpreter = 'none';
the simple models in newresults1
and newresults2
both find mve_bvtd
and re_ta
as important predictors.
fit a linear simple model for the second query point, and plot the lime results for the second query point.
newresults3 = fit(results,querypoint(2,:),4);
f3 = plot(newresults3);
f3.currentaxes.ticklabelinterpreter = 'none';
the prediction from the blackbox
model is b
, but the prediction from the simple model is not b
. when the two predictions are not the same, you can specify a smaller 'kernelwidth'
value. the software fits a simple model using weights that are more focused on the samples near the query point. if a query point is an outlier or is located near a decision boundary, then the two prediction values can be different, even if you specify a small 'kernelwidth'
value. in such a case, you can change other name-value pair arguments. for example, you can generate a local synthetic data set (specify 'datalocality'
of lime
as 'local'
) for the query point and increase the number of samples ('numsyntheticdata'
of lime
or fit
) in the synthetic data set. you can also use a different distance metric ('distance'
of lime
or fit
).
fit a linear simple model with a small 'kernelwidth'
value.
newresults4 = fit(results,querypoint(2,:),4,'kernelwidth',0.01); f4 = plot(newresults4); f4.currentaxes.ticklabelinterpreter = 'none';
the credit ratings for the first and second query points are aaa
and b
, respectively. the simple models in newresults1
and newresults4
both find mve_bvtd
, re_ta
, and wc_ta
as important predictors. however, their coefficient values are different. the plots show that these predictors act differently depending on the credit ratings.
input arguments
results
— lime results
lime
object
lime results, specified as a lime
object.
querypoint
— query point
row vector of numeric values | single-row table
query point around which the fit
function fits the simple
model, specified as a row vector of numeric values or a single-row table. the
querypoint
value must have the same data type and the same number
of columns as the predictor data (results.
or x
results.
) in the syntheticdata
lime
object
results
.
querypoint
must not contain missing values.
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'
, 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.
the default value of the numimportantpredictors
argument is the
numimportantpredictors
property value of the lime
object
results
. if you do not specify the property value when creating
results
, then the property value is empty ([]
)
and you must specify this argument.
data types: single
| double
name-value arguments
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: 'numsyntheticdata',2000,'simplemodeltype','tree'
sets the
number of samples to generate for the synthetic data set to 2000 and specifies the simple
model type as a decision tree.
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 value is the 'cov'
value that you specify when
creating the lime
object results
. the default
'cov'
value of lime
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
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
fit
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
fit
supports these distance metrics.value description 'goodall3'
modified goodall distance
'ofd'
occurrence frequency distance
for definitions, see distance metrics.
the default value is the 'distance'
value that you specify when
creating the lime
object results
. the default
'distance'
value of lime
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
kernelwidth
— kernel width
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 fit
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 fit
uses
weights that are more focused on the samples near the query point. for details, see lime.
the default value is the 'kernelwidth'
value that you specify
when creating the lime
object results
. the
default 'kernelwidth'
value of lime
is
0.75.
example: 'kernelwidth',0.5
data types: single
| double
numneighbors
— number of neighbors of query point
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 the datalocality
property of results
is
'local'
.
the fit
function estimates the distribution
parameters of the predictor data using the specified number of nearest neighbors of
the query point. then the function generates synthetic predictor data using the
estimated distribution.
if you specify a value larger than the number of observations in the predictor
data set (results.
) in the x
lime
object
results
, then fit
uses all
observations.
the default value is the 'numneighbors'
value that you specify
when creating the lime
object results
. the
default 'numneighbors'
value of lime
is
1500.
example: 'numneighbors',2000
data types: single
| double
numsyntheticdata
— number of samples to generate for synthetic data set
results.numsyntheticdata
(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.
the default value is the numsyntheticdata
property value of the lime
object
results
. if you provide a custom synthetic data set when
creating results
, then the property value is the number of
samples in the data set. otherwise, the 'numsyntheticdata'
value
that you specify when creating results
sets the property. the
default 'numsyntheticdata'
value of lime
is
5000.
example: 'numsyntheticdata',2500
data types: single
| double
p
— exponent for minkowski distance metric
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'
.
the default value is the 'p'
value that you specify when
creating the lime
object results
. the default
'p'
value of lime
is 2.
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 value is the 'scale'
value that you specify when
creating the lime
object results
. the default
'scale'
value of lime
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
simplemodeltype
— type of simple model
'linear'
| '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.
the default value is the 'simplemodeltype'
value that you
specify when creating the lime
object results
.
the default 'simplemodeltype'
value of lime
is
'linear'
.
example: 'simplemodeltype','tree'
data types: char
| string
output arguments
more about
distance metrics
a distance metric is a function that defines a distance between two
observations. fit
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
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
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)
- 中国
- (日本語)
- (한국어)