# 创建一个类别条件扩散模型 在这节笔记本中,我们将阐述一种给扩散模型加条件信息的方法。具体来说,我们将接着[这个从头训练的例子](../unit1/02_diffusion_models_from_scratch_CN.ipynb)在 MNIST 上训练一个以类别为条件的扩散模型。这里我们可以在推理时指定我们要生成的是哪个数字。 就像本单元介绍中说的那样,这只是很多给扩散模型添加额外条件信息的方法中的一种,这里用它做示例是因为它比较简单。就像第一单元中“从走训练”的例子一样,这节笔记本也是为了解释说明的目的。如果你想,你也可以安全地跳过本节。 ## 配置和数据准备 ```python !pip install -q diffusers ```  |████████████████████████████████| 503 kB 7.2 MB/s  |████████████████████████████████| 182 kB 51.3 MB/s [?25h ```python import torch import torchvision from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader from diffusers import DDPMScheduler, UNet2DModel from matplotlib import pyplot as plt from tqdm.auto import tqdm device = 'mps' if torch.backends.mps.is_available() else 'cuda' if torch.cuda.is_available() else 'cpu' print(f'Using device: {device}') ``` Using device: cuda ```python # Load the dataset dataset = torchvision.datasets.MNIST(root="mnist/", train=True, download=True, transform=torchvision.transforms.ToTensor()) # Feed it into a dataloader (batch size 8 here just for demo) train_dataloader = DataLoader(dataset, batch_size=8, shuffle=True) # View some examples x, y = next(iter(train_dataloader)) print('Input shape:', x.shape) print('Labels:', y) plt.imshow(torchvision.utils.make_grid(x)[0], cmap='Greys'); ``` Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to mnist/MNIST/raw/train-images-idx3-ubyte.gz 0%| | 0/9912422 [00:00] ![png](02_class_conditioned_diffusion_model_example_CN_files/02_class_conditioned_diffusion_model_example_CN_10_21.png) 一旦训练结束,我们就可以通过输入不同的标签作为条件,来采样图片了: ```python #@markdown Sampling some different digits: # Prepare random x to start from, plus some desired labels y x = torch.randn(80, 1, 28, 28).to(device) y = torch.tensor([[i]*8 for i in range(10)]).flatten().to(device) # Sampling loop for i, t in tqdm(enumerate(noise_scheduler.timesteps)): # Get model pred with torch.no_grad(): residual = net(x, t, y) # Again, note that we pass in our labels y # Update sample with step x = noise_scheduler.step(residual, t, x).prev_sample # Show the results fig, ax = plt.subplots(1, 1, figsize=(12, 12)) ax.imshow(torchvision.utils.make_grid(x.detach().cpu().clip(-1, 1), nrow=8)[0], cmap='Greys') ``` 0it [00:00, ?it/s] ![png](02_class_conditioned_diffusion_model_example_CN_files/02_class_conditioned_diffusion_model_example_CN_12_2.png) 就是这么简单!我们现在已经对要生成的图片有所控制了。 希望你喜欢这个例子。一如既往地,如果你有问题,你随时可以在 Discord 上提出来。 ```python # 练习(选做):用同样方法在 FashionMNIST 数据集上试试。调节学习率、batch size 和训练的轮数(epochs)。 # 你能用比例子更少的训练时间得到些看起来不错的时尚相关的图片吗? ```