{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Reference \nhttps://machinelearningmastery.com/how-to-develop-a-generative-adversarial-network-for-a-cifar-10-small-object-photographs-from-scratch/","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\n\nimport os\nimport re\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport math\nfrom numpy import expand_dims\nfrom numpy import ones\nfrom numpy import zeros\nfrom numpy.random import rand\nfrom numpy.random import randint\nfrom matplotlib import pyplot as plt\n\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\nimport tensorflow_addons as tfa\nfrom sklearn.model_selection import StratifiedKFold\nfrom tqdm import tqdm\n\n#import efficientnet.tfkeras as efn\n\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow.keras import backend as K\nimport tensorflow_addons as tfa\nfrom numpy.random import randn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Configuration\nEPOCHS = 3\nBATCH_SIZE = 4 # * strategy.num_replicas_in_sync\nimg_size = 192\nIMAGE_SIZE = [img_size,img_size]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def define_vgg16_discriminator(in_shape=(img_size,img_size,3)):\n    # Relu modified to LeakyRelu \n    # as described in paper works better for GAN discriminator\n    # using VGG16 as backbone for this\n    with strategy.scope():\n        model = tf.keras.Sequential()\n        tflayer = tf.keras.layers\n\n        model.add(tflayer.Conv2D(input_shape=in_shape,filters=64,kernel_size=(3,3),padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=64,kernel_size=(3,3),padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.MaxPool2D(pool_size=(2,2),strides=(2,2)))\n\n        model.add(tflayer.Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.MaxPool2D(pool_size=(2,2),strides=(2,2)))\n\n        model.add(tflayer.Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.MaxPool2D(pool_size=(2,2),strides=(2,2)))\n\n        model.add(tflayer.Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.MaxPool2D(pool_size=(2,2),strides=(2,2)))\n\n        model.add(tflayer.Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.MaxPool2D(pool_size=(2,2),strides=(2,2)))\n    \n        #This is extra layer----- \n        #model.add(tflayer.Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=tflayer.LeakyReLU(0.2)))\n        #model.add(tflayer.MaxPool2D(pool_size=(2,2),strides=(2,2)))\n        # ------------------------\n    \n        model.add(tflayer.Flatten())\n\n        model.add(tflayer.Dense(4096, activation=tflayer.LeakyReLU(0.2)))\n        model.add(tflayer.Dense(1, activation='sigmoid'))\n        # compile model\n        opt = tf.keras.optimizers.Adam(lr=0.0002, beta_1=0.5)\n        model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\n\n        return model\n    #model.add(tflayer.Dense(units=4096,activation=\"relu\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = define_vgg16_discriminator((img_size,img_size,3))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"faeture_list = ['image_name','target','tfrecord']\n\nsiim20_csv = pd.read_csv('../input/jpeg-melanoma-192x192/train.csv',usecols=faeture_list)\n#siim19_csv = pd.read_csv('../input/jpeg-isic2019-192x192/train.csv',usecols=faeture_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#siim19_csv['year'] = '2019' \nsiim20_csv['year'] = '2020'\n\n#siim_all = pd.concat([siim19_csv,siim20_csv],ignore_index = True)\n\n#train = siim_all.loc[siim_all.target == 1]\ntrain = siim20_csv.loc[siim20_csv.target == 1]\nprint('Number of Class 1 images ')\nprint(train.target.value_counts())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# REMOVE duplicate images\nfilter_train = train[train.tfrecord != -1 ]\n\nidx_list = []\nfor img_name in filter_train.image_name.values:\n    if img_name.endswith('downsampled'):\n        idx = filter_train.index[filter_train['image_name'] == img_name].to_list()\n        #print(str(idx) + str(len(idx)) + ':' +img_name )\n        if len(idx) == 1:\n            idx_list.append(idx[0])\n\nprint(len(idx_list))\nfilter_train = filter_train.drop(idx_list)\n# shuffle the rows\nfilter_train.reset_index(inplace=True)\n\nfilter_train.drop('index',axis=1)\n\nprint(filter_train.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Taking only 2020 images\nfilter_train = siim20_csv.loc[siim20_csv.target == 1]\n\n# take only 10% of data\nfilter_train = filter_train.sample(frac = 1.0)\nfilter_train.target.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n# Data access\nGCS_PATH_19 = KaggleDatasets().get_gcs_path('jpeg-isic2019-384x384')\nGCS_PATH_20 = KaggleDatasets().get_gcs_path('jpeg-melanoma-192x192')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def add_gcs_path(image_id):\n    \n    year_nb = filter_train.loc[filter_train.image_name == image_id].year.to_numpy()[0]\n    #print(year_nb)\n    GCS_PATH = ''\n    \n    if year_nb == '2019':\n        GCS_PATH = GCS_PATH_19 + '/train/' + image_id + '.jpg'\n    else:\n        GCS_PATH = GCS_PATH_20 + '/train/' + image_id + '.jpg'\n    \n    return GCS_PATH\n\ndef file_path(image_id):\n    \n    year_nb = filter_train.loc[filter_train.image_name == image_id].year.to_numpy()[0]\n    #print(year_nb)\n    GCS_PATH = ''\n    \n    if year_nb == '2019':\n        #print('19')\n        GCS_PATH = '../input/jpeg-isic2019-384x384' + '/train/' + image_id + '.jpg'\n    else:\n        #print('20')\n        GCS_PATH = '../input/jpeg-melanoma-384x384' + '/train/' + image_id + '.jpg'\n    \n    return GCS_PATH","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filter_train[\"image_path\"] = filter_train[\"image_name\"].apply(lambda x : add_gcs_path(x))\nfilter_train[\"image_jpg_id\"] = filter_train[\"image_name\"].apply(lambda x: file_path(x))\n\nprint(filter_train.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths = filter_train.image_path.values\n#val_paths   = df_val.image_path.values\n\ntrain_labels = filter_train.target\n#val_labels   = df_val.target","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    tf.random.set_seed(seed)\n    \ndef decode_image(filename, label=None, image_size=(img_size, img_size)):\n    bits = tf.io.read_file(filename)\n    image = tf.image.decode_jpeg(bits, channels=3)\n    image = tf.cast(image, tf.float32)\n    # scaling to [-1,1]\n    image = (image-127.5) / 127.5  \n    image = tf.image.resize(image, size = image_size)\n    \n    if label is None:\n        return image\n    else:\n        return image, label\n\ndef int_div_round_up(a, b):\n    return (a + b - 1) // b","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Generate real sample","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((train_paths, train_labels))\n    .map(decode_image, num_parallel_calls=AUTO)\n    #.map(data_augment, num_parallel_calls=AUTO)\n    #.map(transform, num_parallel_calls = AUTO)\n    .repeat()\n    .shuffle(512)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO))\n\nNUM_TRAINING_IMAGES = filter_train.shape[0]\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nprint('Dataset: {} training images, '.format(NUM_TRAINING_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# just a test case\n'''\nfor i in range(146):\n    step_nb = i\n    if step_nb == 0:\n        startIndex = 0\n        endIndex = BATCH_SIZE\n        print('Start Index: {} ,End Index :{} '.format(startIndex,endIndex))\n    else:\n        startIndex = endIndex\n        endIndex = startIndex + BATCH_SIZE\n        print('Start Index: {} ,End Index :{} '.format(startIndex,endIndex))\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def generate_real_samples(startIndex, endIndex, half_batch):\n    train = []\n    for filename in train_paths[startIndex:endIndex]:\n        bits = tf.io.read_file(filename)\n        image = tf.image.decode_jpeg(bits, channels=3)\n        image = tf.cast(image, tf.float32)\n        # scaling to [-1,1]\n        image = (image-127.5) / 127.5\n        train.append(image)\n        \n    train = np.array(train)\n    y = ones((half_batch, 1))\n    \n    return train, y\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#X,y = generate_real_samples(0, 4, 4)\n#print(X.shape)\n#print(X)\n#print(y)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Generate Fake data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# generate n fake samples with class labels\n# batch_size is same as BATCH_SIZE\n# It is because need to keep same number of images\ndef generate_fake_samples(batch_size):\n    \n# generate uniform random numbers in [0,1]\n    X = rand(img_size * img_size * 3 * batch_size)\n# update to have the range [-1, 1]\n    X = -1 + X * 2\n# reshape into a batch of color images\n    X = X.reshape((batch_size, img_size, img_size, 3))\n# generate 'fake' class labels (0)\n    y = zeros((batch_size, 1))\n    return X, y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train the discriminator model\n#img_dataset = train_dataset.enumerate(start=1)\n\ndef train_discriminator(model, n_iter=20, n_batch=BATCH_SIZE):\n    half_batch = int(n_batch / 2)\n    # manually enumerate epochs\n    for i in range(n_iter):\n        print('Epoch :' + str(i))\n        step_count = 0\n        for img_tuple in train_dataset.as_numpy_iterator():\n            step_count = step_count+1\n            print('Batch Number : '+str(step_count))\n            # get randomly selected 'real' samples\n            #X_real, y_real = generate_real_samples(dataset, half_batch)\n            # update discriminator on real samples\n            _, real_acc = model.train_on_batch(img_tuple[0], img_tuple[1])\n            \n            # generate 'fake' examples\n            X_fake, y_fake = generate_fake_samples(half_batch)\n            # update discriminator on fake samples\n            _, fake_acc = model.train_on_batch(X_fake, y_fake)\n            # summarize performance\n            print('>%d real=%.0f%% fake=%.0f%%' % (i+1, real_acc*100, fake_acc*100))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# define the discriminator model\ndisc_model = define_vgg16_discriminator((img_size,img_size,3))\n\n# fit the model\n#train_discriminator(disc_model)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Generator","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# define the standalone generator model\ndef define_generator(latent_dim):\n    \n    with strategy.scope():\n        \n        model = tf.keras.Sequential()\n        # same size as just above the falt layer of discriminator\n        tflayer = tf.keras.layers\n        n_nodes = 512 * 6 * 6\n        model.add(tflayer.Dense(n_nodes, input_dim=latent_dim))\n        model.add(tflayer.LeakyReLU(alpha=0.2))\n    \n        model.add(tflayer.Reshape((6, 6, 512)))\n        # upsample \n        model.add(tflayer.Conv2DTranspose(512, (4,4), strides=(2,2), padding='same'))\n        model.add(tflayer.LeakyReLU(alpha=0.2))\n\n        # upsample \n        model.add(tflayer.Conv2DTranspose(512, (4,4), strides=(2,2), padding='same'))\n        model.add(tflayer.LeakyReLU(alpha=0.2))\n\n        # upsample \n        model.add(tflayer.Conv2DTranspose(256, (4,4), strides=(2,2), padding='same'))\n        model.add(tflayer.LeakyReLU(alpha=0.2))\n    \n        # upsample \n        #model.add(tflayer.Conv2DTranspose(256, (4,4), strides=(2,2), padding='same'))\n        #model.add(tflayer.LeakyReLU(alpha=0.2))\n    \n        # upsample \n        model.add(tflayer.Conv2DTranspose(128, (4,4), strides=(2,2), padding='same'))\n        model.add(tflayer.LeakyReLU(alpha=0.2))\n    \n        # upsample \n        model.add(tflayer.Conv2DTranspose(64, (4,4), strides=(2,2), padding='same'))\n        model.add(tflayer.LeakyReLU(alpha=0.2))\n    \n        # output layer\n        model.add(tflayer.Conv2D(3, (3,3), activation='tanh', padding='same'))\n        return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create Generator model object","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"latent_dim = 4096\ngen_model = define_generator(latent_dim)\ngen_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# generate points in latent space as input for the generator\ndef generate_latent_points(latent_dim, n_samples):\n    # generate points in the latent space\n    x_input = randn(latent_dim * n_samples)\n    # reshape into a batch of inputs for the network\n    x_input = x_input.reshape(n_samples, latent_dim)\n    return x_input\n\n# use the generator to generate n fake examples, with class labels\ndef generate_fake_samples(g_model, latent_dim, n_samples):\n    # generate points in latent space\n    x_input = generate_latent_points(latent_dim, n_samples)\n    # predict outputs\n    X = g_model.predict(x_input)\n    # create 'fake' class labels (0)\n    y = zeros((n_samples, 1))\n    return X, y","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# View image before train model\nall image will be grey square","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib import pyplot\n\nX, _ = generate_fake_samples(gen_model, latent_dim, BATCH_SIZE)\n\nX = (X + 1) / 2.0\n\n# plot the generated samples\nfor i in range(BATCH_SIZE):\n    # define subplot\n    pyplot.subplot(7, 7, 1 + i)\n    # turn off axis labels\n    pyplot.axis('off')\n    # plot single image\n    pyplot.imshow(X[i])\n# show the figure\npyplot.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training the model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# define the combined generator and discriminator model, for updating the generator\ndef define_gan(g_model, d_model):\n    with strategy.scope():\n        # make weights in the discriminator not trainable\n        d_model.trainable = False\n        # connect them\n        model = tf.keras.Sequential()\n        # add generator\n        model.add(g_model)\n        # add the discriminator\n        model.add(d_model)\n        # compile model\n        opt = tf.keras.optimizers.Adam(lr=0.0002, beta_1=0.5)\n        model.compile(loss='binary_crossentropy', optimizer=opt)\n        return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create GAN model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    gan_model = define_gan(gen_model, disc_model)\n    # summarize gan model\n    gan_model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# View model\n\n* Input is 4096 and output a image of 192x192x3","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.vis_utils import plot_model\n# plot gan model\nplot_model(gan_model, to_file='gan_plot.png', show_shapes=True, show_layer_names=True)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training the model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# train the generator and discriminator\ndef train(g_model, d_model, gan_model, latent_dim, n_epochs=1, n_batch=128):\n    step_per_epoch = int(filter_train.shape[0] / n_batch)\n    half_batch = int(n_batch / 2)\n    # manually enumerate epochs\n    for i in range(n_epochs):\n        # enumerate batches over the training set\n        for j in range(step_per_epoch):\n            # get randomly selected 'real' samples\n            step_nb = j\n            if step_nb == 0:\n                startIndex = 0\n                endIndex = half_batch\n                #print('Epoch: {} / Start Index: {} | End Index :{} '.format(i,startIndex,endIndex))\n            else:\n                startIndex = endIndex\n                endIndex = startIndex + half_batch\n                #print('Epoch: {} / Start Index: {} ,End Index :{} '.format(i, startIndex,endIndex))\n        \n            # get real images\n            X_real, y_real = generate_real_samples(startIndex, endIndex, half_batch)\n            # update discriminator model weights\n            d_loss1, _ = d_model.train_on_batch(X_real, y_real)\n\n            # generate 'fake' examples\n            X_fake, y_fake = generate_fake_samples(g_model, latent_dim, half_batch)\n            \n            # update discriminator model weights\n            d_loss2, _ = d_model.train_on_batch(X_fake, y_fake)\n            \n            # prepare points in latent space as input for the generator\n            X_gan = generate_latent_points(latent_dim, n_batch)\n            \n            # create inverted labels for the fake samples\n            y_gan = ones((n_batch, 1))\n            \n            # update the generator via the discriminator's error\n            g_loss = gan_model.train_on_batch(X_gan, y_gan)\n            \n            # summarize loss on this batch\n            print('>%d, %d/%d, d1=%.3f, d2=%.3f g=%.3f' %\n                (i+1, j+1, step_per_epoch, d_loss1, d_loss2, g_loss))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# Start training of model\ntrain(gen_model, disc_model, gan_model, latent_dim, n_epochs=3, n_batch=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gen_model.save('generator_model_192.h5')\ndisc_model.save('discriminator_model_192.h5')\ngan_model.save('gan_model_192.h5')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image Generator","execution_count":null},{"metadata":{"trusted":true},"cell_type":"markdown","source":"from tensorflow.keras.models import load_model\nfrom matplotlib import pyplot\n\n# load model here../input/siimganmodels/generator_model.h5\nimg_gen_model = load_model('../input/siimganmodels/generator_model.h5',compile=False,\n                                custom_objects={'LeakyReLU': tf.keras.layers.LeakyReLU()})","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# all 0s\nvector = np.asarray([[0.5 for _ in range(4096)]])","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# generate image\nX = img_gen_model.predict(vector)\n# scale from [-1,1] to [0,1]\nX = (X + 1) / 2.0\n\nprint(X)\n# plot the result\npyplot.imshow(X[0, :, :])\npyplot.show()","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}