prhbrt commited on
Commit
4e5beba
·
verified ·
1 Parent(s): cd6534e

Upload bayesiantests.py

Browse files
Files changed (1) hide show
  1. bayesiantests.py +488 -0
bayesiantests.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import numpy.matlib
3
+
4
+ LEFT, ROPE, RIGHT = range(3)
5
+
6
+ def correlated_ttest_MC(x, rope, runs=1, nsamples=50000):
7
+ """
8
+ See correlated_ttest module for explanations
9
+ """
10
+ if x.ndim == 2:
11
+ x = x[:, 1] - x[:, 0]
12
+ diff=x
13
+ n = len(diff)
14
+ nfolds = n / runs
15
+ x = np.mean(diff)
16
+ # Nadeau's and Bengio's corrected variance
17
+ var = np.var(diff, ddof=1) * (1 / n + 1 / (nfolds - 1))
18
+ if var == 0:
19
+ return int(x < rope), int(-rope <= x <= rope), int(rope < x)
20
+
21
+ return x+np.sqrt(var)*np.random.standard_t( n - 1, nsamples)
22
+
23
+
24
+
25
+ ## Correlated t-test
26
+ def correlated_ttest(x, rope, runs=1, verbose=False, names=('C1', 'C2')):
27
+ import scipy.stats as stats
28
+ """
29
+ Compute correlated t-test
30
+
31
+ The function uses the Bayesian interpretation of the p-value and returns
32
+ the probabilities the difference are below `-rope`, within `[-rope, rope]`
33
+ and above the `rope`. For details, see `A Bayesian approach for comparing
34
+ cross-validated algorithms on multiple data sets
35
+ <http://link.springer.com/article/10.1007%2Fs10994-015-5486-z>`_,
36
+ G. Corani and A. Benavoli, Mach Learning 2015.
37
+
38
+ |
39
+ The test assumes that the classifiers were evaluated using cross
40
+ validation. The number of folds is determined from the length of the vector
41
+ of differences, as `len(diff) / runs`. The variance includes a correction
42
+ for underestimation of variance due to overlapping training sets, as
43
+ described in `Inference for the Generalization Error
44
+ <http://link.springer.com/article/10.1023%2FA%3A1024068626366>`_,
45
+ C. Nadeau and Y. Bengio, Mach Learning 2003.)
46
+
47
+ |
48
+ Args:
49
+ x (array): a vector of differences or a 2d array with pairs of scores.
50
+ rope (float): the width of the rope
51
+ runs (int): number of repetitions of cross validation (default: 1)
52
+ return: probablities (tuple) that differences are below -rope, within rope or
53
+ above rope
54
+ """
55
+ if x.ndim == 2:
56
+ x = x[:, 1] - x[:, 0]
57
+ diff=x
58
+ n = len(diff)
59
+ nfolds = n / runs
60
+ x = np.mean(diff)
61
+ # Nadeau's and Bengio's corrected variance
62
+ var = np.var(diff, ddof=1) * (1 / n + 1 / (nfolds - 1))
63
+ if var == 0:
64
+ return int(x < rope), int(-rope <= x <= rope), int(rope < x)
65
+ pr = 1-stats.t.cdf(rope, n - 1, x, np.sqrt(var))
66
+ pl = stats.t.cdf(-rope, n - 1, x, np.sqrt(var))
67
+ pe=1-pl-pr
68
+ if verbose:
69
+ print('P({c1} > {c2}) = {pl}, P(rope) = {pe}, P({c2} > {c1}) = {pr}'.
70
+ format(c1=names[0], c2=names[1], pl=pl, pe=pe, pr=pr))
71
+ return pl, pe, pr
72
+
73
+ ## SIGN TEST
74
+ def signtest_MC(x, rope, prior_strength=1, prior_place=ROPE, nsamples=50000):
75
+ """
76
+ Args:
77
+ x (array): a vector of differences or a 2d array with pairs of scores.
78
+ rope (float): the width of the rope
79
+ prior_strength (float): prior strength (default: 1)
80
+ prior_place (LEFT, ROPE or RIGHT): the region to which the prior is
81
+ assigned (default: ROPE)
82
+ nsamples (int): the number of Monte Carlo samples
83
+
84
+ Returns:
85
+ 2-d array with rows corresponding to samples and columns to
86
+ probabilities `[p_left, p_rope, p_right]`
87
+ """
88
+ if prior_strength < 0:
89
+ raise ValueError('Prior strength must be nonegative')
90
+ if nsamples < 0:
91
+ raise ValueError('Number of samples must be a positive integer')
92
+ if rope < 0:
93
+ raise ValueError('Rope must be a positive number')
94
+
95
+ if x.ndim == 2:
96
+ x = x[:, 1] - x[:, 0]
97
+ nleft = sum(x < -rope)
98
+ nright = sum(x > rope)
99
+ nrope = len(x) - nleft - nright
100
+ alpha = np.array([nleft, nrope, nright], dtype=float)
101
+ alpha += 0.0001 # for numerical stability
102
+ alpha[prior_place] += prior_strength
103
+ return np.random.dirichlet(alpha, nsamples)
104
+
105
+ def signtest(x, rope, prior_strength=1, prior_place=ROPE, nsamples=50000,
106
+ verbose=False, names=('C1', 'C2')):
107
+ """
108
+ Args:
109
+ x (array): a vector of differences or a 2d array with pairs of scores.
110
+ rope (float): the width of the rope
111
+ prior_strength (float): prior strength (default: 1)
112
+ prior_place (LEFT, ROPE or RIGHT): the region to which the prior is
113
+ assigned (default: ROPE)
114
+ nsamples (int): the number of Monte Carlo samples
115
+ verbose (bool): report the computed probabilities
116
+ names (pair of str): the names of the two classifiers
117
+
118
+ Returns:
119
+ p_left, p_rope, p_right
120
+ """
121
+ samples = signtest_MC(x, rope, prior_strength, prior_place, nsamples)
122
+
123
+ winners = np.argmax(samples, axis=1)
124
+ pl, pe, pr = np.bincount(winners, minlength=3) / len(winners)
125
+ if verbose:
126
+ print('P({c1} > {c2}) = {pl}, P(rope) = {pe}, P({c2} > {c1}) = {pr}'.
127
+ format(c1=names[0], c2=names[1], pl=pl, pe=pe, pr=pr))
128
+ return pl, pe, pr
129
+
130
+ ## SIGNEDRANK
131
+ def heaviside(X):
132
+ Y = np.zeros(X.shape);
133
+ Y[np.where(X > 0)] = 1;
134
+ Y[np.where(X == 0)] = 0.5;
135
+ return Y #1 * (x > 0)
136
+
137
+ def signrank_MC(x, rope, prior_strength=0.6, prior_place=ROPE, nsamples=50000):
138
+ """
139
+ Args:
140
+ x (array): a vector of differences or a 2d array with pairs of scores.
141
+ rope (float): the width of the rope
142
+ prior_strength (float): prior strength (default: 0.6)
143
+ prior_place (LEFT, ROPE or RIGHT): the region to which the prior is
144
+ assigned (default: ROPE)
145
+ nsamples (int): the number of Monte Carlo samples
146
+
147
+ Returns:
148
+ 2-d array with rows corresponding to samples and columns to
149
+ probabilities `[p_left, p_rope, p_right]`
150
+ """
151
+ if x.ndim == 2:
152
+ zm = x[:, 1] - x[:, 0]
153
+ else:
154
+ zm = x
155
+ nm=len(zm)
156
+ if prior_place==ROPE:
157
+ z0=[0]
158
+ if prior_place==LEFT:
159
+ z0=[-float('inf')]
160
+ if prior_place==RIGHT:
161
+ z0=[float('inf')]
162
+ z=np.concatenate((zm,z0))
163
+ n=len(z)
164
+ z=np.transpose(np.asmatrix(z))
165
+ X=np.matlib.repmat(z,1,n)
166
+ Y=np.matlib.repmat(-np.transpose(z)+2*rope,n,1)
167
+ Aright = heaviside(X-Y)
168
+ X=np.matlib.repmat(-z,1,n)
169
+ Y=np.matlib.repmat(np.transpose(z)+2*rope,n,1)
170
+ Aleft = heaviside(X-Y)
171
+ alpha=np.concatenate((np.ones(nm),[prior_strength]),axis=0)
172
+ samples=np.zeros((nsamples,3), dtype=float)
173
+ for i in range(0,nsamples):
174
+ data = np.random.dirichlet(alpha, 1)
175
+ samples[i,2]=numpy.inner(np.dot(data,Aright),data)
176
+ samples[i,0]=numpy.inner(np.dot(data,Aleft),data)
177
+ samples[i,1]=1-samples[i,0]-samples[i,2]
178
+
179
+ return samples
180
+
181
+ def signrank(x, rope, prior_strength=0.6, prior_place=ROPE, nsamples=50000,
182
+ verbose=False, names=('C1', 'C2')):
183
+ """
184
+ Args:
185
+ x (array): a vector of differences or a 2d array with pairs of scores.
186
+ rope (float): the width of the rope
187
+ prior_strength (float): prior strength (default: 0.6)
188
+ prior_place (LEFT, ROPE or RIGHT): the region to which the prior is
189
+ assigned (default: ROPE)
190
+ nsamples (int): the number of Monte Carlo samples
191
+ verbose (bool): report the computed probabilities
192
+ names (pair of str): the names of the two classifiers
193
+
194
+ Returns:
195
+ p_left, p_rope, p_right
196
+ """
197
+ samples = signrank_MC(x, rope, prior_strength, prior_place, nsamples)
198
+
199
+ winners = np.argmax(samples, axis=1)
200
+ pl, pe, pr = np.bincount(winners, minlength=3) / len(winners)
201
+ if verbose:
202
+ print('P({c1} > {c2}) = {pl}, P(rope) = {pe}, P({c2} > {c1}) = {pr}'.
203
+ format(c1=names[0], c2=names[1], pl=pl, pe=pe, pr=pr))
204
+ return pl, pe, pr
205
+
206
+
207
+ def hierarchical(diff, rope, rho, upperAlpha=2, lowerAlpha =1, lowerBeta = 0.01, upperBeta = 0.1,std_upper_bound=1000, verbose=False, names=('C1', 'C2') ):
208
+ # upperAlpha, lowerAlpha, upperBeta, lowerBeta, are the upper and lower bound for alpha and beta, which are the parameters of
209
+ #the Gamma distribution used as a prior for the degress of freedom.
210
+ #std_upper_bound is a constant which multiplies the sample standard deviation, to set the upper limit of the prior on the
211
+ #standard deviation. Posterior inferences are insensitive to this value as this is large enough, such as 100 or 1000.
212
+
213
+ samples=hierarchical_MC(diff, rope, rho, upperAlpha, lowerAlpha, lowerBeta, upperBeta, std_upper_bound,names )
214
+ winners = np.argmax(samples, axis=1)
215
+ pl, pe, pr = np.bincount(winners, minlength=3) / len(winners)
216
+ if verbose:
217
+ print('P({c1} > {c2}) = {pl}, P(rope) = {pe}, P({c2} > {c1}) = {pr}'.
218
+ format(c1=names[0], c2=names[1], pl=pl, pe=pe, pr=pr))
219
+ return pl, pe, pr
220
+
221
+ def hierarchical_MC(diff, rope, rho, upperAlpha=2, lowerAlpha =1, lowerBeta = 0.01, upperBeta = 0.1, std_upper_bound=1000, names=('C1', 'C2') ):
222
+ # upperAlpha, lowerAlpha, upperBeta, lowerBeta, are the upper and lower bound for alpha and beta, which are the parameters of
223
+ #the Gamma distribution used as a prior for the degress of freedom.
224
+ #std_upper_bound is a constant which multiplies the sample standard deviation, to set the upper limit of the prior on the
225
+ #standard deviation. Posterior inferences are insensitive to this value as this is large enough, such as 100 or 1000.
226
+
227
+ import scipy.stats as stats
228
+ import pystan
229
+ #data rescaling, to have homogenous scale among all dsets
230
+ stdX = np.mean(np.std(diff,1)) #we scale all the data by the mean of the standard deviation of data sets
231
+ x = diff/stdX
232
+ rope=rope/stdX
233
+
234
+ #to avoid numerical problems with zero variance
235
+ for i in range(0,len(x)):
236
+ if np.std(x[i,:])==0:
237
+ x[i,:]=x[i,:]+np.random.normal(0,np.min(1/1000000000,np.abs(np.mean(x[i,:])/100000000)))
238
+
239
+
240
+ #This is the Hierarchical model written in Stan
241
+ hierarchical_code = """
242
+ /*Hierarchical Bayesian model for the analysis of competing cross-validated classifiers on multiple data sets.
243
+ */
244
+
245
+ data {
246
+
247
+ real deltaLow;
248
+ real deltaHi;
249
+
250
+ //bounds of the sigma of the higher-level distribution
251
+ real std0Low;
252
+ real std0Hi;
253
+
254
+ //bounds on the domain of the sigma of each data set
255
+ real stdLow;
256
+ real stdHi;
257
+
258
+
259
+ //number of results for each data set. Typically 100 (10 runs of 10-folds cv)
260
+ int<lower=2> Nsamples;
261
+
262
+ //number of data sets.
263
+ int<lower=1> q;
264
+
265
+ //difference of accuracy between the two classifier, on each fold of each data set.
266
+ matrix[q,Nsamples] x;
267
+
268
+ //correlation (1/(number of folds))
269
+ real rho;
270
+
271
+ real upperAlpha;
272
+ real lowerAlpha;
273
+ real upperBeta;
274
+ real lowerBeta;
275
+
276
+ }
277
+
278
+
279
+ transformed data {
280
+
281
+ //vector of 1s appearing in the likelihood
282
+ vector[Nsamples] H;
283
+
284
+ //vector of 0s: the mean of the mvn noise
285
+ vector[Nsamples] zeroMeanVec;
286
+
287
+ /* M is the correlation matrix of the mvn noise.
288
+ invM is its inverse, detM its determinant */
289
+ matrix[Nsamples,Nsamples] invM;
290
+ real detM;
291
+
292
+ //The determinant of M is analytically known
293
+ detM <- (1+(Nsamples-1)*rho)*(1-rho)^(Nsamples-1);
294
+
295
+ //build H and invM. They do not depend on the data.
296
+ for (j in 1:Nsamples){
297
+ zeroMeanVec[j]<-0;
298
+ H[j]<-1;
299
+ for (i in 1:Nsamples){
300
+ if (j==i)
301
+ invM[j,i]<- (1 + (Nsamples-2)*rho)*pow((1-rho),Nsamples-2);
302
+ else
303
+ invM[j,i]<- -rho * pow((1-rho),Nsamples-2);
304
+ }
305
+ }
306
+ /*at this point invM contains the adjugate of M.
307
+ we divide it by det(M) to obtain the inverse of M.*/
308
+ invM <-invM/detM;
309
+ }
310
+
311
+ parameters {
312
+ //mean of the hyperprior from which we sample the delta_i
313
+ real<lower=deltaLow,upper=deltaHi> delta0;
314
+
315
+ //std of the hyperprior from which we sample the delta_i
316
+ real<lower=std0Low,upper=std0Hi> std0;
317
+
318
+ //delta_i of each data set: vector of lenght q.
319
+ vector[q] delta;
320
+
321
+ //sigma of each data set: : vector of lenght q.
322
+ vector<lower=stdLow,upper=stdHi>[q] sigma;
323
+
324
+ /* the domain of (nu - 1) starts from 0
325
+ and can be given a gamma prior*/
326
+ real<lower=0> nuMinusOne;
327
+
328
+ //parameters of the Gamma prior on nuMinusOne
329
+ real<lower=lowerAlpha,upper=upperAlpha> gammaAlpha;
330
+ real<lower=lowerBeta, upper=upperBeta> gammaBeta;
331
+
332
+ }
333
+
334
+ transformed parameters {
335
+ //degrees of freedom
336
+ real<lower=1> nu ;
337
+
338
+ /*difference between the data (x matrix) and
339
+ the vector of the q means.*/
340
+ matrix[q,Nsamples] diff;
341
+
342
+ vector[q] diagQuad;
343
+
344
+ /*vector of length q:
345
+ 1 over the variance of each data set*/
346
+ vector[q] oneOverSigma2;
347
+
348
+ vector[q] logDetSigma;
349
+
350
+ vector[q] logLik;
351
+
352
+ //degrees of freedom
353
+ nu <- nuMinusOne + 1 ;
354
+
355
+ //1 over the variance of each data set
356
+ oneOverSigma2 <- rep_vector(1, q) ./ sigma;
357
+ oneOverSigma2 <- oneOverSigma2 ./ sigma;
358
+
359
+ /*the data (x) minus a matrix done as follows:
360
+ the delta vector (of lenght q) pasted side by side Nsamples times*/
361
+ diff <- x - rep_matrix(delta,Nsamples);
362
+
363
+ //efficient matrix computation of the likelihood.
364
+ diagQuad <- diagonal (quad_form (invM,diff'));
365
+ logDetSigma <- 2*Nsamples*log(sigma) + log(detM) ;
366
+ logLik <- -0.5 * logDetSigma - 0.5*Nsamples*log(6.283);
367
+ logLik <- logLik - 0.5 * oneOverSigma2 .* diagQuad;
368
+
369
+ }
370
+
371
+ model {
372
+ /*mu0 and std0 are not explicitly sampled here.
373
+ Stan automatically samples them: mu0 as uniform and std0 as
374
+ uniform over its domain (std0Low,std0Hi).*/
375
+
376
+ //sampling the degrees of freedom
377
+ nuMinusOne ~ gamma ( gammaAlpha, gammaBeta);
378
+
379
+ //vectorial sampling of the delta_i of each data set
380
+ delta ~ student_t(nu, delta0, std0);
381
+
382
+ //logLik is computed in the previous block
383
+ increment_log_prob(sum(logLik));
384
+ }
385
+ """
386
+ datatable=x
387
+ std_within=np.mean(np.std(datatable,1))
388
+
389
+ Nsamples = len(datatable[0])
390
+ q= len(datatable)
391
+ if q>1:
392
+ std_among=np.std(np.mean(datatable,1))
393
+ else:
394
+ std_among=np.mean(np.std(datatable,1))
395
+
396
+ #Hierarchical data in Stan
397
+ hierachical_dat = {'x': datatable,
398
+ 'deltaLow' : -np.max(np.abs(datatable)),
399
+ 'deltaHi' : np.max(np.abs(datatable)),
400
+ 'stdLow' : 0,
401
+ 'stdHi' : std_within*std_upper_bound,
402
+ 'std0Low' : 0,
403
+ 'std0Hi' : std_among*std_upper_bound,
404
+ 'Nsamples' : Nsamples,
405
+ 'q' : q,
406
+ 'rho' : rho,
407
+ 'upperAlpha' : upperAlpha,
408
+ 'lowerAlpha' : lowerAlpha,
409
+ 'upperBeta' : upperBeta,
410
+ 'lowerBeta' : lowerBeta}
411
+
412
+ #Call to Stan code
413
+ fit = pystan.stan(model_code=hierarchical_code, data=hierachical_dat,
414
+ iter=1000, chains=4)
415
+
416
+ la = fit.extract(permuted=True) # return a dictionary of arrays
417
+ mu = la['delta0']
418
+ stdh = la['std0']
419
+ nu = la['nu']
420
+
421
+ samples=np.zeros((len(mu),3), dtype=float)
422
+ for i in range(0,len(mu)):
423
+ samples[i,2]=1-stats.t.cdf(rope, nu[i], mu[i], stdh[i])
424
+ samples[i,0]=stats.t.cdf(-rope, nu[i], mu[i], stdh[i])
425
+ samples[i,1]=1-samples[i,0]-samples[i,2]
426
+
427
+ return samples
428
+
429
+ def plot_posterior(samples, names=('C1', 'C2')):
430
+ """
431
+ Args:
432
+ x (array): a vector of differences or a 2d array with pairs of scores.
433
+ names (pair of str): the names of the two classifiers
434
+
435
+ Returns:
436
+ matplotlib.pyplot.figure
437
+ """
438
+ return plot_simplex(samples, names)
439
+
440
+
441
+ def plot_simplex(points, names=('C1', 'C2')):
442
+ import matplotlib.pyplot as plt
443
+ from matplotlib.lines import Line2D
444
+ from matplotlib.pylab import rcParams
445
+
446
+ def _project(points):
447
+ from math import sqrt, sin, cos, pi
448
+ p1, p2, p3 = points.T / sqrt(3)
449
+ x = (p2 - p1) * cos(pi / 6) + 0.5
450
+ y = p3 - (p1 + p2) * sin(pi / 6) + 1 / (2 * sqrt(3))
451
+ return np.vstack((x, y)).T
452
+
453
+ vert0 = _project(np.array(
454
+ [[0.3333, 0.3333, 0.3333], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]]))
455
+
456
+ fig = plt.figure()
457
+ fig.set_size_inches(8, 7)
458
+
459
+ nl, ne, nr = np.max(points, axis=0)
460
+ for i, n in enumerate((nl, ne, nr)):
461
+ if n < 0.001:
462
+ print("p{} is too small, switching to 2d plot".format(names[::-1] + ["rope"]))
463
+ coords = sorted(set(range(3)) - i)
464
+ return plot2d(points[:, coords], labels[coords])
465
+
466
+ # triangle
467
+ fig.gca().add_line(
468
+ Line2D([0, 0.5, 1.0, 0],
469
+ [0, np.sqrt(3) / 2, 0, 0], color='orange'))
470
+ # decision lines
471
+ for i in (1, 2, 3):
472
+ fig.gca().add_line(
473
+ Line2D([vert0[0, 0], vert0[i, 0]],
474
+ [vert0[0, 1], vert0[i, 1]], color='orange'))
475
+ # vertex labels
476
+ rcParams.update({'font.size': 16})
477
+ fig.gca().text(-0.08, -0.08, 'p({})'.format(names[0]), color='orange')
478
+ fig.gca().text(0.44, np.sqrt(3) / 2 + 0.05, 'p(rope)', color='orange')
479
+ fig.gca().text(1.00, -0.08, 'p({})'.format(names[1]), color='orange')
480
+
481
+ # project and draw points
482
+ tripts = _project(points[:, [0, 2, 1]])
483
+ plt.hexbin(tripts[:, 0], tripts[:, 1], mincnt=1, cmap=plt.cm.Blues_r)
484
+ # Leave some padding around the triangle for vertex labels
485
+ fig.gca().set_xlim(-0.2, 1.2)
486
+ fig.gca().set_ylim(-0.2, 1.2)
487
+ fig.gca().axis('off')
488
+ return fig