Skip to content

Synthetic Regression Data ​

Machine learning is all about extracting information from data. So you might wonder, what could we possibly learn from synthetic data? While we might not care intrinsically about the patterns that we ourselves baked into an artificial data generating model, such datasets are nevertheless useful for didactic purposes, helping us to evaluate the properties of our learning algorithms and to confirm that our implementations work as expected. For example, if we create data for which the correct parameters are known a priori, then we can check that our model can in fact recover them.

julia
using Pkg
Pkg.activate("../../d2lai")
using d2lai
using Random, Flux
  Activating project at `/workspace/workspace/d2l-julia/d2lai`

Generating the Dataset ​

For this example, we will work in low dimension for succinctness. The following code snippet generates 1000 examples with 2-dimensional features drawn from a standard normal distribution. The resulting design matrix X belongs to R1000×2. We generate each label by applying a ground truth linear function, corrupting them via additive noise ϵ, drawn independently and identically for each example:

y=Xw+b+ϵ.

For convenience we assume that ϵ is drawn from a normal distribution with mean μ=0 and standard deviation σ=0.01.

julia
struct SyntheticRegressionData <: d2lai.AbstractData
    X::AbstractArray 
    y::AbstractArray 
    args::NamedTuple
    function SyntheticRegressionData(w, b, noise = 0.01, num_train = 1000, num_val = 1000, batchsize = 32)
        args = (noise = noise, num_train = num_train, num_val = num_val, batchsize = batchsize)
        n = args.num_train + args.num_val 
        X = randn(length(w), n)
        y = w*X .+ b .+ randn(1, n).*noise
        new(X, y, args)
    end
end

Below, we set the true parameters to w=[2,−3.4]⊤ and b=4.2. Later, we can check our estimated parameters against these ground truth values.

julia
data = SyntheticRegressionData([2 -3.4], 4.3)
Data object of type SyntheticRegressionData

Each row in features consists of a vector in R2 and each row in labels is a scalar. Let's have a look at the first entry.

julia
println("features: $(data.X[:, 1]), labels: $(data.y[1])")
features: [0.2633521971652844, -1.110529094600684], labels: 8.600873573059339

Reading the Dataset ​

Training machine learning models often requires multiple passes over a dataset, grabbing one minibatch of examples at a time. This data is then used to update the model. To illustrate how this works, we implement the get_dataloader method, It takes a batch size, a matrix of features, and a vector of labels, and generates minibatches of size batch_size. As such, each minibatch consists of a tuple of features and labels. Note that we need to be mindful of whether we're in training or validation mode: in the former, we will want to read the data in random order, whereas for the latter, being able to read data in a pre-defined order may be important for debugging purposes.

julia
function d2lai.get_dataloader(data::d2lai.AbstractData; train = true)
        indices = train ? Random.shuffle(1:data.args.num_train) : (data.args.num_train+1):(data.args.num_train+data.args.num_val)
        partitioned_indices = collect(Iterators.partition(indices, data.args.batchsize))
        data = map(partitioned_indices) do idx 
            data.X[:, idx], data.y[:, idx]
        end
        data
end

To build some intuition, let's inspect the first minibatch of data. Each minibatch of features provides us with both its size and the dimensionality of input features. Likewise, our minibatch of labels will have a matching shape given by batch_size.

julia
d2lai.train_dataloader(data)[1][1]
2×32 Matrix{Float64}:
 -0.909321  -0.500413  -0.790988  …  0.313599  -0.0526522  -0.169194
 -2.33647   -0.913567   0.516172     1.45126   -0.156959   -2.91507

While seemingly innocuous, the invocation of d2lai.train_dataloader illustrates the power of multiple dispatch.

Throughout the iteration we obtain distinct minibatches until the entire dataset has been exhausted (try this). While the iteration implemented above is good for didactic purposes, it is inefficient in ways that might get us into trouble with real problems. For example, it requires that we load all the data in memory and that we perform lots of random memory access. The built-in iterators implemented in a deep learning framework are considerably more efficient and they can deal with sources such as data stored in files, data received via a stream, and data generated or processed on the fly. Next let's try to implement the same method using built-in iterators.

Concise Implementation of the Data Loader ​

Rather than writing our own iterator, we can call the existing API in a framework to load data. As before, we need a dataset with features X and labels y. Beyond that, we set batchsize in the built-in data loader and let it take care of shuffling examples efficiently.

julia
function d2lai.get_dataloader(data::SyntheticRegressionData; train = true)
    indices = train ? Random.shuffle(1:data.args.num_train) : (data.args.num_train+1):(data.args.num_train+data.args.num_val)
    Flux.DataLoader((data.X[:, indices], data.y[indices]); batchsize = data.args.batchsize, )

end

The new data loader behaves just like the previous one, except that it is more efficient and has some added functionality.

julia
first(d2lai.train_dataloader(data))[1]
2×32 Matrix{Float64}:
 -0.71515    0.407084  -1.88941  …  0.0295728  0.346882  -0.346259
  0.372792  -0.688122   1.75975     0.255949   0.702533  -0.0318633

Summary ​

Data loaders are a convenient way of abstracting out the process of loading and manipulating data. This way the same machine learning algorithm is capable of processing many different types and sources of data without the need for modification. One of the nice things about data loaders is that they can be composed. For instance, we might be loading images and then have a postprocessing filter that crops them or modifies them in other ways. As such, data loaders can be used to describe an entire data processing pipeline.

As for the model itself, the two-dimensional linear model is about the simplest we might encounter. It lets us test out the accuracy of regression models without worrying about having insufficient amounts of data or an underdetermined system of equations. We will put this to good use in the next section.

Exercises ​

  1. What will happen if the number of examples cannot be divided by the batch size. How would you change this behavior by specifying a different argument by using the framework's API?

  2. Suppose that we want to generate a huge dataset, where both the size of the parameter vector w and the number of examples num_examples are large.

  3. What happens if we cannot hold all data in memory?

  4. How would you shuffle the data if it is held on disk? Your task is to design an efficient algorithm that does not require too many random reads or writes. Hint: pseudorandom permutation generators allow you to design a reshuffle without the need to store the permutation table explicitly [12].

  5. Implement a data generator that produces new data on the fly, every time the iterator is called.

  6. How would you design a random data generator that generates the same data each time it is called?

julia