flowchart LR
W["sillysplines()<br/>drawing widget"] -->|Download boundary| J[coords.json]
W -->|"input$<id>_coords"| S[Shiny server]
J --> C["create_data()"]
S --> C
C --> K["classify_boundary()"]
K --> D[(x, y, class)]
D --> N["add_noise_vars()"]
D --> T["trim_shape()"]
6 sillysplines: Data generation using linear splines
After addressing the XAI explanation layer and the visualization of the dataset layer, the next step we addressed is the synthetic data generation for model testing.
Evaluating an explanation is difficult when the true relationship between the predictors and the response is unknown. If a model’s decision boundary and the explanation of it both disagree with intuition, it is not possible to tell whether the model, the explainer or the intuition is at fault. Synthetic data with a decision boundary fixed by the analyst removes one of these unknowns: the data generating process is known exactly, so the fitted model’s boundary can be compared against it, and an explanation can be judged on whether it recovers the features and regions that truly drive the class label.
The sillysplines package (TODO-sillysplines-cite?) provides this ground truth for two-dimensional binary classification problems. The boundary is a linear spline, a sequence of straight segments joined at knots, which the user draws by hand in an interactive widget. The package then samples points in the plane and labels each one by whether it lies above or below the drawn boundary.
In any two-dimensional area, there are numerous ways to define a boundary for a classification task. While complex, disjointed boundaries can exist, a single, continuous line is often preferred when teaching machine learning concepts. As a pedagogical tool, it’s far more intuitive for students and end users to visually separate two regions with a continuous line, making it easier to conceptualize how a model is attempting to learn and generalize.

However, to ensure that the generated boundary provides a suitable challenge for predictive models, the default design is intentionally complex. Instead of a simple line parallel to an axis, the design consists of a mix of oblique and axis-parallel segments. This approach ensures that the downstream classification task is not trivial and compels the model to learn non-linear relationships. Furthermore, this mixed design helps the model developer discern which of the two features is more influential in the model’s final decision-making process.
6.1 Package overview
The package has two parts. The first is a drawing widget, written in Svelte and compiled to a single JavaScript bundle, which is exposed to R as an htmlwidget through sillysplines(). The second is a set of R functions that turn a drawn boundary into a labelled dataset: classify_boundary(), create_data(), add_noise_vars() and trim_shape(). The two parts communicate only through the knot coordinates, a K \times 2 array holding the (x, y) coordinates of the K knots of the boundary, which can be passed as a downloaded JSON file or, inside a Shiny application, as a reactive input (Figure 6.1).
A typical session draws a boundary, downloads it and generates data from it:
library(sillysplines)
sillysplines() # draw the boundary, then click "Download boundary"
df <- create_data(coord_filepath = "coords.json", n_samples = 5000)The boundary is stored as an array of knots rather than as a table of labelled points. The array is small, maps directly onto the JavaScript representation of the spline, and keeps the sampling decisions (sample size, distribution, gap) in R where they can be changed without redrawing the boundary.
Key points of consideration
When developing this tool several technical considerations had to be taken to translate the user input into a usable decision boundary.
A position on the drawing canvas passes through three coordinate systems before it becomes a knot of the boundary (Figure 6.2). The browser reports the position of the pointer in CSS pixels, measured from the top-left corner of the browser window. The widget converts this position to the coordinate system of the SVG drawing, its user space, in which the canvas has a width W and height H (640 by default, set through the width and height arguments of sillysplines()). The knots are then exported in data coordinates, normalised to [-1, 1] on both axes. A point at position (p_x, p_y) in user space is mapped to
x = 2\frac{p_x}{W} - 1, \qquad y = 1 - 2\frac{p_y}{H},
where the second expression flips the vertical axis, because SVG places its origin at the top-left corner and measures y downwards, while the data coordinate system measures y upwards. Separating the drawing coordinates from the data coordinates makes the exported boundary independent of the size at which it was drawn, and places it on the same scale as standardised predictors.
The relationship between the first two coordinate systems is set by the viewBox attribute of the SVG element. An SVG element occupies a rectangle on the page whose size, in CSS pixels, is decided by the layout of the page. The viewBox separately declares which rectangle of user space is shown in that area: viewBox="0 0 W H" states that user coordinates from 0 to W horizontally and from 0 to H vertically fill the element. The browser scales the drawing by the ratio of the two, so anything defined in user units is reproduced faithfully at any displayed size. In sillysplines the SVG element fills the width of its container and keeps the aspect ratio W/H, so a 640 \times 640 canvas may be displayed at 640 CSS pixels in a wide R Markdown document but at 320 pixels in a narrow column of a Shiny application. The knots and shaded regions are stored and drawn in user units throughout, so they rescale with the element, and the default spline is stored as fractions of the canvas so that it fits canvases of any shape.
This scaling applies to what is drawn but not to pointer input. Pointer events report positions in CSS pixels, and once the element is displayed at a size other than W \times H pixels, one CSS pixel no longer corresponds to one user unit. Treating the pointer offsets as user coordinates would then place knots in the wrong position. When the canvas is displayed at half size, a click on the point (310, 360) in user space is reported at an offset of (155, 180) pixels, and a knot created from these offsets would appear at half the intended distance from the top-left corner (Figure 6.3). The widget therefore converts every pointer position with the inverse of the SVG element’s screen transformation matrix, which combines the offset of the element within the window and the scale implied by the viewBox, so that pointer positions are always obtained in user coordinates regardless of the size at which the canvas is displayed.
When dragging begins on an existing point, it selects that point for manipulation. However, when dragging starts on empty space, the system dynamically creates a new point at that location and immediately begins dragging it. This creates an intuitive user experience where clicking anywhere adds a point.
Each knot has an invisible hit area with a radius of 30 pixels around the visible 5 pixel marker, so a knot can be grabbed without precise clicking. Input is handled with pointer events, which treat mouse, pen and touch input identically, and the pointer is captured for the length of a drag so that moving the cursor outside the canvas does not drop the knot. A new knot is inserted between its neighbours in x order, and during a drag each knot is confined horizontally to the interval between its neighbours (less a one pixel margin) and to the canvas. As a result the knots are always sorted by x and no two share an x value, which guarantees that the drawn line is a function of x: every vertical line crosses the boundary exactly once.
The widget shades two complementary polygons, one above the line and one below it, so the user can see which region each class will occupy. The upper polygon runs from the top-left corner of the canvas, down the left edge to the height of the first knot, along the spline, out to the right edge at the height of the last knot and back to the top-right corner. The lower polygon is built the same way from the bottom corners. Because the knots are kept in x order during editing, the polygons can be built directly from the stored points without sorting. When the first or last knot is not on the edge of the canvas, the boundary is drawn as a dashed horizontal line out to the edge. This mirrors how the boundary is extended in R (Section 6.2), so the regions shaded in the widget are exactly the regions that will be labelled in the generated data.
6.2 Labelling points against the boundary
Let the boundary be given by K \geq 2 knots (x_1, y_1), \dots, (x_K, y_K) with x_1 < x_2 < \dots < x_K. The boundary is the piecewise linear function
f(x) =
\begin{cases}
y_1, & x < x_1, \\[4pt]
y_k + \dfrac{y_{k+1} - y_k}{x_{k+1} - x_k}\,(x - x_k), & x_k \le x \le x_{k+1}, \\[4pt]
y_K, & x > x_K,
\end{cases}
that is, linear interpolation between the knots, held constant beyond the end knots. In classify_boundary() this is computed with stats::approxfun() using rule = 2. A point (x, y) is labelled
\text{class}(x, y) =
\begin{cases}
\text{Above}, & y > f(x), \\
\text{Below}, & y \le f(x),
\end{cases}
so points lying exactly on the boundary are assigned to the second class. The function also returns the signed vertical distance d(x, y) = y - f(x), called the advantage, which is positive above the boundary and negative below it. The class labels can be renamed through the classes argument.
The advantage is a vertical distance, not the perpendicular distance to the nearest segment. On a segment with slope m the perpendicular distance is |d| / \sqrt{1 + m^2}, so the two agree on flat segments but the perpendicular distance is much smaller than |d| on steep ones. This matters for the gap argument described below.
6.3 Generating datasets
create_data() samples n points in a rectangle and labels them with classify_boundary(). By default the rectangle is the bounding box of the knots, which for a boundary drawn edge to edge in the widget is [-1, 1]^2. The xlim and ylim arguments set the rectangle explicitly, which is needed when the boundary does not span the canvas, or is flat and so has no vertical range. Three sampling schemes are available (Figure 6.4):
-
type = "uniform"(the default) draws x and y independently from uniform distributions over the rectangle. Both classes are spread evenly, and the class proportions equal the proportions of the rectangle on either side of the boundary. -
type = "normal"draws points from a bivariate normal distribution with standard normal margins and correlation r, where |r| \le 0.9, and then stretches each coordinate linearly so that the sample spans the rectangle. A linear rescaling does not change the correlation, so the predictors keep the correlation r. Points are concentrated near the centre, so the parts of the boundary near the edges of the rectangle are sparsely covered, and the most extreme sampled points always lie on the edges of the rectangle. -
type = "grid"places \lfloor \sqrt{n} \rfloor^2 points on a regular grid. This is useful for drawing the true boundary as a background layer behind a model’s predictions, or for evaluating a fitted model over the whole space.
create_data(), using the default boundary of the widget (black line) and 2000 points each. Uniform sampling covers the whole square evenly, normal sampling concentrates points near the centre, and grid sampling places points on a regular lattice.
The gap argument removes points whose advantage satisfies |d| < \text{gap}, leaving an empty margin along the boundary (Figure 6.5). A gap turns a problem with overlapping classes near the boundary into one that is perfectly separable, which is useful for checking whether a model can recover the boundary shape at all, and for separating the effect of boundary shape from the effect of label ambiguity. Because the gap is defined through the vertical distance d, the margin is narrower, measured perpendicular to the boundary, on steep segments than on flat ones; this is visible on the steep segments of the default boundary. The gap is restricted to [0, 0.2], on the assumption that the data are on the [-1, 1] scale, and points are removed rather than resampled, so the returned dataset has fewer than n rows.
gap argument on 2000 uniformly sampled points. Points closer than the gap to the boundary, measured vertically, are removed, so the number of points returned decreases as the gap widens.
6.4 Beyond two independent predictors
Two further functions change the generated data without changing the boundary, so that the effect of each change on a model and its explanations can be studied with the true boundary held fixed.
add_noise_vars() appends p variables drawn uniformly over the range of the original predictors. These carry no information about the class, so the data become (p + 2)-dimensional while the boundary remains a function of the last two variables only. The predictors are renamed x_1, \dots, x_{p+2} with the informative pair last. This provides a direct test of an explainer: a faithful explanation should attribute no importance to x_1, \dots, x_p, however many of them there are. Figure 6.6 shows a tour of a four-dimensional dataset produced this way. The boundary is only visible in projections close to the plane of x_3 and x_4; in projections dominated by the noise variables the two classes overlap.
add_noise_vars(): 600 uniformly sampled points with a gap of 0.1 around the default boundary, plus two uniform noise variables x_1 and x_2. The tour moves between random projections and the x_3–x_4 plane, where the boundary appears as the gap between the two classes.
trim_shape() keeps only the points inside an ellipse, which induces a correlation between the two predictors without changing how any point is labelled. Each predictor is standardised, and a point z is kept when its squared Mahalanobis distance from the origin satisfies
z^\top \Sigma^{-1} z < 4, \qquad
\Sigma = \begin{pmatrix} 1 & r \\ r & 1 \end{pmatrix},
with |r| \le 0.9 (Figure 6.7). If the points were bivariate normal with correlation r, this threshold would keep about 1 - e^{-2} \approx 86\% of them; for uniformly sampled points it simply cuts out an elliptical window. Correlated predictors are a known difficulty for perturbation-based explainers such as LIME and Kernel SHAP, which sample from the marginal distribution of each predictor and so create points in regions that contain no training data. Trimming the data lets this effect be examined while the true boundary stays known.
trim_shape() to induce correlation between the predictors. Starting from 3000 uniformly sampled points, only the points inside an ellipse are kept. With r = 0 the window is circular, and with r = 0.6 it is stretched along the diagonal, which leaves parts of the boundary with no nearby data.
6.5 Use inside Shiny applications
The widget can be placed in a Shiny application with sillysplinesOutput() and renderSillysplines(). Whenever the user releases a knot, the widget sends the current knots to the server as input$<outputId>_coords, so the generated data can be updated as the boundary is edited. Each widget keeps its own state, so several widgets can be used on one page.
library(shiny)
shinyApp(
ui = fluidPage(
sillysplinesOutput("splines"),
plotOutput("data")
),
server = function(input, output) {
output$splines <- renderSillysplines(sillysplines())
output$data <- renderPlot({
req(input$splines_coords)
coords <- jsonlite::fromJSON(input$splines_coords)
df <- create_data(coord = coords, n_samples = 3000)
plot(df$x, df$y, col = factor(df$class), pch = 16, cex = 0.4)
})
}
)6.6 Limitations and future work
The design choices that keep the tool simple also limit the boundaries it can express.
- Function-of-x boundaries only. Because knots are kept in x order and every vertical line crosses the boundary once, closed regions (such as a circle of one class inside another), boundaries that fold back on themselves and disconnected regions of the same class cannot be drawn.
- Two classes and two informative predictors. Multi-class problems would need several non-crossing boundaries, and higher-dimensional problems are only available by adding uninformative noise variables.
- Deterministic labels. Every point is labelled exactly by its side of the boundary. Label noise that increases near the boundary, for example by passing the advantage through a logistic function, would give data closer to real classification problems and is a natural extension.
- Vertical rather than perpendicular gap. As noted in Section 6.3, the gap is narrower on steep segments. Defining it by the perpendicular distance to the nearest segment would give a uniform margin.
-
Widget customisation. Knots cannot yet be deleted, the starting spline cannot be passed in from R, and the region colours are fixed in
sillysplines()rather than exposed as arguments.