pytorch GAN生成对抗网络实例
作者:全栈的方向 时间:2022-06-30 03:41:27
我就废话不多说了,直接上代码吧!
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
torch.manual_seed(1)
np.random.seed(1)
BATCH_SIZE = 64
LR_G = 0.0001
LR_D = 0.0001
N_IDEAS = 5
ART_COMPONENTS = 15
PAINT_POINTS = np.vstack([np.linspace(-1,1,ART_COMPONENTS) for _ in range(BATCH_SIZE)])
def artist_works():
a = np.random.uniform(1,2,size=BATCH_SIZE)[:,np.newaxis]
paintings = a*np.power(PAINT_POINTS,2) + (a-1)
paintings = torch.from_numpy(paintings).float()
return Variable(paintings)
G = nn.Sequential(
nn.Linear(N_IDEAS,128),
nn.ReLU(),
nn.Linear(128,ART_COMPONENTS),
)
D = nn.Sequential(
nn.Linear(ART_COMPONENTS,128),
nn.ReLU(),
nn.Linear(128,1),
nn.Sigmoid(),
)
opt_D = torch.optim.Adam(D.parameters(),lr=LR_D)
opt_G = torch.optim.Adam(G.parameters(),lr=LR_G)
plt.ion()
for step in range(10000):
artist_paintings = artist_works()
G_ideas = Variable(torch.randn(BATCH_SIZE,N_IDEAS))
G_paintings = G(G_ideas)
prob_artist0 = D(artist_paintings)
prob_artist1 = D(G_paintings)
D_loss = - torch.mean(torch.log(prob_artist0) + torch.log(1-prob_artist1))
G_loss = torch.mean(torch.log(1 - prob_artist1))
opt_D.zero_grad()
D_loss.backward(retain_variables=True)
opt_D.step()
opt_G.zero_grad()
G_loss.backward()
opt_G.step()
if step % 50 == 0:
plt.cla()
plt.plot(PAINT_POINTS[0],G_paintings.data.numpy()[0],c='#4ad631',lw=3,label='Generated painting',)
plt.plot(PAINT_POINTS[0],2 * np.power(PAINT_POINTS[0], 2) + 1,c='#74BCFF',lw=3,label='upper bound',)
plt.plot(PAINT_POINTS[0],1 * np.power(PAINT_POINTS[0], 2) + 0,c='#FF9359',lw=3,label='lower bound',)
plt.text(-.5,2.3,'D accuracy=%.2f (0.5 for D to converge)' % prob_artist0.data.numpy().mean(), fontdict={'size':15})
plt.text(-.5, 2, 'D score= %.2f (-1.38 for G to converge)' % -D_loss.data.numpy(), fontdict={'size': 15})
plt.ylim((0,3))
plt.legend(loc='upper right', fontsize=12)
plt.draw()
plt.pause(0.01)
plt.ioff()
plt.show()
来源:https://blog.csdn.net/pureszgd/article/details/75095332
标签:pytorch,GAN,生成对抗网络
0
投稿
猜你喜欢
使用 Python 在京东上抢口罩的思路详解
2023-06-01 01:10:30
详解Selenium+PhantomJS+python简单实现爬虫的功能
2023-03-09 01:09:00
python3爬虫怎样构建请求header
2023-04-17 19:01:45
Python扩展内置类型详解
2023-03-19 17:23:36
python OpenCV图像直方图处理
2022-05-28 06:31:45
ASP使用xmlhttp调用WEBSERVICE文档
2008-05-30 13:56:00
Python实现的旋转数组功能算法示例
2021-09-11 20:49:46
TensorFlow2基本操作之合并分割与统计
2022-01-01 21:47:39
mysql中workbench实例详解
2024-01-15 01:45:03
pandas groupby 分组取每组的前几行记录方法
2021-06-19 05:52:20
Python绘制3d螺旋曲线图实例代码
2022-12-22 01:30:23
Mozilla 表达式 __noSuchMethod__
2024-04-18 09:42:21
实现asp长文章自动分页插件
2011-02-26 13:51:00
Python+OpenCV图片局部区域像素值处理详解
2023-10-26 12:59:22
Python通过yagmail实现发送邮件代码解析
2022-12-31 13:44:58
python判断列表的连续数字范围并分块的方法
2021-01-18 12:04:19
python三种数据结构及13种创建方法总结
2021-03-23 04:46:52
nodeJS express路由学习req.body与req.query方法实例详解
2024-06-05 09:52:34
MySQL中将一列以逗号分隔的值行转列的实现
2024-01-20 15:31:23
图文详解go语言反射实现原理
2024-02-08 05:01:31