Standard library · Encoding and data

data

Reading data for machine learning: CSV tables, batching samples, MNIST and images, and synthetic data.

import data

This package readies data for training a model. LoadCsv builds a table that turns text columns into category numbers by itself, and split_xy divides it into a feature matrix and a label.

The Make... functions build synthetic data from a fixed seed, for trying algorithms out without needing a file. All of it works with the matrix and tensor packages.

Types

Table

struct Table
A data table with named columns, for machine learning.
NameTypeDescription
namesVectorThe column names.
kindsVectorThe kind of each column; one of the COL_ constants.
catsVector>The levels of each categorical column.
rawVector>The original text of the cells.
cellsmatrix.MatrixThe numeric value of the cells; a categorical column holds the level number.
data-Table.salam
import data
import matrix

func main:
    text := "age,city,score,ok\n30,tehran,1.5,1\n25,shiraz,2.5,0\n41,tehran,3.0,1\n"
    mut t := data.LoadCsv(text, true)
    println t.rows(), t.cols(), t.names, t.col_index("score"), t.col_index("x")
    println t.kinds[0] == data.COL_INT, t.kinds[1] == data.COL_CAT, t.kinds[2] == data.COL_FLOAT, data.COL_STR
    println t.cat_levels("city")
    mut m := t.to_matrix()
    println m.rows, m.cols, m.at(2, 1)
    mut x := matrix.Matrix {}
    mut y := matrix.Matrix {}
    println t.split_xy("ok", x, y), x.cols, y.at(1, 0)
    mut good := true
    _ := data.LoadCsvFile("missing.csv", true, good)
    println good
    matrix.Free(m)
    matrix.Free(x)
    matrix.Free(y)
    t.free()
end
Output3 4 ["age", "city", "score", "ok"] 2 -1 true true true 3 ["tehran", "shiraz"] 3 4 0 true 3 0 false

rows

func rows(): int
The number of data rows, not counting the header.

The example for this item is shown with the ones above: data-Table.salam

cols

func cols(): int
The number of columns.

The example for this item is shown with the ones above: data-Table.salam

col_index

func col_index(name: str): int
The index of the column with this name; -1 when there is none.

The example for this item is shown with the ones above: data-Table.salam

cat_levels

func cat_levels(name: str): Vector<str>
The levels of a categorical column, in the order they were seen.

The example for this item is shown with the ones above: data-Table.salam

to_matrix

func to_matrix(): matrix.Matrix
Turns every column into a numeric matrix.

The example for this item is shown with the ones above: data-Table.salam

split_xy

func split_xy(label: str, x &: matrix.Matrix, y &: matrix.Matrix): bool
Moves the label column into y and the rest into x.

The example for this item is shown with the ones above: data-Table.salam

free

func free()
Frees the memory.

The example for this item is shown with the ones above: data-Table.salam

BatchIter

struct BatchIter
A batch iterator.
NameTypeDescription
xmatrix.MatrixThe features.
ymatrix.MatrixThe labels.
batchint = 32The batch size.
shufflebool = trueShuffle the order.
seedi64 = 0The shuffle seed.
orderVectorThe order of the samples in this epoch.
posint = 0The current position.
data-Batch.salam
import data
import matrix
import tensor

func main:
    mut y := matrix.Matrix {}
    x := data.MakeBlobs(10, 2, 3, 0.2, 1, y)
    mut set := data.MatrixDataset { x = x, y = y }
    println set.len()
    mut it := set.batches(4, false, 0)
    println it.batches_per_epoch()
    mut batch_x := matrix.Matrix {}
    mut batch_y := matrix.Matrix {}
    until it.next(batch_x, batch_y):
        println batch_x.rows, batch_x.cols, batch_y.rows
    end
    it.reset(1)
    mut t := tensor.Tensor {}
    mut labels := Vector {} as Vector<int>
    println it.next_tensor(t, labels), labels.len()
    println data.YLabels(y).len(), data.XTensor(x).shape
    mut good := true
    _ := data.ParseIdx(null, 0, good)
    println good
    _ := data.LoadIdx("missing.idx", good)
    println good, data.LoadMnist("a", "b", batch_x, batch_y)
    mut classes := Vector {} as Vector<str>
    println data.LoadImageFolder("missing-folder", 8, 8, true, t, labels, classes)
    it.free()
    set.free()
end
Output10 3 4 3 4 4 3 4 2 3 2 true 4 10 [10, 3] false false false false

reset

func reset(epoch: i64)
Goes back to the start and builds a fresh order from the seed plus the epoch number.

The example for this item is shown with the ones above: data-Batch.salam

next

func next(x_out &: matrix.Matrix, y_out &: matrix.Matrix): bool
Puts the next batch in x_out and y_out; the last batch may be smaller. False when no batch is left.

The example for this item is shown with the ones above: data-Batch.salam

next_tensor

func next_tensor(x_out &: tensor.Tensor, labels_out &: Vector<int>): bool
Hands out the next batch as a tensor and a list of integer labels.

The example for this item is shown with the ones above: data-Batch.salam

batches_per_epoch

func batches_per_epoch(): int
The number of batches in one epoch.

The example for this item is shown with the ones above: data-Batch.salam

free

func free()
Frees the memory.

The example for this item is shown with the ones above: data-Batch.salam

MatrixDataset

struct MatrixDataset
A dataset of a feature matrix and labels.
NameTypeDescription
xmatrix.MatrixThe feature matrix, one row per sample.
ymatrix.MatrixThe labels, one row per sample.

The example for this item is shown with the ones above: data-Batch.salam

len

func len(): int
The number of samples.

The example for this item is shown with the ones above: data-Batch.salam

batches

func batches(batch: int, shuffle: bool, seed: i64): BatchIter
An iterator that hands out the samples a batch at a time; when shuffle is true the order is shuffled from seed.

The example for this item is shown with the ones above: data-Batch.salam

free

func free()
Frees the memory.

The example for this item is shown with the ones above: data-Batch.salam

Constants and variables

Column kinds COL_…

The kind of each table column, worked out as the CSV is read.
NameValue
COL_FLOAT0
COL_INT1
COL_CAT2
COL_STR3

The example for this item is shown with the ones above: data-Table.salam

Functions

MakeBlobs

func MakeBlobs(n: int, centers: int, p: int, spread: f64, seed: i64, y &: matrix.Matrix): matrix.Matrix
Random samples in several clusters with random centres; the label of a sample is the number of its cluster.
data-Synth.salam
import data
import matrix

func count_ones(y: matrix.Matrix): int:
    mut n := 0
    repeat y.rows in i:
        if y.at(i, 0) == 1.0:
            n += 1
        end
    end
    ret n
end

func main:
    mut y := matrix.Matrix {}
    blobs := data.MakeBlobs(90, 3, 2, 0.5, 42, y)
    println blobs.rows, blobs.cols, y.rows
    moons := data.MakeMoons(100, 0.1, 7, y)
    println moons.rows, moons.cols, count_ones(y)
    circles := data.MakeCircles(60, 0.05, 0.5, 7, y)
    println circles.rows, count_ones(y)
    mut coef := matrix.Matrix {}
    reg := data.MakeRegression(50, 3, 0.1, 1, y, coef)
    println reg.rows, reg.cols, coef.rows
    cls := data.MakeClassification(40, 4, 2, 1.0, 3, y)
    println cls.rows, cls.cols, count_ones(y) > 0
end
Output90 2 90 100 2 50 60 30 50 3 3 40 4 true

MakeMoons

func MakeMoons(n: int, noise: f64, seed: i64, y &: matrix.Matrix): matrix.Matrix
Two interleaving crescents with two labels; for trying non linear separators out.

The example for this item is shown with the ones above: data-Synth.salam

MakeCircles

func MakeCircles(n: int, noise: f64, factor: f64, seed: i64, y &: matrix.Matrix): matrix.Matrix
Two concentric circles with two labels; factor is the radius ratio of the inner circle.

The example for this item is shown with the ones above: data-Synth.salam

MakeRegression

func MakeRegression(n: int, p: int, noise: f64, seed: i64, y &: matrix.Matrix, true_coef &: matrix.Matrix): matrix.Matrix
Linear regression data with random coefficients; the real coefficients come back in true_coef.

The example for this item is shown with the ones above: data-Synth.salam

MakeClassification

func MakeClassification(n: int, p: int, classes: int, sep: f64, seed: i64, y &: matrix.Matrix): matrix.Matrix
Classification data with several classes; sep sets how far apart the classes are.

The example for this item is shown with the ones above: data-Synth.salam

LoadImageFolder

func LoadImageFolder(root: str, width: int, height: int, gray: bool, x &: tensor.Tensor, labels &: Vector<int>, classes &: Vector<str>): bool
Loads the images of a folder: each subfolder is one class. The images are resized to the given size, and turned grey when gray is true.

The example for this item is shown with the ones above: data-Batch.salam

ParseIdx

func ParseIdx(p: void*, n: int, ok &: bool): matrix.Matrix
Reads IDX format data, the MNIST format, from memory into a matrix.

The example for this item is shown with the ones above: data-Batch.salam

LoadIdx

func LoadIdx(path: str, ok &: bool): matrix.Matrix
Reads an IDX file into a matrix.

The example for this item is shown with the ones above: data-Batch.salam

LoadMnist

func LoadMnist(images_path: str, labels_path: str, x &: matrix.Matrix, y &: matrix.Matrix): bool
Reads the MNIST image and label files; each image is one row of 784 values between zero and 1.

The example for this item is shown with the ones above: data-Batch.salam

LoadCsv

func LoadCsv(text: str, header: bool): Table
Reads CSV text into a table and works out the kind of each column: integer, float, or text as a categorical column.

The example for this item is shown with the ones above: data-Table.salam

LoadCsvFile

func LoadCsvFile(path: str, header: bool, ok &: bool): Table
Reads a CSV file into a table.

The example for this item is shown with the ones above: data-Table.salam

XTensor

func XTensor(x &: matrix.Matrix): tensor.Tensor
Turns the feature matrix into a tensor.

The example for this item is shown with the ones above: data-Batch.salam

YLabels

func YLabels(y &: matrix.Matrix): Vector<int>
Turns the label column into a list of integers.

The example for this item is shown with the ones above: data-Batch.salam