DEV Community

tgb yhn
tgb yhn

Posted on

https://rb.gy/l2hewa

TensorFlowを用いた画像分類の基本

はじめに

TensorFlowは画像分類の実装に最適なライブラリの一つです。本記事では、TensorFlowを用いて画像分類モデルを構築し、実際に動作させる方法を解説します。

画像分類の概念

画像分類は、一般的なタスクである「特徴抽出」と「分類器の構築」からなります。CNNは、画像から関連する特徴を抽出し、分類器で判定する仕組みを持っています。

TensorFlowでのデータ前処理

画像分類のために、先にデータの前処理を行います。

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(rescale=1./255)
dataset = datagen.flow_from_directory("data/train", target_size=(150, 150), batch_size=32, class_mode='binary')
Enter fullscreen mode Exit fullscreen mode

CNNの構築

CNNは、複数の小さなフィルタを通じて特徴を抽出する機構です。

from tensorflow.keras import layers, models

model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(128, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Flatten(),
    layers.Dense(512, activation='relu'),
    layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
Enter fullscreen mode Exit fullscreen mode

モデルの学習と評価

history = model.fit(dataset, epochs=10)
Enter fullscreen mode Exit fullscreen mode

おわりに

TensorFlowを使うことで、実際に画像を分類する機械学習モデルを構築できます。

Top comments (0)