PHP 配列の要素を変数に代入

<?php
// $scores = [70, 90, 80];
// $firstScore = $scores[0];
// $secondScore = $scores[1];
// $thirdScore = $scores[2];
// list($firstScore, $secondScore, $thirdScore) = $scores;
// [$firstScore, $secondScore, $thirdScore] = $scores;
// echo $firstScore . PHP_EOL;
// echo $secondScore . PHP_EOL;
// echo $thirdScore . PHP_EOL;

$x = 10;
$y = 20;
[$y, $x] = [$x, $y];
echo $x . PHP_EOL;
echo $y . PHP_EOL;

二次元画像生成AI python

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
from tqdm import tqdm

# データセットの変換(リサイズと正規化)
transform = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,))  # ピクセル値を[-1, 1]の範囲にスケーリング
])

# AnimeFaceDatasetのロード
dataset = datasets.ImageFolder(root='C:/Users/tyosu/projects/anime_faces',transform=transform)
dataloader = DataLoader(dataset, batch_size=64, shuffle=True)

# Generator(生成モデル)
class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()
        self.main = nn.Sequential(
            nn.Linear(100, 256),
            nn.ReLU(True),
            nn.Linear(256, 512),
            nn.ReLU(True),
            nn.Linear(512, 1024),
            nn.ReLU(True),
            nn.Linear(1024, 64 * 64 * 3),
            nn.Tanh()
        )

    def forward(self, input):
        output = self.main(input)
        return output.view(-1, 3, 64, 64)

# Discriminator(判別モデル)
class Discriminator(nn.Module):
    def __init__(self):
        super(Discriminator, self).__init__()
        self.main = nn.Sequential(
            nn.Linear(64 * 64 * 3, 1024),
            nn.ReLU(True),
            nn.Linear(1024, 512),
            nn.ReLU(True),
            nn.Linear(512, 256),
            nn.ReLU(True),
            nn.Linear(256, 1),
            nn.Sigmoid()
        )

    def forward(self, input):
        input_flat = input.view(-1, 64 * 64 * 3)
        return self.main(input_flat)

# モデルのインスタンス化
G = Generator()
D = Discriminator()

# ロス関数とオプティマイザ
criterion = nn.BCELoss()
optimizerD = optim.Adam(D.parameters(), lr=0.0002)
optimizerG = optim.Adam(G.parameters(), lr=0.0002)

# ランダムノイズ生成関数
def generate_noise(batch_size):
    return torch.randn(batch_size, 100)

# トレーニングループ
num_epochs = 50
for epoch in range(num_epochs):
    for i, (real_images, _) in enumerate(tqdm(dataloader)):
        batch_size = real_images.size(0)

        # 本物の画像のラベルは1、偽物の画像のラベルは0
        real_labels = torch.ones(batch_size, 1)
        fake_labels = torch.zeros(batch_size, 1)

        # Discriminatorの学習
        optimizerD.zero_grad()
        outputs = D(real_images)
        real_loss = criterion(outputs, real_labels)

        noise = generate_noise(batch_size)
        fake_images = G(noise)
        outputs = D(fake_images.detach())
        fake_loss = criterion(outputs, fake_labels)

        d_loss = real_loss + fake_loss
        d_loss.backward()
        optimizerD.step()

        # Generatorの学習
        optimizerG.zero_grad()
        outputs = D(fake_images)
        g_loss = criterion(outputs, real_labels)  # 生成画像を本物と認識させたい
        g_loss.backward()
        optimizerG.step()

    print(f'Epoch [{epoch+1}/{num_epochs}] | d_loss: {d_loss.item()} | g_loss: {g_loss.item()}')

    # 生成された画像を表示
    if (epoch + 1) % 10 == 0:
        fake_images = G(generate_noise(64)).detach().cpu()
        plt.imshow(fake_images[0].permute(1, 2, 0) * 0.5 + 0.5)
       

簡単な画像生成AI python

import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torchvision.utils import save_image  # 画像保存のための関数
import os  # ファイルの保存先を指定するためのライブラリ

# VAEのエンコーダーとデコーダー
class VAE(nn.Module):
    def __init__(self, input_dim=784, hidden_dim=400, latent_dim=20):
        super(VAE, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.fc21 = nn.Linear(hidden_dim, latent_dim)
        self.fc22 = nn.Linear(hidden_dim, latent_dim)
        self.fc3 = nn.Linear(latent_dim, hidden_dim)
        self.fc4 = nn.Linear(hidden_dim, input_dim)

    def encode(self, x):
        h1 = torch.relu(self.fc1(x))
        return self.fc21(h1), self.fc22(h1)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return mu + eps * std

    def decode(self, z):
        h3 = torch.relu(self.fc3(z))
        return torch.sigmoid(self.fc4(h3))

    def forward(self, x):
        mu, logvar = self.encode(x.view(-1, 784))
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

# VAEの損失関数
def loss_function(recon_x, x, mu, logvar):
    BCE = nn.functional.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum')
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE + KLD

# モデルの定義とデータローダーの準備
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
vae = VAE().to(device)
optimizer = optim.Adam(vae.parameters(), lr=1e-3)

transform = transforms.ToTensor()
train_dataset = datasets.MNIST('.', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)

# トレーニングループ
vae.train()
for epoch in range(10):  # 10エポックで学習
    train_loss = 0
    for batch_idx, (data, _) in enumerate(train_loader):
        data = data.to(device)
        optimizer.zero_grad()
        recon_batch, mu, logvar = vae(data)
        loss = loss_function(recon_batch, data, mu, logvar)
        loss.backward()
        train_loss += loss.item()
        optimizer.step()
    
    print(f'Epoch {epoch + 1}, Loss: {train_loss / len(train_loader.dataset)}')

# 学習したモデルで画像生成
vae.eval()
with torch.no_grad():
    z = torch.randn(64, 20).to(device)
    sample = vae.decode(z).cpu()
    sample = sample.view(64, 1, 28, 28)  # 28x28の画像サイズに変換 (MNISTデータのフォーマット)
    
    # 保存先ディレクトリを指定
    os.makedirs('generated_images', exist_ok=True)
    save_image(sample, 'generated_images/sample.png')

    print("画像生成完了: 'generated_images/sample.png' に保存されました")