## GAN和一维数据
https://blog.csdn.net/weixin_44719615/article/details/106966719?utm_medium=distribute.pc_relevant_download.none-task-blog-BlogCommendFromBaidu-4.nonecase&dist_request_id=d223260a-f1a7-4ce1-8a87-02562fbbb881&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-BlogCommendFromBaidu-4.nonecas
#环境用tensorflow2.0以上版本
import numpy as np
from numpy.random import rand, randn
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import pandas as pd
#输入真实样本数据,这里是在原来输入图片的代码修改的
def get_real_samples(n):
X = pd.read_excel('result1.xls')
y = np.ones((n, 1))
return X, y
#定义对抗模型,参数和模型都可以替换
def disc_model(input_dim=5):
model = Sequential()
model.add(Dense(28, activation='relu', input_dim=input_dim))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
#定义噪声输入,这个可以根据输入维度去自选
def noise_points(noise_dim, n):
noise = randn(n * noise_dim)
noise = noise.reshape(n, noise_dim)
return noise
#定义噪声和数据的一个匹配适应
def get_fake_samples(gen, noise_dim, n):
x_input = noise_points(noise_dim, n)
X = gen.predict(x_input)
y = np.zeros((n, 1))
return X, y
#定义生成模型
def gen_model(input_dim, output_dim=5):
model = Sequential()
model.add(Dense(23, activation='sigmoid', input_dim=input_dim))
model.add(Dense(output_dim, activation='linear'))
return model
#定义生成对抗模型的接口
def gan_model(disc, gen):
disc.trainable = False
model = Sequential()
model.add(gen)
model.add(disc)
model.compile(loss='binary_crossentropy', optimizer='adam')
return model
#训练模型
def train(g_model, d_model, gan_model, noise_dim, epochs=200000, batch_size=820, n_eval=100):
half_batch = batch_size // 2
for i in range(epochs):
x_real, y_real = get_real_samples(half_batch)
x_fake, y_fake = get_fake_samples(g_model, noise_dim, half_batch)
d_model.train_on_batch(x_real, y_real)
d_model.train_on_batch(x_fake, y_fake)
x_gan = noise_points(noise_dim, batch_size)
y = np.ones((batch_size, 1))
gan_model.train_on_batch(x_gan, y)
if (i + 1) % n_eval == 0:
show_performance(i + 1, g_model, d_model, noise_dim)
mingming = str(i) + '.txt'
np.savetxt(mingming, x_fake)
#将数据输出到文件里,可以将调下数据格式
def show_performance(epoch, g_model, d_model, noise_dim, n=410):
x_real, y_real = get_real_samples(n)
_, real_acc = d_model.evaluate(x_real, y_real, verbose=0)
x_fake, y_fake = get_fake_samples(g_model, noise_dim, n)
_, fake_acc = d_model.evaluate(x_fake, y_fake, verbose=0)
# print(epoch,real_acc,fake_acc)
a = [epoch, real_acc, fake_acc]
print(a)
b.append(a)
np.savetxt('Result.txt', b)
# plt.figure(figsize=(5,5))
# plt.scatter(x_real[:,0],x_real[:,1],color='red')
# plt.scatter(x_fake[:,0],x_fake[:,1],color='blue')
b = []
noise_dim =5
gen = gen_model(noise_dim)
disc = disc_model()
gan = gan_model(disc, gen)
train(gen, disc, gan, noise_dim)
#代码参考https://github.com/starhou/One-dimensional-GAN/commit/797e15044e8359626ee6b6667227ff8c5b394bf8
#视频参考https://www.bilibili.com/video/BV1f7411E7wU?p=4
```