Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ja/hub/tutorials/cropnet_cassava.ipynb
25118 views
Kernel: Python 3
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==============================================================================

CropNet: Cassava Disease Detection

このノートブックでは、TensorFlow Hub の CropNet キャッサバの病気の分類モデルの使用方法を説明します。このモデルはキャッサバの葉の画像を 6 つのクラスのいずれかに分類します。クラスは斑点細菌病、褐色条斑病、緑ダニ、モザイク病、健康、不明です。

この Colab では、以下の方法を実演します。

  • TensorFlow Hub からモデル https://tfhub.dev/google/cropnet/classifier/cassava_disease_V1/2 を読み込む。

  • TensorFlow Datasets (TFDS) からキャッサバデータセットを読み込む。

  • キャッサバの葉の画像を、4 つの異なるキャッサバの病気のカテゴリ、あるいは健康または不明として分類する。

  • 分類器の精度を評価し、ドメイン外の画像を適用した際のモデルのロバスト性を検査する。

インポートとセットアップ

!pip install matplotlib==3.2.2
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_hub as hub
#@title Helper function for displaying examples 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 = np.ceil(np.sqrt(batch_size)) y = 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()

データセット

TFDS からキャッサバデータセットを読み込みます。

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

データセットの情報を見て、説明や引用、例の数などの詳細情報を確認しましょう。

info

キャッサバデータセットには、健康なキャッサバの葉とそれぞれ異なる病気を持つ 4 枚のキャッサバの葉の画像があります。モデルはこれらの全てのクラスの予測ができ、予測に自信がない場合、モデルは 6 番目の "unknown(不明)" のクラスを予測します。

# 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])

データをモデルに送る前に、少し前処理をする必要があります。モデルは RGB チャンネル値が [0, 1] の 224 x 224 の画像を想定しています。画像を正規化してサイズを変更しましょう。

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

データセットからいくつかの例を見てみましょう。

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

モデル

TF-Hub から分類器を読み込んで予測値をいくつか取得し、複数の例のモデルの予測値を見てみましょう。

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)

評価とロバスト性

データセットを分割した場合の分類器の精度を測定してみましょう。また、キャッサバ以外のデータセットで性能を評価して、モデルのロバスト性を調べることもできます。iNaturalist や豆など、他の植物のデータセット画像を使用すると、モデルは殆ど全ての画像に対して不明を返すはずです。

#@title Parameters {run: "auto"} DATASET = 'cassava' #@param {type:"string"} ['cassava', 'beans', 'i_naturalist2017'] DATASET_SPLIT = 'test' #@param {type:"string"} ['train', 'test', 'validation'] BATCH_SIZE = 32 #@param {type:"integer"} MAX_EXAMPLES = 1000 #@param {type:"integer"}
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()))

詳細情報