Linear Layer Shape Calculator
Calculate the output shape of a PyTorch nn.Linear layer. Enter input shape and out_features to see the output tensor dimensions instantly.
Built by Michael Lip
PyTorch Linear Layer Code
import torch.nn as nn
# Define Linear layer
linear = nn.Linear(in_features=512, out_features=10)
# Input: batch=32, features=512
x = torch.randn(32, 512)
output = linear(x)
print(output.shape) # torch.Size([32, 10])
# Parameters: in_features * out_features + out_features (bias)
print(sum(p.numel() for p in linear.parameters())) # 5130
# Common pattern: flatten CNN output → Linear
model = nn.Sequential(
nn.Flatten(), # (batch, C, H, W) → (batch, C*H*W)
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(),
nn.Linear(4096, 1000)
)
Frequently Asked Questions
What is the output shape of nn.Linear?
nn.Linear(in_features, out_features) transforms only the last dimension. For input [batch, in_features], output is [batch, out_features]. For input [batch, seq, in_features], output is [batch, seq, out_features].
How many parameters does a Linear layer have?
A Linear layer has in_features * out_features weights plus out_features biases (if bias=True). Total: in_features * out_features + out_features. For Linear(512, 10), that's 512*10 + 10 = 5,130 parameters.
Why do I get a shape error with Linear after Conv2d?
Conv2d outputs a 4D tensor [batch, channels, H, W], but Linear expects the last dimension to match in_features. You need to flatten first: use nn.Flatten() to convert [batch, C, H, W] to [batch, C*H*W], then set in_features = C*H*W.
Is this tool free?
Yes. All HeyTensor tools are free, run in your browser, and require no signup.
Does this work offline?
Once loaded, the tool runs entirely in your browser. No internet needed after the initial page load.
About This Tool
This tool is part of HeyTensor, a free suite of PyTorch and deep learning utilities. All calculations run entirely in your browser — no data is sent to any server. The source code is open on GitHub.
Contact
HeyTensor is built and maintained by Michael Lip. For questions or feedback, email [email protected].