def predict(latent_dim, height, width, channels): random_latent_vectors = np.random.normal(size=(100, latent_dim)) dcgan = DCGAN(latent_dim, height, width, channels) dcgan.load_weights('gan_epoch20.h5') # dcgan.load_weights('gan_epoch1.h5') generated_images = dcgan.predict(random_latent_vectors) for i, generated_image in enumerate(generated_images): img = image.array_to_img(denormalize(generated_image), scale=False) img.save(os.path.join('generated', str(i) + '.png'))
if args is None: exit() x_train, y_train = create_dataset( 128, 128, nSlices=1000, resize=1, directory='FluidArt/') # 3 channels = RGB assert (x_train.shape[0] > 0) x_train /= 255 # plot results to make sure data looks good! fig, axs = plt.subplots(4, 4) for i in range(4): for j in range(4): axs[i, j].imshow(x_train[np.random.randint(x_train.shape[0])]) axs[i, j].axis('off') plt.show() dcgan = DCGAN(img_rows=x_train[0].shape[0], img_cols=x_train[0].shape[1], channels=x_train[0].shape[2], latent_dim=256, name='fluid_256_128') try: dcgan.load_weights( generator_file="generator ({}).h5".format(dcgan.name), discriminator_file="discriminator ({}).h5".format(dcgan.name)) except: pass dcgan.train(x_train, epochs=args.epochs, batch_size=32, save_interval=500)
def make_post(): # make sure to load in the correct sized data dcgan = DCGAN(img_rows = 128, img_cols = 128, channels = 3, latent_dim=256, name='fluid_256_128') dcgan.load_weights(generator_file="generator ({}).h5".format(dcgan.name), discriminator_file="discriminator ({}).h5".format(dcgan.name)) # video settings fps = 30 maxTime = 20 # seconds frameCount = 0 time = 0 nframes = int( maxTime*fps ) # controls for animation seed_start = np.random.normal(1, 1, (4, dcgan.latent_dim)) latentSpeed = np.random.normal(3, 1, (4, dcgan.latent_dim)) vary = np.random.normal(1, 1, (4, nframes, dcgan.latent_dim)) # randomize image transformations #rhue = np.random.random() rotation = 360 * np.round(np.random.random((4,))*4)/4 # random rotation flip = np.random.randint(0,4,(4,)) # 0=normal, 1=y-axis, 2=x-axis, 3=transpose # latent parameter animation for k in range(4): time = 0 # for each image in animation for i in range(nframes): # change the latent variables for j in range(dcgan.latent_dim): vary[k][i][j] = seed_start[k][j] + np.sin( 2*np.pi*(time/maxTime) * latentSpeed[k][j] ) time += 1./fps imgs = [] for k in range(4): imgs.append( dcgan.generator.predict(vary[k]) ) imgs = np.array(imgs) # create animation animated_gif = AnimatedGif() for i in range(nframes): for k in range(4): imgs[k,i] = create_mosaic( imgs[k,i], rotation[k], flip[k] ) animated_gif.add(imgs[:,i]) animated_gif.save('artificial_art.mp4',fps=fps) count = np.loadtxt('count.txt') with open('hashtags.txt') as fp: hashtags = fp.readlines() hashtags = [hashtags[i].strip() for i in range(len(hashtags))] message = "Automated Artificial Art v 1.{:.1f} - machine hallucinations from an artificial neural network \n \n#".format(count[0]) message = message + " #".join( np.random.choice(hashtags,4,replace=False)) with open('twitter_api_keys.json') as f: data = json.load(f) api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret= data["consumer_secret"], access_token_key=data["access_token"], access_token_secret=data["access_secret"]) api.PostUpdate(message, media="artificial_art.mp4" ) count += 1 np.savetxt('count.txt',count)
start_seed = None target_seed = None steps = 199 linear_step_frames = {} spherical_step_frames = {} for n, step_frames in zip(['linear', 'spherical'], [linear_step_frames, spherical_step_frames]): for model in models: gan = DCGAN(name=model, reload=True) gan.load_weights(250) if start_seed is None: start_seed, target_seed = gan.generate_random_noise(2) for s, val in enumerate([s / steps for s in range(steps + 1)]): if n == 'spherical': seed = np.expand_dims(slerp(val, start_seed, target_seed), axis=0) elif n == 'linear': seed = np.expand_dims((val * target_seed), axis=0) if s not in step_frames: step_frames[s] = []
os.path.basename(settings["g_weight_path"]).replace( "generator_", "").replace(".h5", "")) + 1 print("使用するGeneratorの重みは {} ".format(settings["g_weight_path"])) print() print("使用するDiscriminatorの重みは {}".format(settings["d_weight_path"])) # データ・セットの用意 X_test, y_test = load_data(test_path_list) # データの正規化 X_test = normalize(X_test) input_shape = X_test[0].shape # dcganを用意する dcgan = DCGAN(settings["input_dim"], input_shape) dcgan.load_weights(d_weight=settings["d_weight_path"], g_weight=settings["g_weight_path"]) # 保存先rootフォルダの指定 start = time.time() # AnoGANインスタンスの生成 anogan = ANOGAN(settings["input_dim"], dcgan.g) anogan.compile(anogan_optim) with open(save_score_path, "w") as f: f.write("filenam,anomaly_score" + "\n") for i, (test_img, test_path) in enumerate(zip(X_test, test_path_list)): filename = os.path.basename(test_path)[:-4] loop_start = time.time() test_img = test_img[np.newaxis, :, :, :]
# parse arguments args = parse_args() if args is None: exit() x_train, y_train = create_dataset( 128, 128, nSlices=1000, resize=0.5, directory='Space/Galaxy/') # 3 channels = RGB assert (x_train.shape[0] > 0) x_train /= 255 # plot results to make sure data looks good! fig, axs = plt.subplots(4, 4) for i in range(4): for j in range(4): axs[i, j].imshow(x_train[np.random.randint(x_train.shape[0])]) axs[i, j].axis('off') plt.show() dcgan = DCGAN(img_rows=x_train[0].shape[0], img_cols=x_train[0].shape[1], channels=x_train[0].shape[2], latent_dim=128, name='space_128_128') dcgan.load_weights(generator_file="generator (space_128_128).h5", discriminator_file="discriminator (space_128_128).h5") dcgan.train(x_train, epochs=args.epochs, batch_size=32, save_interval=100)
from keras.optimizers import Adam from data_loader import load_cucumber from train import normalize, denormalize if __name__ == '__main__': iterations = 100 input_dim = 30 anogan_optim = Adam(lr=0.001, amsgrad=True) ### 0. prepare data X_train, X_test, y_test = load_cucumber() X_train = normalize(X_train) X_test = normalize(X_test) input_shape = X_train[0].shape ### 1. train generator & discriminator dcgan = DCGAN(input_dim, input_shape) dcgan.load_weights('weights/generator_3999.h5', 'weights/discriminator_3999.h5') for i, test_img in enumerate(X_test): test_img = test_img[np.newaxis,:,:,:] anogan = ANOGAN(input_dim, dcgan.g) anogan.compile(anogan_optim) anomaly_score, generated_img = anogan.compute_anomaly_score(test_img, iterations) generated_img = denormalize(generated_img) imgs = np.concatenate((denormalize(test_img[0]), generated_img[0]), axis=1) cv2.imwrite('predict' + os.sep + str(int(anomaly_score)) + '_' + str(i) + '.png', imgs) print(str(i) + ' %.2f'%anomaly_score) with open('scores.txt', 'a') as f: f.write(str(anomaly_score) + '\n')