<br />

|---|---|---|---|---|
| [![](https://www.tensorflow.org/images/tf_logo_32px.png)View on TensorFlow.org](https://www.tensorflow.org/hub/tutorials/cropnet_cassava) | [![](https://www.tensorflow.org/images/colab_logo_32px.png)Run in Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/hub/tutorials/cropnet_cassava.ipynb) | [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png)View on GitHub](https://github.com/tensorflow/docs/blob/master/site/en/hub/tutorials/cropnet_cassava.ipynb) | [![](https://www.tensorflow.org/images/download_logo_32px.png)Download notebook](https://storage.googleapis.com/tensorflow_docs/docs/site/en/hub/tutorials/cropnet_cassava.ipynb) | [![](https://www.tensorflow.org/images/hub_logo_32px.png)See TF Hub model](https://tfhub.dev/google/cropnet/classifier/cassava_disease_V1/2) |

This notebook shows how to use the CropNet [cassava disease classifier](https://tfhub.dev/google/cropnet/classifier/cassava_disease_V1/2) model from **TensorFlow Hub** . The model classifies images of cassava leaves into one of 6 classes: *bacterial blight, brown streak disease, green mite, mosaic disease, healthy, or unknown*.

This colab demonstrates how to:

- Load the <https://tfhub.dev/google/cropnet/classifier/cassava_disease_V1/2> model from **TensorFlow Hub**
- Load the [cassava](https://www.tensorflow.org/datasets/catalog/cassava) dataset from **TensorFlow Datasets (TFDS)**
- Classify images of cassava leaves into 4 distinct cassava disease categories or as healthy or unknown.
- Evaluate the *accuracy* of the classifier and look at how *robust* the model is when applied to out of domain images.

## Imports and setup

    pip install -U -q matplotlib

    import numpy as np
    import matplotlib.pyplot as plt

    import tensorflow as tf
    import tensorflow_datasets as tfds
    import tensorflow_hub as hub

```
/tmpfs/src/tf_docs_env/lib/python3.11/site-packages/tensorflow_hub/__init__.py:61: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81.
  from pkg_resources import parse_version
```

### Helper function for displaying examples

<br />

<button type="button" class="button-red button expand-control">Toggle code</button>

<br />

    def plot(examples, predictions=None):
      # Get the images, labels, and optionally predictions
      images = examples['image']
      labels = examples['label']
      batch_size = len(images)
      if predictions is None:
        predictions = batch_size * [None]

      # Configure the layout of the grid
      x = int(np.ceil(np.sqrt(batch_size)))
      y = int(np.ceil(batch_size / x))
      fig = plt.figure(figsize=(x * 6, y * 7))

      for i, (image, label, prediction) in enumerate(zip(images, labels, predictions)):
        # Render the image
        ax = fig.add_subplot(x, y, i+1)
        ax.imshow(image, aspect='auto')
        ax.grid(False)
        ax.set_xticks([])
        ax.set_yticks([])

        # Display the label and optionally prediction
        x_label = 'Label: ' + name_map[class_names[label]]
        if prediction is not None:
          x_label = 'Prediction: ' + name_map[class_names[prediction]] + '\n' + x_label
          ax.xaxis.label.set_color('green' if label == prediction else 'red')
        ax.set_xlabel(x_label)

      plt.show()

<br />

<br />

## Dataset

Let's load the *cassava* dataset from TFDS

    dataset, info = tfds.load('cassava', with_info=True)

```
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
E0000 00:00:1793885543.624760   82486 cuda_platform.cc:52] failed call to cuInit: INTERNAL: CUDA error: Failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected
```

Let's take a look at the dataset info to learn more about it, like the description and citation and information about how many examples are available

    info

```
tfds.core.DatasetInfo(
    name='cassava',
    full_name='cassava/0.1.0',
    description="""
    Cassava consists of leaf images for the cassava plant depicting healthy and
    four (4) disease conditions; Cassava Mosaic Disease (CMD), Cassava Bacterial
    Blight (CBB), Cassava Greem Mite (CGM) and Cassava Brown Streak Disease (CBSD).
    Dataset consists of a total of 9430 labelled images.
    The 9430 labelled images are split into a training set (5656), a test set(1885)
    and a validation set (1889). The number of images per class are unbalanced with
    the two disease classes CMD and CBSD having 72% of the images.
    """,
    homepage='https://www.kaggle.com/c/cassava-disease/overview',
    data_dir='gs://tensorflow-datasets/datasets/cassava/0.1.0',
    file_format=tfrecord,
    download_size=1.26 GiB,
    dataset_size=Unknown size,
    features=FeaturesDict({
        'image': Image(shape=(None, None, 3), dtype=uint8),
        'image/filename': Text(shape=(), dtype=string),
        'label': ClassLabel(shape=(), dtype=int64, num_classes=5),
    }),
    supervised_keys=('image', 'label'),
    disable_shuffling=False,
    nondeterministic_order=False,
    splits={
        'test': <SplitInfo num_examples=1885, num_shards=4>,
        'train': <SplitInfo num_examples=5656, num_shards=8>,
        'validation': <SplitInfo num_examples=1889, num_shards=4>,
    },
    citation="""@misc{mwebaze2019icassava,
        title={iCassava 2019Fine-Grained Visual Categorization Challenge},
        author={Ernest Mwebaze and Timnit Gebru and Andrea Frome and Solomon Nsumba and Jeremy Tusubira},
        year={2019},
        eprint={1908.02900},
        archivePrefix={arXiv},
        primaryClass={cs.CV}
    }""",
)
```

The *cassava* dataset has images of cassava leaves with 4 distinct diseases as well as healthy cassava leaves. The model can predict all of these classes as well as sixth class for "unknown" when the model is not confident in its prediction.

    # Extend the cassava dataset classes with 'unknown'
    class_names = info.features['label'].names + ['unknown']

    # Map the class names to human readable names
    name_map = dict(
        cmd='Mosaic Disease',
        cbb='Bacterial Blight',
        cgm='Green Mite',
        cbsd='Brown Streak Disease',
        healthy='Healthy',
        unknown='Unknown')

    print(len(class_names), 'classes:')
    print(class_names)
    print([name_map[name] for name in class_names])

```
6 classes:
['cbb', 'cbsd', 'cgm', 'cmd', 'healthy', 'unknown']
['Bacterial Blight', 'Brown Streak Disease', 'Green Mite', 'Mosaic Disease', 'Healthy', 'Unknown']
```

Before we can feed the data to the model, we need to do a bit of preprocessing. The model expects 224 x 224 images with RGB channel values in \[0, 1\]. Let's normalize and resize the images.

    def preprocess_fn(data):
      image = data['image']

      # Normalize [0, 255] to [0, 1]
      image = tf.cast(image, tf.float32)
      image = image / 255.

      # Resize the images to 224 x 224
      image = tf.image.resize(image, (224, 224))

      data['image'] = image
      return data

Let's take a look at a few examples from the dataset

    batch = dataset['validation'].map(preprocess_fn).batch(25).as_numpy_iterator()
    examples = next(batch)
    plot(examples)

![png](https://www.tensorflow.org/static/hub/tutorials/cropnet_cassava_files/output_j6LkAxv3f-aJ_0.png)

## Model

Let's load the classifier from TF Hub and get some predictions and see the predictions of the model is on a few examples

    classifier = hub.KerasLayer('https://tfhub.dev/google/cropnet/classifier/cassava_disease_V1/2')
    probabilities = classifier(examples['image'])
    predictions = tf.argmax(probabilities, axis=-1)

    plot(examples, predictions)

![png](https://www.tensorflow.org/static/hub/tutorials/cropnet_cassava_files/output_MTQA1YAltfRZ_0.png)

## Evaluation \& robustness

Let's measure the *accuracy* of our classifier on a split of the dataset. We can also look at the *robustness* of the model by evaluating its performance on a non-cassava dataset. For image of other plant datasets like iNaturalist or beans, the model should almost always return *unknown*.

### Parameters

<br />

<button type="button" class="button-red button expand-control">Toggle code</button>

<br />

    DATASET = 'cassava' 
    DATASET_SPLIT = 'test'
    BATCH_SIZE =  32
    MAX_EXAMPLES = 1000

<br />

<br />

    def label_to_unknown_fn(data):
      data['label'] = 5  # Override label to unknown.
      return data

    # Preprocess the examples and map the image label to unknown for non-cassava datasets.
    ds = tfds.load(DATASET, split=DATASET_SPLIT).map(preprocess_fn).take(MAX_EXAMPLES)
    dataset_description = DATASET
    if DATASET != 'cassava':
      ds = ds.map(label_to_unknown_fn)
      dataset_description += ' (labels mapped to unknown)'
    ds = ds.batch(BATCH_SIZE)

    # Calculate the accuracy of the model
    metric = tf.keras.metrics.Accuracy()
    for examples in ds:
      probabilities = classifier(examples['image'])
      predictions = tf.math.argmax(probabilities, axis=-1)
      labels = examples['label']
      metric.update_state(labels, predictions)

    print('Accuracy on %s: %.2f' % (dataset_description, metric.result().numpy()))

```
Accuracy on cassava: 0.88
```

## Learn more

- Learn more about the model on TensorFlow Hub: <https://tfhub.dev/google/cropnet/classifier/cassava_disease_V1/2>
- Learn how to build a custom image classifier running on a mobile phone with [ML Kit](https://developers.google.com/ml-kit/custom-models#tfhub) with the [TensorFlow Lite version of this model](https://tfhub.dev/google/lite-model/cropnet/classifier/cassava_disease_V1/1).