1.预处理函数(这里有一个问题,transforms.Normalize()函数的使用)
有博主写了 https://blog.csdn.net/xys430381_1/article/details/85724668
2.定义鉴别器
计算方式参考上一张 迁移学习的内容。最后输出向量的类型为256*6*6.
同时每次卷积过后,进行批归一化(这点与传统的方式不一样)+LeaKy ReLU
3.定义生成器(理解为鉴别器的逆过程,反卷积的过程)
4.训练(初始化参数)
def train(d,g,criterion,d_optimizer,g_optimizer,epochs=1,show_every=1000,print_every=10):
iter_count = 0
for epoch in range(epochs):
for inputs,_ in trainloader:
real_inputs = inputs
fake_inputs = g(torch.randn(5,100))
real_labels = torch.ones(real_inputs.size(0))
fake_labels = torch.zeros(5)
real_outputs = d(real_inputs)
d_loss_real = criterion(real_outputs,real_labels)
real_scores = real_outputs
fake_outputs = d(fake_inputs)
d_loss_fake = criterion(fake_outputs,fake_labels)
fake_scores = fake_outputs
d_loss = d_loss_real+d_loss_fake
d_optimizer.zero_grad()
d_loss.backward()
d_optimizer.step()
fake_inputs = g(torch.randn(5,100))
outputs = d(fake_inputs)
real_labels = torch.ones(outputs.size(0))
g_loss = criterion(outputs,real_labels)
g_optimizer.zero_grad()
g_loss.backward()
g_optimizer.step()
if (iter_count % show_every == 0):
print('Epoch:{},Iter: {}, D: {:.4}, G:{:.4}'.format(epoch,iter_count, d_loss.item(), g_loss.item()))
picname = "Epoch_"+str(epoch)+"Iter_"+str(iter_count)
imshow(torchvision.utils.make_grid(fake_inputs.data),picname)
save_param(d,'d_model.pkl')
save_param(g,'g_model.pkl')
if (iter_count%print_every == 0):
print('Epoch:{},Iter: {}, D: {:.4}, G:{:.4}'.format(epoch,iter_count, d_loss.item(), g_loss.item()))
iter_count += 1
print('Finished Training')
这里就是训练的过程:
最后训练就完事了,结果我没有完全跑出来,时间太长不想跑。
跑了一部分结果出来,大概是这样的效果啦!!
来源:CSDN
作者:小邢~
链接:https://blog.csdn.net/weixin_43384504/article/details/103236028