Operações Elemento a Elemento e Reduções
Some, calcule a média e encontre o máximo nos eixos escolhidos
Operações Elemento a Elemento e Reduções é uma aula grátis de Deep Learning Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Deep Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Deep Learning Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Two Kinds of Operations
Tensor math splits into two families: elementwise ops that keep the shape, and reductions that collapse it down to fewer numbers.
Elementwise Keeps the Shape
An elementwise op applies the same action to every entry independently. Input shape in, same shape out, no mixing between positions.
b = a * 2 + 1
# same shape as a, every element transformedPairwise Elementwise Math
With two tensors of equal shape, elementwise ops act position by position. Add matches index to index, multiply does the same.
c = a + b
d = a * bMath Functions Are Elementwise Too
Functions like torch.relu, exp, and sqrt run elementwise. Each number is transformed on its own, and the tensor keeps its original shape.
r = torch.relu(x)
e = torch.exp(x)Reductions Collapse Numbers
A reduction combines many values into fewer. Sum, mean, and max fold a whole tensor down, by default to a single scalar.
total = x.sum()
avg = x.mean()The dim Argument Picks an Axis
Pass dim to reduce along one axis only. The chosen axis disappears while the others stay, so a 2D tensor becomes 1D.
col_sums = x.sum(dim=0)
row_means = x.mean(dim=1)keepdim Saves the Shape
Set keepdim=True to keep the reduced axis as size 1. That preserved shape is what makes later broadcasting line up cleanly.
m = x.max(dim=1, keepdim=True).valuesMean Needs Floats
mean divides, so it expects floating-point input. Call it on an integer tensor and PyTorch will complain until you cast to float first.
avg = x.float().mean()argmax Finds the Winner
Sometimes you want the position, not the value. argmax returns the index of the largest entry, which is how a classifier picks its predicted class.
pred = logits.argmax(dim=1)Chain Them Together
Real code stacks both kinds: an elementwise transform feeds a reduction. Square the errors, then take the mean, and you have mean squared error.
mse = ((pred - target) ** 2).mean()Pick Shape-Keeping or Shape-Shrinking
The rule of thumb: reach for elementwise when every value should change in place, and reach for a reduction when you need a summary like a total or average.
Quick Check
Can you tell which operation changes a tensor shape?
Recap: Transform vs Summarize
Elementwise ops keep the shape and act per value; reductions like sum and mean collapse it, with dim and keepdim controlling exactly how. 🎯
Perguntas Frequentes
A aula “Operações Elemento a Elemento e Reduções” é grátis?
Sim — o texto completo de “Operações Elemento a Elemento e Reduções” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Deep Learning Academy, atualize para CoddyKit PRO. O curso de Deep Learning Academy inclui 4 aulas no total.
O que vou aprender em “Operações Elemento a Elemento e Reduções”?
Some, calcule a média e encontre o máximo nos eixos escolhidos Você pratica Deep Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Deep Learning Academy?
Nenhuma experiência prévia é necessária. Deep Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Operações Elemento a Elemento e Reduções”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Deep Learning Academy?
Sim. Cada aula de Deep Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Por Que Loops São Lentos para Matemática
- Operações Elemento a Elemento e Reduções
- Multiplicação de Matrizes com matmul e @
- Produtos Escalares Movimentam Cada Camada