Skip to content

Commit

Permalink
Rename num_classes to classes across entire repo (#657)
Browse files Browse the repository at this point in the history
* Rename num_classes to classes

* Fix find and replace mistake

* Fix accidental fstring removal

* Rename num_classes to classes for non-model uses

* More find-and-replace fixes

* One more f+r fix

* Fix non_max_supression

* Rename targets to class_predictions in non_max_supression
  • Loading branch information
Ian Johnson authored Aug 3, 2022
1 parent 0758c89 commit c4a6991
Show file tree
Hide file tree
Showing 23 changed files with 139 additions and 139 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from keras_cv.metrics import coco


def produce_random_data(include_confidence=False, num_images=128, num_classes=20):
def produce_random_data(include_confidence=False, num_images=128, classes=20):
"""Generates a fake list of bounding boxes for use in this test.
Returns:
Expand All @@ -23,9 +23,9 @@ def produce_random_data(include_confidence=False, num_images=128, num_classes=20
images = []
for _ in range(num_images):
num_boxes = math.floor(25 * random.uniform(0, 1))
classes = np.floor(np.random.rand(num_boxes, 1) * num_classes)
classes_in_image = np.floor(np.random.rand(num_boxes, 1) * classes)
bboxes = np.random.rand(num_boxes, 4)
boxes = np.concatenate([bboxes, classes], axis=-1)
boxes = np.concatenate([bboxes, classes_in_image], axis=-1)
if include_confidence:
confidence = np.random.rand(num_boxes, 1)
boxes = np.concatenate([boxes, confidence], axis=-1)
Expand Down
6 changes: 3 additions & 3 deletions benchmarks/metrics/coco/mean_average_precision_performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from keras_cv.metrics import coco


def produce_random_data(include_confidence=False, num_images=128, num_classes=20):
def produce_random_data(include_confidence=False, num_images=128, classes=20):
"""Generates a fake list of bounding boxes for use in this test.
Returns:
Expand All @@ -23,9 +23,9 @@ def produce_random_data(include_confidence=False, num_images=128, num_classes=20
images = []
for _ in range(num_images):
num_boxes = math.floor(25 * random.uniform(0, 1))
classes = np.floor(np.random.rand(num_boxes, 1) * num_classes)
classes_in_image = np.floor(np.random.rand(num_boxes, 1) * classes)
bboxes = np.random.rand(num_boxes, 4)
boxes = np.concatenate([bboxes, classes], axis=-1)
boxes = np.concatenate([bboxes, classes_in_image], axis=-1)
if include_confidence:
confidence = np.random.rand(num_boxes, 1)
boxes = np.concatenate([boxes, confidence], axis=-1)
Expand Down
6 changes: 3 additions & 3 deletions benchmarks/metrics/coco/recall_performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from keras_cv.metrics import coco


def produce_random_data(include_confidence=False, num_images=128, num_classes=20):
def produce_random_data(include_confidence=False, num_images=128, classes=20):
"""Generates a fake list of bounding boxes for use in this test.
Returns:
Expand All @@ -23,9 +23,9 @@ def produce_random_data(include_confidence=False, num_images=128, num_classes=20
images = []
for _ in range(num_images):
num_boxes = math.floor(25 * random.uniform(0, 1))
classes = np.floor(np.random.rand(num_boxes, 1) * num_classes)
classes_in_image = np.floor(np.random.rand(num_boxes, 1) * classes)
bboxes = np.random.rand(num_boxes, 4)
boxes = np.concatenate([bboxes, classes], axis=-1)
boxes = np.concatenate([bboxes, classes_in_image], axis=-1)
if include_confidence:
confidence = np.random.rand(num_boxes, 1)
boxes = np.concatenate([boxes, confidence], axis=-1)
Expand Down
8 changes: 4 additions & 4 deletions examples/layers/preprocessing/classification/demo_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
import tensorflow_datasets as tfds


def resize(image, label, img_size=(224, 224), num_classes=10):
def resize(image, label, img_size=(224, 224), classes=10):
image = tf.image.resize(image, img_size)
label = tf.one_hot(label, num_classes)
label = tf.one_hot(label, classes)
return {"images": image, "labels": label}


Expand All @@ -32,11 +32,11 @@ def load_oxford_dataset(
# Load dataset.
data, ds_info = tfds.load(name, as_supervised=as_supervised, with_info=True)
train_ds = data["train"]
num_classes = ds_info.features["label"].num_classes
classes = ds_info.features["label"].num_classes

# Get tf dataset.
train_ds = train_ds.map(
lambda x, y: resize(x, y, img_size=img_size, num_classes=num_classes)
lambda x, y: resize(x, y, img_size=img_size, classes=classes)
).batch(batch_size)
return train_ds

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
FLAGS = flags.FLAGS
FLAGS(sys.argv)

NUM_CLASSES = 1000
CLASSES = 1000
BATCH_SIZE = 256
IMAGE_SIZE = (224, 224)
EPOCHS = 250
Expand Down Expand Up @@ -94,7 +94,7 @@ def parse_imagenet_example(example):

# Decode label
label = tf.cast(tf.reshape(parsed[label_key], shape=()), dtype=tf.int32) - 1
label = tf.one_hot(label, NUM_CLASSES)
label = tf.one_hot(label, CLASSES)
return image, label


Expand Down Expand Up @@ -164,7 +164,7 @@ def augment(img, label):
model = DenseNet121(
include_rescaling=True,
include_top=True,
num_classes=NUM_CLASSES,
classes=CLASSES,
input_shape=IMAGE_SIZE + (3,),
)

Expand Down
16 changes: 8 additions & 8 deletions keras_cv/layers/object_detection/non_max_suppression.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class NonMaxSuppression(tf.keras.layers.Layer):
- [Yolo paper](https://arxiv.org/pdf/1506.02640)
Args:
num_classes: an integer representing the number of classes that a bounding
classes: an integer representing the number of classes that a bounding
box can belong to.
bounding_box_format: a case-insensitive string which is one of `"xyxy"`,
`"rel_xyxy"`, `"xyWH"`, `"center_xyWH"`, `"yxyx"`, `"rel_yxyx"`. The
Expand Down Expand Up @@ -67,7 +67,7 @@ class NonMaxSuppression(tf.keras.layers.Layer):
], dtype = np.float32)
nms = NonMaxSuppression(
num_classes=8,
classes=8,
bounding_box_format="center_xyWH",
iou_threshold=0.1
)
Expand All @@ -78,7 +78,7 @@ class NonMaxSuppression(tf.keras.layers.Layer):

def __init__(
self,
num_classes,
classes,
bounding_box_format,
confidence_threshold=0.05,
iou_threshold=0.5,
Expand All @@ -87,7 +87,7 @@ def __init__(
**kwargs,
):
super().__init__(**kwargs)
self.num_classes = num_classes
self.classes = classes
self.bounding_box_format = bounding_box_format
self.confidence_threshold = confidence_threshold
self.iou_threshold = iou_threshold
Expand All @@ -112,11 +112,11 @@ def call(self, predictions, images=None):

# preparing the predictions for TF NMS op
boxes = tf.expand_dims(predictions[..., :4], axis=2)
classes = tf.cast(predictions[..., 4], tf.int32)
class_predictions = tf.cast(predictions[..., 4], tf.int32)
scores = predictions[..., 5]

classes = tf.one_hot(classes, self.num_classes)
scores = tf.expand_dims(scores, axis=-1) * classes
class_predictions = tf.one_hot(class_predictions, self.classes)
scores = tf.expand_dims(scores, axis=-1) * class_predictions

# applying the NMS operation
nmsed_boxes = tf.image.combined_non_max_suppression(
Expand Down Expand Up @@ -181,7 +181,7 @@ def _encode_to_ragged(self, boxes, valid_detections):

def get_config(self):
config = {
"num_classes": self.num_classes,
"classes": self.classes,
"bounding_box_format": self.bounding_box_format,
"confidence_threshold": self.confidence_threshold,
"iou_threshold": self.iou_threshold,
Expand Down
10 changes: 5 additions & 5 deletions keras_cv/layers/object_detection/non_max_suppression_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

class NonMaxSuppressionTest(tf.test.TestCase):
def test_return_shapes(self):
layer = NonMaxSuppression(num_classes=4, bounding_box_format="xyWH")
layer = NonMaxSuppression(classes=4, bounding_box_format="xyWH")
images = tf.ones((3, 480, 480, 3))

boxes = tf.cast(tf.random.uniform((3, 5, 4), 0, 480, tf.int32), tf.float32)
Expand All @@ -32,7 +32,7 @@ def test_return_shapes(self):
self.assertEqual(boxes.shape, [3, None, 6])

def test_non_square_images(self):
layer = NonMaxSuppression(num_classes=4, bounding_box_format="xyxy")
layer = NonMaxSuppression(classes=4, bounding_box_format="xyxy")

boxes = tf.cast(tf.random.uniform((2, 5, 4), 0, 480, tf.int32), tf.float32)
classes = tf.cast(tf.random.uniform((2, 5, 1), 0, 4, tf.int32), tf.float32)
Expand All @@ -51,7 +51,7 @@ def test_non_square_images(self):
self.assertEqual(boxes.shape, [2, None, 6])

def test_different_channels(self):
layer = NonMaxSuppression(num_classes=4, bounding_box_format="xyWH")
layer = NonMaxSuppression(classes=4, bounding_box_format="xyWH")
images = tf.ones((3, 480, 480, 5))

boxes = tf.cast(tf.random.uniform((3, 5, 4), 0, 480, tf.int32), tf.float32)
Expand All @@ -66,7 +66,7 @@ def test_different_channels(self):
def test_in_a_model(self):
input1 = tf.keras.layers.Input([5, 6])
input2 = tf.keras.layers.Input([480, 480, 3])
layer = NonMaxSuppression(num_classes=4, bounding_box_format="xyWH")
layer = NonMaxSuppression(classes=4, bounding_box_format="xyWH")
outputs = layer(input1, input2)

model = tf.keras.models.Model(inputs=[input1, input2], outputs=outputs)
Expand All @@ -83,7 +83,7 @@ def test_in_a_model(self):
self.assertEqual(boxes.shape, [3, None, 6])

def test_without_images(self):
layer = NonMaxSuppression(num_classes=4, bounding_box_format="xyWH")
layer = NonMaxSuppression(classes=4, bounding_box_format="xyWH")

boxes = tf.cast(tf.random.uniform((3, 5, 4), 0, 480, tf.int32), tf.float32)
classes = tf.cast(tf.random.uniform((3, 5, 1), 0, 4, tf.int32), tf.float32)
Expand Down
4 changes: 2 additions & 2 deletions keras_cv/layers/preprocessing/cut_mix_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from keras_cv.layers.preprocessing.cut_mix import CutMix

NUM_CLASSES = 10
classes = 10


class CutMixTest(tf.test.TestCase):
Expand All @@ -24,7 +24,7 @@ def test_return_shapes(self):
# randomly sample labels
ys = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 2)
ys = tf.squeeze(ys)
ys = tf.one_hot(ys, NUM_CLASSES)
ys = tf.one_hot(ys, classes)

layer = CutMix(seed=1)
outputs = layer({"images": xs, "labels": ys})
Expand Down
4 changes: 2 additions & 2 deletions keras_cv/layers/preprocessing/fourier_mix_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from keras_cv.layers.preprocessing.fourier_mix import FourierMix

NUM_CLASSES = 10
classes = 10


class FourierMixTest(tf.test.TestCase):
Expand All @@ -24,7 +24,7 @@ def test_return_shapes(self):
# randomly sample labels
ys = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 2)
ys = tf.squeeze(ys)
ys = tf.one_hot(ys, NUM_CLASSES)
ys = tf.one_hot(ys, classes)

layer = FourierMix()
outputs = layer({"images": xs, "labels": ys})
Expand Down
4 changes: 2 additions & 2 deletions keras_cv/layers/preprocessing/mix_up_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from keras_cv.layers.preprocessing.mix_up import MixUp

NUM_CLASSES = 10
classes = 10


class MixUpTest(tf.test.TestCase):
Expand All @@ -24,7 +24,7 @@ def test_return_shapes(self):
# randomly sample labels
ys_labels = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 2)
ys_labels = tf.squeeze(ys_labels)
ys_labels = tf.one_hot(ys_labels, NUM_CLASSES)
ys_labels = tf.one_hot(ys_labels, classes)

# randomly sample bounding boxes
ys_bounding_boxes = tf.random.uniform((2, 3, 5), 0, 1)
Expand Down
4 changes: 2 additions & 2 deletions keras_cv/layers/preprocessing/random_shear_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from keras_cv.layers import preprocessing

NUM_CLASSES = 10
classes = 10


class RandomShearTest(tf.test.TestCase):
Expand Down Expand Up @@ -45,7 +45,7 @@ def test_return_shapes(self):
# randomly sample labels
ys_labels = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 2)
ys_labels = tf.squeeze(ys_labels)
ys_labels = tf.one_hot(ys_labels, NUM_CLASSES)
ys_labels = tf.one_hot(ys_labels, classes)

# randomly sample bounding boxes
ys_bounding_boxes = tf.random.uniform((2, 3, 7), 0, 1)
Expand Down
2 changes: 1 addition & 1 deletion keras_cv/layers/serialization_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ class SerializationTest(tf.test.TestCase, parameterized.TestCase):
"NonMaxSuppression",
object_detection.NonMaxSuppression,
{
"num_classes": 5,
"classes": 5,
"bounding_box_format": "xyxy",
"confidence_threshold": 0.5,
"iou_threshold": 0.5,
Expand Down
2 changes: 1 addition & 1 deletion keras_cv/metrics/coco/mean_average_precision.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class COCOMeanAveragePrecision(tf.keras.metrics.Metric):
Args:
class_ids: The class IDs to evaluate the metric for. To evaluate for
all classes in over a set of sequentially labelled classes, pass
`range(num_classes)`.
`range(classes)`.
bounding_box_format: Format of the incoming bounding boxes. Supported values
are "xywh", "center_xywh", "xyxy".
iou_thresholds: IoU thresholds over which to evaluate the recall. Must
Expand Down
2 changes: 1 addition & 1 deletion keras_cv/metrics/coco/recall.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class COCORecall(keras.metrics.Metric):
Args:
class_ids: The class IDs to evaluate the metric for. To evaluate for
all classes in over a set of sequentially labelled classes, pass
`range(num_classes)`.
`range(classes)`.
bounding_box_format: Format of the incoming bounding boxes. Supported values
are "xywh", "center_xywh", "xyxy".
iou_thresholds: IoU thresholds over which to evaluate the recall. Must
Expand Down
18 changes: 9 additions & 9 deletions keras_cv/models/csp_darknet.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def CSPDarkNet(
depth_multiplier=1.0,
width_multiplier=1.0,
use_depthwise=False,
num_classes=None,
classes=None,
weights=None,
input_shape=(None, None, 3),
input_tensor=None,
Expand All @@ -65,14 +65,14 @@ def CSPDarkNet(
include_rescaling: whether or not to Rescale the inputs.If set to True,
inputs will be passed through a `Rescaling(1/255.0)` layer.
include_top: whether to include the fully-connected layer at the top of
the network. If provided, `num_classes` must be provided.
the network. If provided, `classes` must be provided.
depth_multiplier: A float value used to calculate the base depth of the model
this changes based the detection model being used. Defaults to 1.0.
width_multiplier: A float value used to calculate the base width of the model
this changes based the detection model being used. Defaults to 1.0.
use_depthwise: a boolean value used to decide whether a depthwise conv block
should be used over a regular darknet block. Defaults to False
num_classes: optional number of classes to classify images into, only to be
classes: optional number of classes to classify images into, only to be
specified if `include_top` is True, and if no `weights` argument is
specified.
weights: one of `None` (random initialization), or a pretrained weight
Expand Down Expand Up @@ -102,10 +102,10 @@ def CSPDarkNet(
f"weights file to be loaded. Weights file not found at location: {weights}"
)

if include_top and not num_classes:
if include_top and not classes:
raise ValueError(
"If `include_top` is True, you should specify `num_classes`. Received: "
f"num_classes={num_classes}"
"If `include_top` is True, you should specify `classes`. Received: "
f"classes={classes}"
)

ConvBlock = DarknetConvBlockDepthwise if use_depthwise else DarknetConvBlock
Expand Down Expand Up @@ -165,9 +165,9 @@ def CSPDarkNet(

if include_top:
x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
x = layers.Dense(
num_classes, activation=classifier_activation, name="predictions"
)(x)
x = layers.Dense(classes, activation=classifier_activation, name="predictions")(
x
)
elif pooling == "avg":
x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
elif pooling == "max":
Expand Down
Loading

0 comments on commit c4a6991

Please sign in to comment.