Skip to content

Instantly share code, notes, and snippets.

@aymanosman
Last active August 12, 2024 18:52
Show Gist options
  • Save aymanosman/73c76baa2204283b076a7de37d0c2855 to your computer and use it in GitHub Desktop.
Save aymanosman/73c76baa2204283b076a7de37d0c2855 to your computer and use it in GitHub Desktop.
How Nx.stack works

Nx.stack

Mix.install([
  {:nx, "~> 0.7.3"}
])

Section

tensors = [
  Nx.tensor([1, 2, 3]),
  Nx.tensor([4, 5, 6])
]

Nx.stack(tensors, axis: 0, name: :x)
#Nx.Tensor<
  s64[x: 2][3]
  [
    [1, 2, 3],
    [4, 5, 6]
  ]
>
Nx.stack(tensors, axis: 1, name: :x)
#Nx.Tensor<
  s64[3][x: 2]
  [
    [1, 4],
    [2, 5],
    [3, 6]
  ]
>
tensors = [
  Nx.tensor([[1, 2, 3]]),
  Nx.tensor([[4, 5, 6]])
]

Nx.stack(tensors, axis: 0, name: :x)
#Nx.Tensor<
  s64[x: 2][1][3]
  [
    [
      [1, 2, 3]
    ],
    [
      [4, 5, 6]
    ]
  ]
>
Nx.stack(tensors, axis: 1, name: :x)
#Nx.Tensor<
  s64[1][x: 2][3]
  [
    [
      [1, 2, 3],
      [4, 5, 6]
    ]
  ]
>
Nx.stack(tensors, axis: 2, name: :x)
#Nx.Tensor<
  s64[1][3][x: 2]
  [
    [
      [1, 4],
      [2, 5],
      [3, 6]
    ]
  ]
>
Nx.stack(tensors, axis: -1, name: :x)
#Nx.Tensor<
  s64[1][3][x: 2]
  [
    [
      [1, 4],
      [2, 5],
      [3, 6]
    ]
  ]
>
Nx.stack(tensors, axis: -2, name: :x)
#Nx.Tensor<
  s64[1][x: 2][3]
  [
    [
      [1, 2, 3],
      [4, 5, 6]
    ]
  ]
>
Nx.stack(tensors, axis: -3, name: :x)
#Nx.Tensor<
  s64[x: 2][1][3]
  [
    [
      [1, 2, 3]
    ],
    [
      [4, 5, 6]
    ]
  ]
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment