Padding Tensors with PyTorch cat
I found myself wanting to pad a tensor with zeroes last week, and wasn’t sure how to do so most easily in pytorch.
This is a short example of the pytorch cat
function, mostly for my own memory.
First, let’s import the PyTorch library.
import torch
Let’s say we have a 2x2 tensor, like so:
first = torch.ones(2, 2)
first
# Output:
# tensor([[1., 1.],
# [1., 1.]])
And another 2x2 tensor, like so:
second = torch.zeros(2,2)
second
# Output:
# tensor([[0., 0.],
# [0., 0.]])
We can put them together with the cat
command like so:
third = torch.cat((first, second), 1)
third
# Output:
# tensor([[1., 1., 0., 0.],
# [1., 1., 0., 0.]])
The first argument is the tuple of tensors to concatenate and the second argument is the dimension on which to append them. The function will check the tensors are of the same size on the dimension specified (here, 2 and 2).
Since the size of our tensors also match in the zero index dimension, we can also combine them like so:
fourth = torch.cat((first, second), 0)
fourth
# Output:
# tensor([[1., 1.],
# [1., 1.],
# [0., 0.],
# [0., 0.]])
More
Archive
chinese
tang-dynasty-poetry
李白
python
王维
rl
pytorch
numpy
emacs
杜牧
spinningup
networking
deep-learning
贺知章
白居易
王昌龄
杜甫
李商隐
tips
reinforcement-learning
macports
jekyll
骆宾王
贾岛
孟浩然
xcode
time-series
terminal
regression
rails
productivity
pandas
math
macosx
lesson-plan
helicopters
flying
fastai
conceptual-learning
command-line
bro
黄巢
韦应物
陈子昂
王翰
王之涣
柳宗元
杜秋娘
李绅
张继
孟郊
刘禹锡
元稹
youtube
visdom
system
sungho
stylelint
stripe
softmax
siri
sgd
scipy
scikit-learn
scikit
safari
research
qtran
qoe
qmix
pyhton
poetry
pedagogy
papers
paper-review
optimization
openssl
openmpi
nyc
node
neural-net
multiprocessing
mpi
morl
ml
mdp
marl
mandarin
macos
machine-learning
latex
language-learning
khan-academy
jupyter-notebooks
ios-programming
intuition
homebrew
hacking
google-cloud
github
flashcards
faker
docker
dme
deepmind
dec-pomdp
data-wrangling
craftsman
congestion-control
coding
books
book-review
atari
anki
analogy
3brown1blue
2fa