Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions keras/src/layers/core/dense.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import math
import numbers

import ml_dtypes

Expand Down Expand Up @@ -94,6 +95,16 @@ def __init__(
lora_alpha=None,
**kwargs,
):
if (
not isinstance(units, numbers.Integral)
or isinstance(units, bool)
or units <= 0
):
raise ValueError(
"Received an invalid value for `units`, expected a positive "
f"integer. Received: units={units}"
)

super().__init__(activity_regularizer=activity_regularizer, **kwargs)
self.units = units
self.activation = activations.get(activation)
Expand Down
11 changes: 11 additions & 0 deletions keras/src/layers/core/dense_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ def test_dense_basics(self):
supports_masking=True,
)

@parameterized.named_parameters(
("zero", 0),
("negative", -3),
("float", 2.5),
("none", None),
("string", "64"),
)
def test_dense_invalid_units_raises(self, units):
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(units)

def test_dense_correctness(self):
# With bias and activation.
layer = layers.Dense(units=2, activation="relu")
Expand Down
Loading