🤯🤯🤯 还在惊叹AI绘画的神奇?还在花钱求别人帮你生成图片?还在苦苦等待Midjourney的邀请码?别out了!今天,我们就来彻底揭秘AI绘画背后的核心技术——Diffusion模型,让你彻底搞懂它到底是怎么“画”出那些以假乱真的图像的!
🤔️ 焦虑的职场人,你是否也有这些困惑?
* 看到别人用AI生成的精美图片,羡慕不已,自己却无从下手?
* 想学习AI绘画,却被复杂的算法和代码吓退?
* 想提升自己的技能,却找不到通俗易懂的学习资料?
别担心!今天这篇文章,就是为你量身定制的!我们将用最通俗的语言,最形象的比喻,最简单的代码,带你一步步揭开Diffusion模型的神秘面纱!
先奉上源码:
import torch
import torchvision
from tqdm import tqdm
import matplotlib.pyplot as plt
from unet import SimpleUnet
from diffusion import NoiseScheduler
def sample(model, scheduler, num_samples, size, device="cpu"):
"""从噪声采样生成图像的函数
Args:
model: UNet模型,用于预测噪声
scheduler: 噪声调度器,包含采样所需的所有系数
num_samples: 要生成的样本数量
size: 生成图像的大小,如(3,32,32)
device: 运行设备
Returns:
生成的图像张量
"""
model.eval()
with torch.no_grad():
# 从标准正态分布采样初始噪声 x_T ~ N(0,I)
x_t = torch.randn(num_samples, *size).to(device)
# 逐步去噪,从t=T到t=0
for t in tqdm(reversed(range(scheduler.num_steps)), desc="Sampling"):
# 构造时间步batch
t_batch = torch.tensor([t] * num_samples).to(device)
# 获取采样需要的系数
sqrt_recip_alpha_bar = scheduler.get(scheduler.sqrt_recip_alphas_bar, t_batch, x_t.shape)
sqrt_recipm1_alpha_bar = scheduler.get(scheduler.sqrt_recipm1_alphas_bar, t_batch, x_t.shape)
posterior_mean_coef1 = scheduler.get(scheduler.posterior_mean_coef1, t_batch, x_t.shape)
posterior_mean_coef2 = scheduler.get(scheduler.posterior_mean_coef2, t_batch, x_t.shape)
# 预测噪声 ε_θ(x_t,t)
predicted_noise = model(x_t, t_batch)
# 计算x_0的预测值: x_0 = 1/sqrt(α_bar_t) * x_t - sqrt(1/α_bar_t-1) * ε_θ(x_t,t)
_x_0 = sqrt_recip_alpha_bar * x_t - sqrt_recipm1_alpha_bar * predicted_noise
# 计算后验分布均值 μ_θ(x_t,t)
model_mean = posterior_mean_coef1 * _x_0 + posterior_mean_coef2 * x_t
# 计算后验分布方差的对数值 log(σ_t^2)
model_log_var = scheduler.get(torch.log(torch.cat([scheduler.posterior_var[1:2], scheduler.betas[1:]])), t_batch, x_t.s