A Dense layer computes output = activation(input @ weights + bias), where weights is a matrix connecting every input feature to every output unit, and bias is a separate learned value added to each output unit. The units argument sets how many output values the layer produces, and activation, like 'relu' or 'softmax', applies a nonlinearity afterward — without any activation, a Dense layer would just be a linear transformation, unable to model anything beyond straight lines and planes, however many layers you stack.
1Understanding tf.keras.layers.Dense()
A Dense layer computes output = activation(input @ weights + bias), where weights is a matrix connecting every input feature to every output unit, and bias is a separate learned value added to each output unit. The units argument sets how many output values the layer produces, and activation, like 'relu' or 'softmax', applies a nonlinearity afterward — without any activation, a Dense layer would just be a linear transformation, unable to model anything beyond straight lines and planes, however many layers you stack.
Stacking Dense layers without a nonlinear activation between them is mathematically pointless — several purely linear layers in a row always collapse into a single equivalent linear layer, so an activation like 'relu' between them is what actually gives a deep network the ability to learn non-linear patterns.
import tensorflow as tf
from tensorflow.keras import layers
layer = layers.Dense(4, activation='relu', input_shape=(3,))
output = layer(tf.constant([[1.0, 2.0, 3.0]]))
print(output.shape)2Practical Example
Here is a real-world application of tf.keras.layers.Dense() showing how it is used in production TensorFlow code.
import tensorflow as tf
from tensorflow.keras import layers
layer = layers.Dense(4, input_shape=(3,))
layer.build((None, 3))
print(len(layer.get_weights()))3Best Practices
Follow these guidelines when working with tf.keras.layers.Dense():
1. Always include a non-linear activation, like 'relu', on hidden Dense layers — stacking purely linear Dense layers collapses mathematically into a single linear layer
2. Match the final Dense layer's units and activation to the task: 'softmax' with units equal to the number of classes for multi-class classification, 'sigmoid' with 1 unit for binary classification, no activation for regression
3. Let every Dense layer after the first infer its input shape automatically, since Keras determines it from the previous layer's output shape
Tip: Stacking Dense layers without a nonlinear activation between them is mathematically pointless — several purely linear layers in a row always collapse into a single equivalent linear layer, so an activation like 'relu' between them is what actually gives a deep network the ability to learn non-linear patterns.
import tensorflow as tf
from tensorflow.keras import layers
layer = layers.Dense(4, activation='relu', input_shape=(3,))
output = layer(tf.constant([[1.0, 2.0, 3.0]]))
print(output.shape)