资源简介
利用gan神经网络生成一维数据,代码有备注,真实数据为一个列表。利用gan神经网络生成一维数据,代码有备注,真实数据为一个列表。
代码片段和文件信息
#coding=utf-8
# 实现简单的DCGAN(深度卷积生成对抗网络)
import warnings
from keras.layers import Dense LeakyReLU BatchNormalization Input Dropout
from keras.layers import Activation
import matplotlib.pyplot as plt
from keras.models import Sequential Model load_model
from keras.optimizers import adam
from keras.utils import plot_model
warnings.filterwarnings(“ignore“)
import numpy as np
import csv
from sklearn.metrics import mean_squared_error
def uniform_sampling(n_sample dim):
# 均匀分布采样
return np.random.uniform(0 1 size=(n_sample dim))
def normal_sampling(n_sample dim):
# 均匀分布采样
return np.random.randn(n_sample dim)
# 构建判别网络
d_model = Sequential()
d_model.add(Dense(units=64 input_dim=1))
d_model.add(LeakyReLU(alpha=0.2))
d_model.add(BatchNormalization(momentum=0.8))
d_model.add(Dense(256))
d_model.add(LeakyReLU(alpha=0.2))
d_model.add(BatchNormalization(momentum=0.8))
d_model.add(Activation(‘tanh‘))
d_model.add(Dense(1 activation=‘sigmoid‘)) # 输出样本标记为1,即假样本的概率
d_model.summary()
# 构建生成网络
g_model = Sequential()
g_model.add(Dense(units=64 input_dim=1))
g_model.add(LeakyReLU(alpha=0.2))
g_model.add(BatchNormalization(momentum=0.8))
g_model.add(Dense(256))
g_model.add(LeakyReLU(alpha=0.2))
g_model.add(BatchNormalization(momentum=0.8))
g_model.add(Activation(‘tanh‘))
g_model.add(Dense(1 activation=‘tanh‘))
g_model.summary()
class DCGAN:
def __init__(self d_model g_model
input_dim=1 g_dim=1
max_step=200 sample_size=256 d_iter=3 kind=‘normal‘):
self.input_dim = input_dim # 图像的展开维度,即判别网络的输入维度
self.g_dim = g_dim # 随机噪声维度,即生成网络的输入维度
self.max_step = max_step # 整个模型的迭代次数
self.sample_size = sample_size # 训练过程中小批量采样的个数的一半
self.d_iter = d_iter # 每次迭代,判别网络训练的次数
self.kind = kind # 随机噪声分布类型
self.d_model = d_model # 判别模型
self.g_model = g_model # 生成模型
self.m_model = self.merge_model() # 合并模型
self.optimizer = adam(lr=0.0002 beta_1=0.5)
self.d_model.compile(optimizer=self.optimizer loss=‘binary_crossentropy‘)
def merge_model(self):
# 合并生成网络与判别网络
noise = Input(shape=(self.g_dim))
gen_sample = self.g_model(noise)
self.d_model.trainable = False # 固定判别网络,训练合并网络等同与训练生成网络
d_output = self.d_model(gen_sample)
m_model = Model(noise d_output) # 模型输出生成样本的预测结果,越接近0越好
m_model.compile(optimizer=‘adam‘ loss=‘binary_crossentropy‘)
return m_model
def gen_noise(self num_sample):
# 生成随机噪声数据
if self.kind == ‘normal‘:
f = normal_sampling
elif self.kind == ‘uniform‘:
f = uniform_sampling
else:
raise ValueError(‘暂不支持分布{}‘.format(self.kind))
return f(num_sample self.g_dim)
def gen_real_data(self train_data):
# 真实样本采样
n_samples = train_data.shape[0]
i
评论
共有 条评论