0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[教師あり学習] 1. 線型多項分類器, 2. 多層ニューラルネットワーク, 3.畳み込みニューラルネットワーク

Posted at

教師あり学習の

  1. 線型多項分類器 (Linear/Logistic Classifier) : 分類
  2. 多層ニューラルネットワーク(MLP: Multi-Layer Perceptron) : 汎用
  3. 畳み込みニューラルネットワーク(CNN: Convolutional Neural Network) :特徴抽出・分類

を整理したいと思う。なお、分類器は 既存データのラベルを予測するだけ なので生成AIではありません。

1. 線型多項分類器 (Linear/Logistic Classifier)

線型分類器とは、入力特徴量 x に対して 線型関数 を使ってクラスを予測するモデルです。可能性の高さを1次関数で計算するモデルとも言われます。

線型多項分類器の代表例​

  • ソフトマックス回帰(Softmax Regression)​
    • 各クラスのスコアに対して確率分布を作る方法​
    • 交差エントロピー損失で学習​
  • 一対他法(One-vs-Rest, OvR)​
    • 各クラスごとに二値線型分類器を学習​
    • 推論時は「最も確信度が高いクラス」を選択​

特徴​

・線型なので計算が高速​
・高次元データでも扱いやすい​
・非線形な境界が必要な場合は、線型分類器単体では不十分

from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)

clf = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=200)
clf.fit(X, y)

print(clf.predict(X[:5]))

実行結果:
$ python3 linear_classifier.py
[0 0 0 0 0]

2. 多層ニューラルネットワーク(MLP)

人間の脳の神経回路を模した計算モデルで、入力から出力までをつなぐ「層」の集まりで構成される。​

  • 入力層(Input Layer):特徴量 xxx を受け取る​
  • 隠れ層(Hidden Layers):入力を加工して特徴を抽出​
  • 出力層(Output Layer):最終的な予測を出力​

多層ニューラルネットワークは 1つ以上の隠れ層を持つネットワーク のことです。​隠れ層があることで、単純な線形関数では表現できない複雑なパターンを学習できます。​

  • 表現力が高い:複雑な関数を近似できる​
  • 多層にするほど複雑なパターンを学習可能​
  • 訓練には大量のデータと計算リソースが必要
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score

X, y = load_digits(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

clf = MLPClassifier(hidden_layer_sizes=(100, 50), max_iter=300, random_state=42)

clf.fit(X_train, y_train)

y_pred = clf.predict(X_test)

print("Accuracy:", accuracy_score(y_test, y_pred))

実行結果
$ python3 mlp.py
Accuracy: 0.9666666666666667

3.畳み込みニューラルネットワーク(CNN)

CNNは、特に画像や時系列データなど、局所的なパターンが重要なデータに強いニューラルネットワークです。​

  • 通常の多層ニューラルネットワーク(全結合層)は、すべての入力に対して重みが接続されるのに対して​
  • CNNは 局所領域(小さな部分)だけをスライドさせながら処理する という仕組みを使います。​

この「局所領域を順に見る処理」を 畳み込み(convolution) と呼びます。​

CNNでは畳み込み層の後にプーリング層を置くことが多いです。最後に、抽出した特徴マップを平坦化して全結合層に入力し、分類や回帰などの最終出力を得ます。​

CNNは「局所的なパターンをフィルタでスキャンして特徴を抽出する層(畳み込み層)+重要な情報を圧縮する層(プーリング層)+最終判断の全結合層」からなる、画像や時系列に強いニューラルネットワークです。

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, ), (0.5,))
])

trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)

class SimpleCNN(nn.Module):
    def __init__(self):
        super(SimpleCNN, self).__init__()
        self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
        self.fc1 = nn.Linear(32 * 7 * 7, 128)
        self.fc2 = nn.Linear(128, 10)
        

    def forward(self, x):
        x = self.pool(torch.relu(self.conv1(x)))
        x = self.pool(torch.relu(self.conv2(x)))
        x = x.view(-1, 32 * 7 * 7)
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = SimpleCNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

for epoch in range(2):
    running_loss = 0.0
    for images, labels in trainloader:
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
    print(f'Epoch {epoch + 1}, Loss: {running_loss / len(trainloader):.4f}')

# Evaluate the model
correct, total = 0, 0
with torch.no_grad():
    for images, labels in testloader:
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f'Accuracy of the model on the test images: {100 * correct / total:.2f}%')

実行結果
$ python3 cnn.py
100%|██████████████████████████████████████████████████████████████████████████████| 9.91M/9.91M [00:04<00:00, 2.06MB/s]
100%|███████████████████████████████████████████████████████████████████████████████| 28.9k/28.9k [00:00<00:00, 136kB/s]
100%|██████████████████████████████████████████████████████████████████████████████| 1.65M/1.65M [00:01<00:00, 1.20MB/s]
100%|██████████████████████████████████████████████████████████████████████████████| 4.54k/4.54k [00:00<00:00, 1.05MB/s]
Epoch 1, Loss: 0.1991
Epoch 2, Loss: 0.0537
Accuracy of the model on the test images: 98.68%

4.まとめ

  • 線型多項分類器
    -- 入力→ラベル (分類)
  • MLP
    -- 入力→ラベル/値 (教師あり学習 / 汎用)
  • CNN
    -- 画像→ラベル (教師あり学習 / 特徴抽出・分類)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?