DEV Community

hallo word
hallo word

Posted on

https://rb.gy/zxg0ue

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を使うことで、実際に画像を分類する機械学習モデルを構築できます。

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay