作为扩散模型的一部分,我构建了这个完全连接的网络:
import torch
from torch import linalg as LA
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from torch.utils.data import TensorDataset, DataLoader, Dataset
import torch.optim as optim
import torch.nn as nn
import matplotlib.pyplot as plt
from tqdm import tqdm
lr = 0.0001
num_data = 3000
batch_size = 3000
num_epochs =3000
x_dim = 2 # dimension of input
beta1 = 0.5 # Beta1 hyperparameter for Adam optimizers
l2 = nn.MSELoss()
colors = px.colors.qualitative.T10
MODEL_PATH = 'denoiser.pth'
CONDITIONAL_MODEL_PATH = 'denoiser_conditional.pth'
# the denoiser
class NetD(nn.Module):
def __init__(self):
super(NetD, self).__init__()
# intput: [x0, x1, t]
self.fc = nn.Sequential(
nn.Linear(x_dim + 1, (x_dim + 1) * 8),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear((x_dim + 1) * 8, (x_dim + 1) * 20),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear((x_dim + 1) * 20, x_dim),
# output: [e0, e1]
)
def forward(self, x_t):
return self.fc(x_t)
首先我用统一的数据对其进行训练,如下所示:
它的形状是[3000,2]
现在我想在尺寸为 (50,50) 的图像的红色通道上训练模型:
import torchvision.transforms as transforms
import torchvision.models as models
# desired size of the output image
imsize =(50,50) # use small size if no GPU
loader = transforms.Compose([
transforms.Resize(imsize), # scale imported image
transforms.ToTensor()]) # transform it into a torch tensor
def image_loader(image_name):
image = Image.open(image_name)
image = loader(image).unsqueeze(0)
return image.to(device, torch.float)
cat=image_loader('/content/orange_cat.jpg')
red_channel = cat[:, 0, :, :] # Extract the red channel (R) of the image
C = 200 # Threshold value for red channel
density = torch.where(red_channel > 0.78, torch.tensor(1.0), torch.tensor(0.0))
data_1 = red_channel.squeeze().to(device)
据我了解,为了将图像的红色通道传递到 FC 网络->netD,数据的维数也应该为 2 (x,y),但我不太确定应该如何变换张量形状 [50 ,50]正确: 我尝试像这样改造它:
# Reshape the tensor to a 2-dimensional tensor
reshaped_red_channel = data_1.view(-1, 2)
它创建了一个大小为 [1250,2] 的张量,但我不确定它是否正确?据我了解,原始张量中的总元素 = 重塑张量中的总元素,因此它确实创建了原始向量的 2500 个元素
根据 pytorch 文档,
torch.linear
需要大小为 [*,H]
的输入,其中 * 表示事先可以有任意数量的维度,最后一个维度 H
是特征的数量。
在您的初始训练中,维度为
[3000,2]
,符合此标准。
查看
[1,50,50]
张量(红色通道)的方法有很多种,只要结果维度为 [*,2]
并且 * 中所有维度的乘积相加,在输入到线性层时都不会抛出错误最多1250*batch_size
。因此 view(-1,2)
将完成此任务并产生大小为 [1250*batch_size,2]
的结果。它在句法意义上是“正确的”,尽管在语义意义上可能不是。
值得考虑的是,查看图像的每种可能方式都保留了数据结构的不同部分。由于您正在处理图像,因此原始数据具有高度的空间结构。通过将此数据视为
[1250*batch_size,2]
,线性层维护的唯一结构是沿着图像的最后一个(可能是列)维度连续的像素值对之间的相关性。如果不了解您打算解决的问题的更多信息,就不能说这是否是一个问题,但乍一看,以这种方式处理高度结构化的图像数据对我来说似乎很奇怪,因为它丢弃了几乎所有的信息包含在图像中。仅根据像素强度很难描述图像的内容。