PythonとPyTorchによる機械学習の基礎習得

Python基礎構文の習得

Pythonの制御構文と反復処理を学習。if文による条件分岐、for/whileループの活用方法を習得。

employee1 = {"name":"Yamada", "age":30, "salary":450000}
employee2 = {"name":"Tanaka", "age":28, "salary":380000}
employees = [employee1, employee2]

for emp in employees:
    for key, value in emp.items():
        print(f"{key}:{value}", end="\t")

PyTorchによるニューラルネットワーク構築

基本的なニューラルネットワークの実装方法を学習。重要なモジュールと関数の役割を理解。

import torch
import torch.nn as nn

class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten(start_dim=1)
        self.linear = nn.Linear(784, 256)
        self.activation = nn.ReLU(inplace=True)
    
    def forward(self, x):
        x = self.flatten(x)
        x = self.linear(x)
        x = self.activation(x)
        return x

自動微分システムの理解

PyTorchのautogradシステムによる勾配計算の仕組みを検証。requires_grad属性とgrad_fnの関係を分析。

a = torch.randn(3, 3, requires_grad=True)
b = torch.randn(3, 3)
b.requires_grad_(True)

z = a * 3 + b ** 2
output = z.mean()

print(f"a grad_fn: {a.grad_fn}")
print(f"z grad_fn: {z.grad_fn}")
print(f"output grad_fn: {output.grad_fn}")

モデルパラメータ最適化手法

データローダーと組み合わせたモデル訓練プロセスを実装。損失計算とパラメータ更新の流れを習得。

from torch.utils.data import DataLoader

train_loader = DataLoader(dataset, batch_size=64, shuffle=True)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    model.train()
    for batch_idx, (inputs, targets) in enumerate(train_loader):
        predictions = model(inputs)
        loss = loss_function(predictions, targets)
        
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        if batch_idx % 100 == 0:
            current = batch_idx * len(inputs)
            total = len(train_loader.dataset)
            print(f"Epoch:{epoch} Loss:{loss.item():.4f} [{current}/{total}]")

モデル保存と読み込み手法

学習済みモデルの保存方法と読み込み手法を実践。state_dictの扱い方を習得。

# モデル保存
torch.save(model.state_dict(), 'model_weights.pth')

# モデル読み込み
new_model = SimpleNet()
new_model.load_state_dict(torch.load('model_weights.pth'))
new_model.eval()

Pythonの高度な機能活用

リスト内包表記やジェネレータ式による効率的なコーディング手法を学習。並列処理の最適化方法を検証。

import time

names = ("Sato", "Suzuki", "Takahashi")
ages = (25, 30, 28)
departments = ("HR", "Engineering", "Sales")

# 並列処理による効率化
start = time.perf_counter()
for _ in range(10000):
    for name, age, dept in zip(names, ages, departments):
        print(f"{name}-{age}-{dept}")
end = time.perf_counter()
print(f"処理時間: {end - start:.4f}秒")

タグ: Python PyTorch ニューラルネットワーク 自動微分 モデル最適化

6月5日 19:56 投稿