2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

猿でもわかるAIプログラミングシリーズ 🐵💻 | [第4回]画像認識AIをPythonで実装してみよう!

Posted at

1. はじめに:なぜ画像認識AIが必要なのか?

近年、AI(人工知能)の進化により、画像認識技術はさまざまな分野で活用されています。

  • 医療: レントゲン画像からの病気診断
  • 自動運転: 歩行者や信号の検知
  • ECサイト: 商品の自動タグ付け
  • セキュリティ: 顔認証システム

しかし、「実際にどうやって実装するの?」と疑問に思うエンジニアも多いでしょう。
この記事では、Pythonを使って簡単な画像認識AIをゼロから構築
し、実践的なノウハウを解説します!

🔖 ハッシュタグ
#AI #Python #画像認識


2. 画像認識AIの基本:CNN(畳み込みニューラルネットワーク)とは?

画像認識で最も使われる**CNN(Convolutional Neural Network)**は、以下の層で構成されます:

  1. 畳み込み層(Convolutional Layer) → 特徴抽出
  2. プーリング層(Pooling Layer) → 次元削減
  3. 全結合層(Fully Connected Layer) → 分類

CNNの構造
(CNNの基本アーキテクチャ)


3. 実装してみよう!Python + TensorFlowでMNIST分類

環境構築

pip install tensorflow numpy matplotlib

コード例:手書き数字(MNIST)認識

import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt

# データセット読み込み
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

# データ前処理
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255

# CNNモデル構築
model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')  # 0-9の10クラス分類
])

# モデルコンパイル
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 学習実行
history = model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels))

# 精度確認
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"Test Accuracy: {test_acc}")

実行結果例

Epoch 5/5
1875/1875 [==============================] - 10s 5ms/step - loss: 0.0456 - accuracy: 0.9855
Test Accuracy: 0.9885

98.85%の精度で手書き数字を認識できました!


4. 実践的なTips & よくある落とし穴

データ拡張(Data Augmentation)で過学習を防ぐ

from tensorflow.keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(rotation_range=10, width_shift_range=0.1)
datagen.fit(train_images)

GPUが使えない場合の対処法

export CUDA_VISIBLE_DEVICES=""  # CPU強制使用

⚠️ 学習が収束しない場合

  • 学習率(optimizerlr)を調整
  • Batch Sizeを小さくする(例: 32 → 16)

5. 応用編:カスタムデータセットで画像認識

独自の画像データで学習させる方法

from tensorflow.keras.preprocessing import image_dataset_from_directory

train_ds = image_dataset_from_directory(
    'data/train',  # 画像フォルダ
    image_size=(180, 180),
    batch_size=32
)

転移学習(Transfer Learning)で効率化

base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False)
base_model.trainable = False  # 特徴抽出層は凍結

6. まとめ:画像認識AIの未来

✅ メリット

  • 高精度な分類が可能
  • 転移学習で少量データでも学習可能

❌ デメリット

  • 計算リソースが必要(GPU推奨)
  • 適切な前処理が必須

今後の展望

  • **Edge AI(端末内推論)**の普及(例: TensorFlow Lite)
  • **Vision Transformer(ViT)**の台頭

「さあ、あなたも画像認識AIを実装してみよう!」 🚀
この記事を参考に、オリジナルのAIモデルを構築してください!

📌 質問やフィードバックはコメントへ!
(Zenn/Qiitaのコメント欄 or Twitterで議論しましょう!)

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?