Skip to content

Latest commit

 

History

History
409 lines (309 loc) · 12.4 KB

TUTORIAL_FIRST_STEPS.md

File metadata and controls

409 lines (309 loc) · 12.4 KB

Tutorial: First Steps

Tensor Properties

Tensors have the following properties:

  • shape - the shape of the tensor. It is a sequence of a the tensor's dimensions along each axis.
  • strides - the strides of the tensor. It is a sequence of numbers of steps to get the next item along a dimension.
  • size - the total number of elements in the tensor.
  • rank() - the number of dimensions in the tensor. It is 0 for scalars, 1 for vectors, 2 for matrices and N for tensors of rank N.
import vtl

t := vtl.from_2d([[1, 2, 3], [4, 5, 6]])!

println(t)
// [[1, 2, 3], [4, 5, 6]]

println(t.size) // 6
println(t.rank()) // 2
println(t.shape) // [2, 3]
println(t.strides) // [3, 1] => next row is 3 elements away in memory while the next column is 1 element away in memory

The optional memory format changes the storage layout, not the logical matrix values. A column-major tensor created from nested rows keeps the same row and column indices:

import vtl

column_major := vtl.from_2d([[1, 2, 3], [4, 5, 6]], memory: .col_major)!
assert column_major.is_col_major_contiguous()
assert column_major.to_array() == [1, 2, 3, 4, 5, 6]
assert column_major.get([0, 1]) == 2

Tensor Creation

The canonical way to create a tensor is to use the vtl.from_* functions.

import vtl

t1d := vtl.from_1d([1, 2, 3])!

println(t1d)
// [1, 2, 3]

t2d := vtl.from_2d([[1, 2, 3], [4, 5, 6]])!

println(t2d)
// [[1, 2, 3], [4, 5, 6]]

t := vtl.from_array([1, 2, 3, 4, 5, 6, 7, 8], [2, 4])!

println(t)
// [[1, 2, 3, 4], [5, 6, 7, 8]]

println(t.size) // 8
println(t.rank()) // 2
println(t.shape) // [2, 4]
println(t.strides) // [4, 1] => next row is 4 elements away in memory while the next column is 1 element away in memory

Use range for unit-spaced integer bounds, arange for a chosen step, and linspace when you need a fixed number of samples. range and arange exclude the stop value; linspace includes it by default. Negative steps create a descending arange sequence.

import vtl

integers := vtl.range[int](2, 6)
fractions := vtl.arange[f64](0.0, 1.0, 0.25)!
countdown := vtl.arange[int](5, 0, -2)!
samples := vtl.linspace[f64](0.0, 1.0, 5)!
interior_samples := vtl.linspace[f64](0.0, 1.0, 4, endpoint: false)!
decades := vtl.logspace[f64](0.0, 4.0, 5)! // [1, 10, 100, 1000, 10000]

assert integers.to_array() == [2, 3, 4, 5]
assert fractions.to_array() == [0.0, 0.25, 0.5, 0.75]
assert countdown.to_array() == [5, 3, 1]
assert samples.to_array() == [0.0, 0.25, 0.5, 0.75, 1.0]
assert interior_samples.to_array() == [0.0, 0.25, 0.5, 0.75]
assert decades.to_array() == [1.0, 10.0, 100.0, 1000.0, 10000.0]

vander builds a polynomial feature matrix from a vector. By default it uses one column per input value with descending powers; set increasing: true for the order commonly used by polynomial regression features.

import vtl

x := vtl.from_1d([1.0, 2.0, 3.0])!
features := vtl.vander(x, increasing: true)!
println(features)
// [[1, 1, 1], [1, 2, 4], [1, 3, 9]]

Numeric dtype conversion

Use the explicit as_* methods when an operation needs a different tensor element type. Numeric casts cover the supported integer, floating-point, and boolean types while preserving the tensor's logical values and shape. A cast to the existing type returns the original tensor; a conversion creates a row-major tensor. Floating-point values converted to integers are truncated.

import vtl

samples := vtl.from_array[u32]([1, 2, 3, 4], [2, 2])!
as_float := samples.as_f64()
as_small_int := samples.as_i16()
assert as_float.shape == samples.shape
assert as_float.to_array() == [1.0, 2.0, 3.0, 4.0]
assert as_small_int.to_array() == [1, 2, 3, 4]

fractional := vtl.from_1d([1.75, 2.5])!
assert fractional.as_int().to_array() == [1, 2]

dtype() reports a tensor's element type. promote_types determines a common result type for two array dtypes and rejects string/numeric mixtures. The promotion helper models NumPy's array-dtype rules using VTL's current types. For mixed real numeric tensors, add_promoted, subtract_promoted, and multiply_promoted apply those rules with broadcasting; choose the output type explicitly and VTL checks it against the promotion result. The arithmetic operators still require matching tensor types. divide_promoted follows NumPy's true-division output types: integer inputs produce f64, while inputs whose promoted dtype is f32 produce f32. remainder_promoted supports mixed integer and floating-point tensors with broadcasting and NumPy's remainder semantics. Nonzero results have the divisor's sign; integer division by zero produces zero, while floating-point division by zero produces NaN.

import vtl

signed := vtl.from_1d[i8]([100, -3])!
unsigned := vtl.from_1d[u8]([60, 4])!
sum := vtl.add_promoted[i16, i8, u8](signed, unsigned)!
assert sum.dtype() == .int16
assert sum.to_array() == [i16(160), 1]

dividends := vtl.from_1d[i8]([6, -6])!
divisors := vtl.from_1d[u8]([4, 2])!
quotients := vtl.divide_promoted[f64, i8, u8](dividends, divisors)!
assert quotients.dtype() == .float64
assert quotients.to_array() == [1.5, -3.0]

remainder_left := vtl.from_1d[i8]([-5, 5])!
remainder_right := vtl.from_1d[i16]([3, -3])!
remainders := vtl.remainder_promoted[i16, i8, i16](remainder_left, remainder_right)!
assert remainders.to_array() == [1, -1]

float_left := vtl.from_1d[f32]([-5.0, 5.0])!
float_right := vtl.from_1d[f64]([3.0, -3.0])!
float_remainders := vtl.remainder_promoted[f64, f32, f64](float_left, float_right)!
assert float_remainders.to_array() == [1.0, -1.0]

The *_scalar_promoted variants apply NumPy-style weak scalar promotion to real numeric tensors, with the tensor on the left. The matching *_scalar_left_promoted variants accept the scalar first and preserve operand order. Floating tensors retain their dtype with boolean, integer, or floating scalars. Integer tensors retain their dtype for in-range integer and boolean scalars, while floating scalars promote the result to f64; an out-of-range integer scalar returns an error. Integer true division returns f64. Because V generic return types are static, specify the result type R; VTL validates it against the inferred result dtype.

Complex tensors keep complex128 with real or complex scalars. A complex scalar promotes real numeric and boolean tensors to complex128; complex remainder is unsupported.

import math.complex
import vtl

values := vtl.from_1d[f32]([1.5, -2.0])!
shifted := vtl.add_scalar_promoted[f32, f32, f64](values, 0.25)!
assert shifted.dtype() == .float32
assert shifted.get_nth(0) == f32(1.75)

integers := vtl.from_1d[i8]([10, -5])!
fractional := vtl.add_scalar_promoted[f64, i8, f64](integers, 0.5)!
assert fractional.dtype() == .float64
assert fractional.to_array() == [10.5, -4.5]

left_difference := vtl.subtract_scalar_left_promoted[f64, i8, int](12, integers)!
assert left_difference.to_array() == [2.0, 17.0]

complex_values := vtl.add_scalar_promoted[complex.Complex, f32, complex.Complex](values,
	complex.complex(0.25, 0.5))!
assert complex_values.dtype() == .complex128
assert complex_values.get_nth(0).re == 1.75
assert complex_values.get_nth(0).im == 0.5

complex_array := vtl.from_1d[complex.Complex]([
	complex.complex(1.0, 2.0),
	complex.complex(-1.0, 1.0),
])!
real_array := vtl.from_1d[f32]([1.0, 2.0])!
mixed_sum := vtl.add_promoted[complex.Complex, complex.Complex, f32](complex_array,
	real_array)!
assert mixed_sum.get_nth(1).re == 1.0
assert mixed_sum.get_nth(1).im == 1.0

Same-dtype tensors support elementwise arithmetic operators with broadcasting. For shape errors returned as !, use the corresponding methods such as subtract instead of operators. V requires dereferencing tensor pointers for binary subtraction because - also supports pointer subtraction.

For elementwise extrema, max and min propagate NaNs like NumPy's maximum and minimum; fmax and fmin ignore a single NaN value. All four methods broadcast their inputs and preserve the tensor dtype.

import math
import vtl

left := vtl.from_1d([math.nan(), 4.0, -0.0])!
right := vtl.from_1d([2.0, math.nan(), 0.0])!
assert left.max(right)!.to_array()[2] == 0.0
assert math.signbit(left.max(right)!.get_nth(2))
assert left.fmax(right)!.to_array()[0] == 2.0
assert left.fmin(right)!.to_array()[1] == 4.0
import vtl

a := vtl.from_2d([[10, 20, 30], [40, 50, 60]])!
b := vtl.from_1d([1, 2, 3])!
difference := (*a) - (*b)
assert difference.to_array() == [9, 18, 27, 39, 48, 57]
import vtl

integers := vtl.from_1d[u16]([1, 2, 3])!
assert integers.dtype() == .uint16
signed32 := integers.as_i32()
assert signed32.dtype() == .int32
assert vtl.promote_types(integers.dtype(), .float32)! == .float32
assert vtl.promote_types(.int16, .uint16)! == .int32
assert vtl.promote_types(.int64, .uint64)! == .float64

logspace spaces samples evenly in the exponent; its default base is 10. Set base in the options to use another positive finite base.

Other ways to create a tensor are:

  • tensor - creates a new tensor. This can be used to initialize a tensor of a specific shape with a default value. (0 for numbers, false for bool, ...)
  • zeros - creates a tensor of zeros.
  • ones - creates a tensor of ones.
  • zeros_like - creates a tensor of zeros with the same shape as the given tensor.
  • ones_like - creates a tensor of ones with the same shape as the given tensor.

indices builds a dense tensor of integer coordinates. Its shape is the number of dimensions followed by the requested dimensions, as in NumPy.

import vtl

coordinates := vtl.indices([2, 3])!
assert coordinates.shape == [2, 2, 3]
assert coordinates.to_array() == [0, 0, 0, 1, 1, 1, 0, 1, 2, 0, 1, 2]

Use indices_sparse when the coordinates will be broadcast later. It returns one tensor per axis and stores only each axis's coordinate vector:

import vtl

coordinates := vtl.indices_sparse([2, 3, 4])!
// Shapes: [2, 1, 1], [1, 3, 1], [1, 1, 4]
import vtl

t := vtl.tensor(0.0, [2, 3])

println(t)
// [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]

booleans := vtl.tensor(false, [2, 3])

println(booleans)
// [[false, false, false], [false, false, false]]

z := vtl.zeros[f64]([2, 3])

println(z)
// [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]

o := vtl.ones[f64]([2, 3])

println(o)
// [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]

tmp := vtl.from_array([1, 2, 3, 4], [2, 2])!

h := vtl.zeros_like(tmp)

println(h)
// [[0.0, 0.0], [0.0, 0.0]]

i := vtl.ones_like(tmp)

println(i)
// [[1.0, 1.0], [1.0, 1.0]]

Coordinate grids

meshgrid(x, y) makes dense 2-D coordinate matrices with NumPy's default xy indexing. The resulting shape is [y.size, x.size].

import vtl

x := vtl.from_1d([1, 2, 3])!
y := vtl.from_1d([10, 20])!
x_grid, y_grid := vtl.meshgrid(x, y)!
println(x_grid) // [[1, 2, 3], [1, 2, 3]]
println(y_grid) // [[10, 10, 10], [20, 20, 20]]

For three or more axes, meshgrid_n returns one grid per input. Use .ij to preserve axis order or .xy to swap the first two axes like NumPy:

import vtl

x := vtl.from_1d([1, 2])!
y := vtl.from_1d([10, 20, 30])!
z := vtl.from_1d([4, 5])!
grids := vtl.meshgrid_n[int]([x, y, z], .xy)!
assert grids[0].shape == [3, 2, 2]
assert grids[0].get([2, 1, 1]) == 2
assert grids[1].get([2, 1, 1]) == 30
assert grids[2].get([2, 1, 1]) == 5

Accessing and modifying a value

import vtl

mut t := vtl.from_array([1, 2, 3, 4, 5, 6, 7, 8], [2, 4])!

println(t.get([1, 1]))
// 5

t.set([1, 1], 10)

println(t)
// [[1, 2, 3, 4], [10, 5, 6, 7]]

Reshaping and copying a tensor

reshape preserves row-major logical element order. A row-major contiguous input can be reshaped as a view, so writes through either tensor are visible through the other. A transposed or column-major input is copied into row-major order when needed. Use copy() when you want to explicitly select a memory layout; use flatten() when you always need an independent one-dimensional copy. These view and copy rules match NumPy's reshape behavior.

import vtl

a := vtl.from_array([1, 2, 3, 4, 5, 6, 7, 8], [2, 4])!

println(a)
// [[1, 2, 3, 4], [5, 6, 7, 8]]

b := a.reshape([4, 2])!

println(b)
// [[1, 2], [3, 4], [5, 6], [7, 8]]

Because a is contiguous, b shares its storage. A transpose changes the logical order, so reshaping it copies those values instead:

import vtl

mut matrix := vtl.from_2d([[1, 2, 3], [4, 5, 6]])!
transposed := matrix.transpose([1, 0])!
mut flat := transposed.reshape([6])!
assert flat.to_array() == [1, 4, 2, 5, 3, 6]
flat.set_nth(0, 99)
assert matrix.get([0, 0]) == 1 // the reshape result owns a copy