FreecodeCamp - NumPy Tutorial
Mix.install([
{:nx, "~> 0.6.4"}
])
import IEx.Helpers
References
- FreecodeCamp Youtube - Python NumPy Tutorial for Beginners
- NumPy Tutorial Github
- NX Docs
- Numerical Elixir (Nx) Github
- NX - Exercises: 1-20
- Discover Livebook notebooks (Elixir)
The Basics
Numerical Elixir. The Nx library is a collection of functions and data types to work with Numerical Elixir.
Create one-dimensional tensor
a = Nx.tensor([1, 2, 3])
#Nx.Tensor<
s64[3]
[1, 2, 3]
>
Using different type
b = Nx.tensor([1, 2, 3], type: {:f, 32})
c = Nx.tensor([1, 2, 3], type: :f32)
IO.inspect({b, c})
{#Nx.Tensor<
f32[3]
[1.0, 2.0, 3.0]
>,
#Nx.Tensor<
f32[3]
[1.0, 2.0, 3.0]
>}
{#Nx.Tensor<
f32[3]
[1.0, 2.0, 3.0]
>,
#Nx.Tensor<
f32[3]
[1.0, 2.0, 3.0]
>}
Create an n-dimensional tensor, name, and axis
d = Nx.tensor([[9.0, 8.0, 7.0], [6.0, 5.0, 4.0]], names: [:y, :x])
Nx.Defn.Kernel.print_value(d)
#Nx.Tensor<
f32[y: 2][x: 3]
Nx.Defn.Expr
tensor a f32[2][3]
b = token hook_70: a tuple1
c = attach_token b, a f32[2][3]
>
Returns the type of the tensor.
# type of a variable
Nx.type(a) |> IO.inspect()
# type of b variable
Nx.type(b) |> IO.inspect()
{:s, 64}
{:f, 32}
{:f, 32}
Returns the byte size of the data in the tensor computed from its shape and type.
Nx.byte_size(a)
24
Returns the number of elements in the tensor.
Nx.size(a)
3
Returns the shape of the tensor as a tuple.
Nx.shape(a)
{3}
Returns all of the names in a tensor.
Nx.names(d)
[:y, :x]
Returns all of the axes in a tensor.
Nx.axes(d)
[0, 1]
Accessing/Changing specific elements, rows, columns, etc
a = Nx.tensor([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], names: [:rows, :cols])
#Nx.Tensor<
s64[rows: 2][cols: 7]
[
[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14]
]
>
Get any cell of the tensor. Access a specific element [row][column].
a[1][5]
#Nx.Tensor<
s64
13
>
Get a specific row.
a[rows: 0] |> IO.inspect()
a[[0]]
#Nx.Tensor<
s64[cols: 7]
[1, 2, 3, 4, 5, 6, 7]
>
#Nx.Tensor<
s64[cols: 7]
[1, 2, 3, 4, 5, 6, 7]
>
Get a specific column.
a[cols: 2] |> IO.inspect()
a[[.., 2]]
#Nx.Tensor<
s64[rows: 2]
[3, 10]
>
#Nx.Tensor<
s64[rows: 2]
[3, 10]
>
Getting a little more fancy [rows: 0][start_index..end_index//step_size].
a[rows: 0][1..-1//2] |> IO.inspect()
a[[0, 1..-1//2]]
#Nx.Tensor<
s64[cols: 3]
[2, 4, 6]
>
#Nx.Tensor<
s64[cols: 3]
[2, 4, 6]
>
Puts individual values from updates into the given tensor at the corresponding indices.
indices = Nx.tensor([1, 5])
updates = 20
Nx.indexed_put(a, indices, updates) |> IO.inspect()
# Another alternative using put_slice/3
Nx.put_slice(a, [1, 5], Nx.tensor([[20]]))
#Nx.Tensor<
s64[rows: 2][cols: 7]
[
[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 20, 14]
]
>
#Nx.Tensor<
s64[rows: 2][cols: 7]
[
[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 20, 14]
]
>
Puts the given slice into the given tensor at the given start_indices.
Nx.put_slice(a, [1, 2], Nx.tensor([[1], [2]]))
#Nx.Tensor<
s64[rows: 2][cols: 7]
[
[1, 2, 1, 4, 5, 6, 7],
[8, 9, 2, 11, 12, 13, 14]
]
>
Create 3-dimensional tensor
b = Nx.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
#Nx.Tensor<
s64[2][2][2]
[
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
]
>
Get specific element (work outside in)
b[0][1][1]
#Nx.Tensor<
s64
4
>
b[[.., 1]]
#Nx.Tensor<
s64[2][2]
[
[3, 4],
[7, 8]
]
>
Replace
Nx.put_slice(b, [0, 1, 1], Nx.tensor([[[9, 9]], [[8, 8]]]))
#Nx.Tensor<
s64[2][2][2]
[
[
[1, 2],
[9, 9]
],
[
[5, 6],
[8, 8]
]
]
>
Initializing Different Types of Arrays
All 0s matrix
Nx.tensor(0, type: :f32) |> Nx.broadcast({2, 3})
#Nx.Tensor<
f32[2][3]
[
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0]
]
>
All 1s matrix
Nx.tensor(1, type: :u32) |> Nx.broadcast({4, 2, 2})
#Nx.Tensor<
u32[4][2][2]
[
[
[1, 1],
[1, 1]
],
[
[1, 1],
[1, 1]
],
[
[1, 1],
[1, 1]
],
[
[1, 1],
[1, 1]
]
]
>
Any other number
Nx.tensor(99, type: :f32) |> Nx.broadcast({2, 2})
#Nx.Tensor<
f32[2][2]
[
[99.0, 99.0],
[99.0, 99.0]
]
>
Any other number full_like
shape = Nx.shape(a) |> IO.inspect()
Nx.tensor(4) |> Nx.broadcast(shape)
{2, 7}
#Nx.Tensor<
s64[2][7]
[
[4, 4, 4, 4, 4, 4, 4],
[4, 4, 4, 4, 4, 4, 4]
]
>
Random decimal numbers between 0 and 1.
{tensor, _} = Nx.Random.uniform(Nx.Random.key(42), 0, 1, shape: {4, 2}, type: {:f, 32})
tensor
#Nx.Tensor<
f32[4][2]
[
[0.22264933586120605, 0.8067858219146729],
[0.443212628364563, 0.2301114797592163],
[0.7512603998184204, 0.6597683429718018],
[0.011617779731750488, 0.35609757900238037]
]
>
Random integer numbers.
{tensor, _} = Nx.Random.randint(Nx.Random.key(4224), -4, 8, shape: {3, 3})
tensor
#Nx.Tensor<
s64[3][3]
[
[5, 7, 4],
[-2, -4, 7],
[1, -1, 3]
]
>
Creates a diagonal tensor from a 1D tensor.
Nx.make_diagonal(Nx.tensor([1, 1, 1, 1, 1]))
#Nx.Tensor<
s64[5][5]
[
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]
]
>
Nx.eye(5)
#Nx.Tensor<
s64[5][5]
[
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]
]
>
Creates a tensor with the given shape which increments along the provided axis.
t = Nx.tensor([1, 2, 3])
Nx.broadcast(t, {3, 3}, axes: [1])
#Nx.Tensor<
s64[3][3]
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
]
>
Nx.iota({3, 3}, axis: 1) |> Nx.add(1)
#Nx.Tensor<
s64[3][3]
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
]
>
How to build this tensor.
[
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 9, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
]
output_tensor = Nx.broadcast(1, {5, 5})
#Nx.Tensor<
s64[5][5]
[
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]
]
>
inner_tensor = Nx.broadcast(0, {3, 3})
#Nx.Tensor<
s64[3][3]
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
>
middle_tensor = Nx.tensor([[9]])
#Nx.Tensor<
s64[1][1]
[
[9]
]
>
new_inner_tensor = Nx.put_slice(inner_tensor, [1, 1], middle_tensor)
#Nx.Tensor<
s64[3][3]
[
[0, 0, 0],
[0, 9, 0],
[0, 0, 0]
]
>
Nx.put_slice(output_tensor, [1, 1], new_inner_tensor)
#Nx.Tensor<
s64[5][5]
[
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 9, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
]
>
Mathematics
a = Nx.tensor([1, 2, 3, 4])
#Nx.Tensor<
s64[4]
[1, 2, 3, 4]
>
Nx.add(a, 2)
#Nx.Tensor<
s64[4]
[3, 4, 5, 6]
>
Nx.subtract(a, 2)
#Nx.Tensor<
s64[4]
[-1, 0, 1, 2]
>
Nx.multiply(a, 2)
#Nx.Tensor<
s64[4]
[2, 4, 6, 8]
>
Nx.divide(a, 2)
#Nx.Tensor<
f32[4]
[0.5, 1.0, 1.5, 2.0]
>
b = Nx.tensor([1, 0, 1, 0])
Nx.add(a, b)
#Nx.Tensor<
s64[4]
[2, 2, 4, 4]
>
Element-wise power of two tensors.
Nx.pow(a, 2)
#Nx.Tensor<
s64[4]
[1, 4, 9, 16]
>
Calculates the cosine of each element in the tensor.
Nx.cos(a)
#Nx.Tensor<
f32[4]
[0.5403022766113281, -0.416146844625473, -0.9899924993515015, -0.6536436080932617]
>
Linear Algebra
a = Nx.tensor(1) |> Nx.broadcast({2, 3})
#Nx.Tensor<
s64[2][3]
[
[1, 1, 1],
[1, 1, 1]
]
>
b = Nx.tensor(2) |> Nx.broadcast({3, 2})
#Nx.Tensor<
s64[3][2]
[
[2, 2],
[2, 2],
[2, 2]
]
>
Returns the dot product of two tensors.
Nx.dot(a, b)
#Nx.Tensor<
s64[2][2]
[
[6, 6],
[6, 6]
]
>
Calculates the determinant of batched square matrices.
Nx.tensor(1)
|> Nx.broadcast({3})
|> Nx.make_diagonal()
#Nx.Tensor<
s64[3][3]
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
>
c = Nx.eye(3)
#Nx.Tensor<
s64[3][3]
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
>
Nx.LinAlg.determinant(c)
#Nx.Tensor<
f32
1.0
>
Statistics
stats = Nx.tensor([[1, 2, 3], [4, 5, 6]], names: [:rows, :cols])
#Nx.Tensor<
s64[rows: 2][cols: 3]
[
[1, 2, 3],
[4, 5, 6]
]
>
Nx.reduce_min(stats)
#Nx.Tensor<
s64
1
>
Nx.reduce_max(stats, axes: [:cols])
#Nx.Tensor<
s64[rows: 2]
[3, 6]
>
Nx.sum(stats, axes: [0])
#Nx.Tensor<
s64[cols: 3]
[5, 7, 9]
>
Reorganizing Arrays
before = Nx.tensor([[1, 2, 3, 4], [5, 6, 7, 8]])
#Nx.Tensor<
s64[2][4]
[
[1, 2, 3, 4],
[5, 6, 7, 8]
]
>
Changes the shape of a tensor.
The new shape is either a tuple or a tensor which we will retrieve the current shape from. The shapes must be compatible: the product of each dimension in the shape must be equal.
Nx.reshape(before, Nx.shape({8, 1}))
#Nx.Tensor<
s64[8][1]
[
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8]
]
>
Nx.reshape(before, Nx.shape({4, 2}))
#Nx.Tensor<
s64[4][2]
[
[1, 2],
[3, 4],
[5, 6],
[7, 8]
]
>
Nx.reshape(before, Nx.shape({2, 2, 2}))
#Nx.Tensor<
s64[2][2][2]
[
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
]
>
Stacks a list of tensors with the same shape along a new axis.
v1 = Nx.tensor([1, 2, 3, 4])
#Nx.Tensor<
s64[4]
[1, 2, 3, 4]
>
v2 = Nx.tensor([5, 6, 7, 8])
#Nx.Tensor<
s64[4]
[5, 6, 7, 8]
>
Nx.stack([v2, v1])
#Nx.Tensor<
s64[2][4]
[
[5, 6, 7, 8],
[1, 2, 3, 4]
]
>
Nx.stack([v1, v2, v1, v2])
#Nx.Tensor<
s64[4][4]
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[1, 2, 3, 4],
[5, 6, 7, 8]
]
>
h1 = Nx.tensor(1) |> Nx.broadcast({2, 4}, names: [:x, :y])
#Nx.Tensor<
s64[x: 2][y: 4]
[
[1, 1, 1, 1],
[1, 1, 1, 1]
]
>
h2 = Nx.tensor(0) |> Nx.broadcast({2, 2}, names: [:x, :y])
#Nx.Tensor<
s64[x: 2][y: 2]
[
[0, 0],
[0, 0]
]
>
Nx.concatenate([h1, h2], axis: :y)
#Nx.Tensor<
s64[x: 2][y: 6]
[
[1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 0, 0]
]
>
Miscellaneous
path = Path.join(__DIR__, "/files/data.txt")
"/Users/herminiotorres/Workspace/herminiotorres/learning/numerical_elixir/freecodecamp-numpy-to-nx/files/data.txt"
filedata =
path
|> File.stream!()
|> Enum.map(fn line ->
line
|> String.replace("\n", "")
|> String.split(",", trim: true)
|> Enum.map(&String.to_integer/1)
end)
|> Nx.tensor(type: :u32)
#Nx.Tensor<
u32[3][18]
[
[1, 13, 21, 11, 196, 75, 4, 3, 34, 6, 7, 8, 0, 1, 2, 3, 4, 5],
[3, 42, 12, 33, 766, 75, 4, 55, 6, 4, 3, 4, 5, 6, 7, 0, 11, 12],
[1, 22, 33, 11, 999, 11, 2, 1, 78, 0, 1, 2, 9, 8, ...]
]
>
Filter
Nx.greater(filedata, 50)
#Nx.Tensor<
u8[3][18]
[
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, ...]
]
>
Boolean Masking and Advanced Indexing
# (~((filedata > 50) & (filedata < 100)))
nil
Gave the image above to finish the challenge:
- create the tensor
- get the tensor
[[11,12], [16,17]]shaped{2,2} - get the tensor
[2, 8, 14, 20]shaped{1,4} - get the tensor
[[4, 5], [24, 25], [29, 30]]shaped{3,2}
l =
Nx.iota({6, 5}, names: [:x, :y])
|> Nx.add(1)
#Nx.Tensor<
s64[x: 6][y: 5]
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30]
]
>
l[[2..3//1, 0..1//1]]
#Nx.Tensor<
s64[x: 2][y: 2]
[
[11, 12],
[16, 17]
]
>
Nx.take_diagonal(l, offset: 1)
#Nx.Tensor<
s64[4]
[2, 8, 14, 20]
>
red_1 = l[[0..0, 3..4]]
#Nx.Tensor<
s64[x: 1][y: 2]
[
[4, 5]
]
>
red_2 = l[[4..5//1, 3..4//1]]
#Nx.Tensor<
s64[x: 2][y: 2]
[
[24, 25],
[29, 30]
]
>
Nx.concatenate([red_1, red_2])
#Nx.Tensor<
s64[x: 3][y: 2]
[
[4, 5],
[24, 25],
[29, 30]
]
>