{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install git+https://github.com/tensorflow/examples.git\nfrom tensorflow_examples.models.pix2pix import pix2pix\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport os\nfrom PIL import Image\nimport time\nimport matplotlib.pyplot as plt\nimport shutil\nfrom IPython.display import clear_output\n\nAUTOTUNE = tf.data.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:22.722519Z","iopub.execute_input":"2023-07-08T04:01:22.722898Z","iopub.status.idle":"2023-07-08T04:01:39.706623Z","shell.execute_reply.started":"2023-07-08T04:01:22.722867Z","shell.execute_reply":"2023-07-08T04:01:39.705470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmonet = []\n\nfor dirname, __, filenames in os.walk('/kaggle/input/gan-getting-started/monet_tfrec'):\n    for filename in filenames:\n        monet.append(os.path.join(dirname, filename))\n\nphoto = []\n\nfor dirname, __, filenames in os.walk('/kaggle/input/gan-getting-started/photo_tfrec'):\n    for filename in filenames:\n        photo.append(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.710520Z","iopub.execute_input":"2023-07-08T04:01:39.710895Z","iopub.status.idle":"2023-07-08T04:01:39.723356Z","shell.execute_reply.started":"2023-07-08T04:01:39.710861Z","shell.execute_reply":"2023-07-08T04:01:39.722364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_photo_ds = tf.data.TFRecordDataset(photo)\ntrain_monet_ds = tf.data.TFRecordDataset(monet)\ndel monet\ndel photo\n(train_monet_ds, train_photo_ds)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.724764Z","iopub.execute_input":"2023-07-08T04:01:39.725094Z","iopub.status.idle":"2023-07-08T04:01:39.772863Z","shell.execute_reply.started":"2023-07-08T04:01:39.725063Z","shell.execute_reply":"2023-07-08T04:01:39.771984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''for raw_record in train_monet_ds.take(1):\n    example = tf.train.Example()\n    example.ParseFromString(raw_record.numpy())\n    print(example)'''","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.775529Z","iopub.execute_input":"2023-07-08T04:01:39.775849Z","iopub.status.idle":"2023-07-08T04:01:39.782140Z","shell.execute_reply.started":"2023-07-08T04:01:39.775810Z","shell.execute_reply":"2023-07-08T04:01:39.781049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''import cv2\n#img0 = cv2.imread('/kaggle/input/gan-getting-started/monet_jpg/011835cfbf.jpg')\nimg1= cv2.imread('/kaggle/input/gan-getting-started/photo_jpg/000ded5c41.jpg')\n#_ = plt.imshow(img0)\n__ = plt.imshow(img1)\nplt.show()\nprint(img1.shape)'''","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.783662Z","iopub.execute_input":"2023-07-08T04:01:39.784163Z","iopub.status.idle":"2023-07-08T04:01:39.792924Z","shell.execute_reply.started":"2023-07-08T04:01:39.784128Z","shell.execute_reply":"2023-07-08T04:01:39.791922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BUFFER_SIZE = 1000\n#BATCH_SIZE = 1\nIMG_WIDTH = 256\nIMG_HEIGHT = 256","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.794302Z","iopub.execute_input":"2023-07-08T04:01:39.794879Z","iopub.status.idle":"2023-07-08T04:01:39.805632Z","shell.execute_reply.started":"2023-07-08T04:01:39.794845Z","shell.execute_reply":"2023-07-08T04:01:39.804703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def random_crop(image):\n    cropped_image = tf.image.random_crop(\n        image, size=[IMG_HEIGHT, IMG_WIDTH, 3])\n\n    return cropped_image","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.807058Z","iopub.execute_input":"2023-07-08T04:01:39.807584Z","iopub.status.idle":"2023-07-08T04:01:39.817610Z","shell.execute_reply.started":"2023-07-08T04:01:39.807553Z","shell.execute_reply":"2023-07-08T04:01:39.816697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# normalizing the images to [-1, 1]\ndef normalize(image):\n    image = tf.cast(image, tf.float32)\n    image = (image / 127.5) - 1\n    return image","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.818922Z","iopub.execute_input":"2023-07-08T04:01:39.820076Z","iopub.status.idle":"2023-07-08T04:01:39.828592Z","shell.execute_reply.started":"2023-07-08T04:01:39.820044Z","shell.execute_reply":"2023-07-08T04:01:39.827529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def random_jitter(image):\n    # resizing to 286 x 286 x 3\n    image = tf.image.resize(image, [286, 286],\n                            method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n\n    # randomly cropping to 256 x 256 x 3\n    image = random_crop(image)\n\n    # random mirroring\n    image = tf.image.random_flip_left_right(image)\n  \n    return image","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.830121Z","iopub.execute_input":"2023-07-08T04:01:39.831230Z","iopub.status.idle":"2023-07-08T04:01:39.845566Z","shell.execute_reply.started":"2023-07-08T04:01:39.831198Z","shell.execute_reply":"2023-07-08T04:01:39.843818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess_image_train(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    #print(image)\n    image = random_jitter(image)\n    image = normalize(image)\n    return image","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.854210Z","iopub.execute_input":"2023-07-08T04:01:39.854863Z","iopub.status.idle":"2023-07-08T04:01:39.859975Z","shell.execute_reply.started":"2023-07-08T04:01:39.854830Z","shell.execute_reply":"2023-07-08T04:01:39.858973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess_image_test(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = normalize(image)\n    return image","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.861573Z","iopub.execute_input":"2023-07-08T04:01:39.862234Z","iopub.status.idle":"2023-07-08T04:01:39.873013Z","shell.execute_reply.started":"2023-07-08T04:01:39.862198Z","shell.execute_reply":"2023-07-08T04:01:39.872038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a description of the features.\nfeature_description = {\n    'image': tf.io.FixedLenFeature([], tf.string),\n    #'image_name': tf.io.FixedLenFeature([], tf.string, default_value=''),\n    #'target': tf.io.FixedLenFeature([], tf.string, default_value=''),\n}\n\ndef _parse_train_function(example_proto):\n    # Parse the input `tf.Example` proto using the dictionary above.\n    example = tf.io.parse_single_example(example_proto, feature_description)\n    #print(example['image'])\n    return preprocess_image_train(example['image'])\ndef _parse_test_function(example_proto):\n    # Parse the input `tf.Example` proto using the dictionary above.\n    example = tf.io.parse_single_example(example_proto, feature_description)\n    return preprocess_image_test(example['image'])","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.874463Z","iopub.execute_input":"2023-07-08T04:01:39.875182Z","iopub.status.idle":"2023-07-08T04:01:39.885858Z","shell.execute_reply.started":"2023-07-08T04:01:39.875150Z","shell.execute_reply":"2023-07-08T04:01:39.884847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ds = train_photo_ds.map(_parse_train_function, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE)\ntrain_monet_ds = train_monet_ds.map(_parse_train_function, num_parallel_calls=AUTOTUNE).shuffle(BUFFER_SIZE)\n#test_ds = train_photo_ds.map(_parse_test_function, num_parallel_calls=AUTOTUNE).map(lambda x, y:x)\n(train_ds, train_monet_ds)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:39.887437Z","iopub.execute_input":"2023-07-08T04:01:39.888119Z","iopub.status.idle":"2023-07-08T04:01:40.179297Z","shell.execute_reply.started":"2023-07-08T04:01:39.888086Z","shell.execute_reply":"2023-07-08T04:01:40.177577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_photo = next(iter(train_ds))\nsample_monet = next(iter(train_monet_ds))\ndisplay_list = [sample_photo, sample_monet]\nfor i in range(2):\n    plt.subplot(1, 2, i+1)\n    plt.imshow(display_list[i])\n    plt.axis('off')\nplt.show()\ndel sample_monet","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:40.182679Z","iopub.execute_input":"2023-07-08T04:01:40.183795Z","iopub.status.idle":"2023-07-08T04:01:44.398976Z","shell.execute_reply.started":"2023-07-08T04:01:40.183736Z","shell.execute_reply":"2023-07-08T04:01:44.398073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"OUTPUT_CHANNELS = 3","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:44.400302Z","iopub.execute_input":"2023-07-08T04:01:44.401207Z","iopub.status.idle":"2023-07-08T04:01:44.405432Z","shell.execute_reply.started":"2023-07-08T04:01:44.401172Z","shell.execute_reply":"2023-07-08T04:01:44.404562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def downsample(filters, size, apply_batchnorm=True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n\n    result = tf.keras.Sequential()\n    result.add(\n      tf.keras.layers.Conv2D(filters, size, strides=2, padding='same',\n                             kernel_initializer=initializer, use_bias=False))\n\n    if apply_batchnorm:\n        result.add(tf.keras.layers.BatchNormalization())\n \n    result.add(tf.keras.layers.LeakyReLU())\n\n    return result","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:44.406811Z","iopub.execute_input":"2023-07-08T04:01:44.407849Z","iopub.status.idle":"2023-07-08T04:01:44.417802Z","shell.execute_reply.started":"2023-07-08T04:01:44.407804Z","shell.execute_reply":"2023-07-08T04:01:44.417134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def upsample(filters, size, apply_dropout=False):\n    initializer = tf.random_normal_initializer(0., 0.02)\n\n    result = tf.keras.Sequential()\n    result.add(\n      tf.keras.layers.Conv2DTranspose(filters, size, strides=2,\n                                    padding='same',\n                                    kernel_initializer=initializer,\n                                    use_bias=False))\n\n    result.add(tf.keras.layers.BatchNormalization())\n\n    if apply_dropout:\n        result.add(tf.keras.layers.Dropout(0.5))\n\n    result.add(tf.keras.layers.LeakyReLU())\n\n    return result","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:44.419194Z","iopub.execute_input":"2023-07-08T04:01:44.420329Z","iopub.status.idle":"2023-07-08T04:01:44.427950Z","shell.execute_reply.started":"2023-07-08T04:01:44.420287Z","shell.execute_reply":"2023-07-08T04:01:44.427377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = tf.keras.layers.Input(shape=[256, 256, 3])\n\n    down_stack = [\n    downsample(64, 4, apply_batchnorm=False),  # (batch_size, 128, 128, 64)\n    downsample(128, 4),  # (batch_size, 64, 64, 128)\n    downsample(256, 4),  # (batch_size, 32, 32, 256)\n    downsample(512, 4),  # (batch_size, 16, 16, 512)\n    downsample(512, 4),  # (batch_size, 8, 8, 512)\n    downsample(512, 4),  # (batch_size, 4, 4, 512)\n    downsample(512, 4),  # (batch_size, 2, 2, 512)\n    downsample(512, 4),  # (batch_size, 1, 1, 512)\n  ]\n\n    up_stack = [\n    upsample(512, 4, apply_dropout=True),  # (batch_size, 2, 2, 1024)\n    upsample(512, 4, apply_dropout=True),  # (batch_size, 4, 4, 1024)\n    upsample(512, 4, apply_dropout=True),  # (batch_size, 8, 8, 1024)\n    upsample(512, 4),  # (batch_size, 16, 16, 1024)\n    upsample(256, 4),  # (batch_size, 32, 32, 512)\n    upsample(128, 4),  # (batch_size, 64, 64, 256)\n    upsample(64, 4),  # (batch_size, 128, 128, 128)\n  ]\n\n    initializer = tf.random_normal_initializer(0., 0.02)\n    last = tf.keras.layers.Conv2DTranspose(OUTPUT_CHANNELS, 4,\n                                          strides=2,\n                                         padding='same',\n                                         kernel_initializer=initializer,\n                                         activation='tanh')  # (batch_size, 256, 256, 3)\n\n    x = inputs\n\n    # Downsampling through the model\n    skips = []\n    for down in down_stack:\n        x = down(x)\n        skips.append(x)\n\n    skips = reversed(skips[:-1])\n\n    # Upsampling and establishing the skip connections\n    for up, skip in zip(up_stack, skips):\n        x = up(x)\n        x = tf.keras.layers.Concatenate()([x, skip])\n\n    x = last(x)\n\n    return tf.keras.Model(inputs=inputs, outputs=x)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:44.429208Z","iopub.execute_input":"2023-07-08T04:01:44.430069Z","iopub.status.idle":"2023-07-08T04:01:44.443986Z","shell.execute_reply.started":"2023-07-08T04:01:44.430030Z","shell.execute_reply":"2023-07-08T04:01:44.443270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"generator_g = Generator()\ngenerator_f = Generator()\n\ndiscriminator_x = pix2pix.discriminator(norm_type='instancenorm', target=False)\ndiscriminator_y = pix2pix.discriminator(norm_type='instancenorm', target=False)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:44.446272Z","iopub.execute_input":"2023-07-08T04:01:44.447297Z","iopub.status.idle":"2023-07-08T04:01:45.974276Z","shell.execute_reply.started":"2023-07-08T04:01:44.447264Z","shell.execute_reply":"2023-07-08T04:01:45.973321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.plot_model(generator_g, show_shapes=True, dpi=64)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:45.975808Z","iopub.execute_input":"2023-07-08T04:01:45.976187Z","iopub.status.idle":"2023-07-08T04:01:46.174404Z","shell.execute_reply.started":"2023-07-08T04:01:45.976147Z","shell.execute_reply":"2023-07-08T04:01:46.173462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.plot_model(discriminator_x, show_shapes=True, dpi=64)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.175971Z","iopub.execute_input":"2023-07-08T04:01:46.176665Z","iopub.status.idle":"2023-07-08T04:01:46.254844Z","shell.execute_reply.started":"2023-07-08T04:01:46.176630Z","shell.execute_reply":"2023-07-08T04:01:46.253943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LAMBDA = 10\n\nloss_obj = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n\ndef discriminator_loss(real, generated):\n    real_loss = loss_obj(tf.ones_like(real), real)\n\n    generated_loss = loss_obj(tf.zeros_like(generated), generated)\n  \n    total_disc_loss = real_loss + generated_loss\n\n    return total_disc_loss * 0.5\n\ndef generator_loss(generated):\n    return loss_obj(tf.ones_like(generated), generated)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.256272Z","iopub.execute_input":"2023-07-08T04:01:46.256803Z","iopub.status.idle":"2023-07-08T04:01:46.264037Z","shell.execute_reply.started":"2023-07-08T04:01:46.256762Z","shell.execute_reply":"2023-07-08T04:01:46.263187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def calc_cycle_loss(real_image, cycled_image):\n    loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))\n\n    return LAMBDA * loss1\ndef identity_loss(real_image, same_image):\n    loss = tf.reduce_mean(tf.abs(real_image - same_image))\n    return LAMBDA * 0.5 * loss","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.265539Z","iopub.execute_input":"2023-07-08T04:01:46.265892Z","iopub.status.idle":"2023-07-08T04:01:46.276756Z","shell.execute_reply.started":"2023-07-08T04:01:46.265859Z","shell.execute_reply":"2023-07-08T04:01:46.275945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"generator_g_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\ngenerator_f_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n\ndiscriminator_x_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\ndiscriminator_y_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.278800Z","iopub.execute_input":"2023-07-08T04:01:46.279888Z","iopub.status.idle":"2023-07-08T04:01:46.293755Z","shell.execute_reply.started":"2023-07-08T04:01:46.279855Z","shell.execute_reply":"2023-07-08T04:01:46.292851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint_path = \"./checkpoints/train\"\n\nckpt = tf.train.Checkpoint(generator_g=generator_g,\n                           generator_f=generator_f,\n                           discriminator_x=discriminator_x,\n                           discriminator_y=discriminator_y,\n                           generator_g_optimizer=generator_g_optimizer,\n                           generator_f_optimizer=generator_f_optimizer,\n                           discriminator_x_optimizer=discriminator_x_optimizer,\n                           discriminator_y_optimizer=discriminator_y_optimizer)\n\nckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=1)\n\n# if a checkpoint exists, restore the latest checkpoint.\nif ckpt_manager.latest_checkpoint:\n    ckpt.restore(ckpt_manager.latest_checkpoint)\n    print ('Latest checkpoint restored!!')","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.295029Z","iopub.execute_input":"2023-07-08T04:01:46.295735Z","iopub.status.idle":"2023-07-08T04:01:46.310479Z","shell.execute_reply.started":"2023-07-08T04:01:46.295701Z","shell.execute_reply":"2023-07-08T04:01:46.309470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 164","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.311665Z","iopub.execute_input":"2023-07-08T04:01:46.312391Z","iopub.status.idle":"2023-07-08T04:01:46.318255Z","shell.execute_reply.started":"2023-07-08T04:01:46.312356Z","shell.execute_reply":"2023-07-08T04:01:46.317185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def generate_images(model, test_input):\n    prediction = model(test_input)\n\n    plt.figure(figsize=(12, 12))\n\n    display_list = [test_input[0], prediction[0]]\n    title = ['Input Image', 'Predicted Image']\n  \n    for i in range(2):\n        plt.subplot(1, 2, i+1)\n        plt.title(title[i])\n        # getting the pixel values between [0, 1] to plot it.\n        plt.imshow(display_list[i] * 0.5 + 0.5)\n        plt.axis('off')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.319859Z","iopub.execute_input":"2023-07-08T04:01:46.320198Z","iopub.status.idle":"2023-07-08T04:01:46.330230Z","shell.execute_reply.started":"2023-07-08T04:01:46.320167Z","shell.execute_reply":"2023-07-08T04:01:46.329122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"@tf.function\ndef train_step(real_x, real_y):\n    # persistent is set to True because the tape is used more than\n    # once to calculate the gradients.\n    with tf.GradientTape(persistent=True) as tape:\n    # Generator G translates X -> Y\n    # Generator F translates Y -> X.\n\n        fake_y = generator_g(real_x, training=True)\n        cycled_x = generator_f(fake_y, training=True)\n\n        fake_x = generator_f(real_y, training=True)\n        cycled_y = generator_g(fake_x, training=True)\n\n        # same_x and same_y are used for identity loss.\n        same_x = generator_f(real_x, training=True)\n        same_y = generator_g(real_y, training=True)\n\n        disc_real_x = discriminator_x(real_x, training=True)\n        disc_real_y = discriminator_y(real_y, training=True)\n\n        disc_fake_x = discriminator_x(fake_x, training=True)\n        disc_fake_y = discriminator_y(fake_y, training=True)\n\n        # calculate the loss\n        gen_g_loss = generator_loss(disc_fake_y)\n        gen_f_loss = generator_loss(disc_fake_x)\n\n        total_cycle_loss = calc_cycle_loss(real_x, cycled_x) + calc_cycle_loss(real_y, cycled_y)\n \n        # Total generator loss = adversarial loss + cycle loss\n        total_gen_g_loss = gen_g_loss + total_cycle_loss + identity_loss(real_y, same_y)\n        total_gen_f_loss = gen_f_loss + total_cycle_loss + identity_loss(real_x, same_x)\n   \n        disc_x_loss = discriminator_loss(disc_real_x, disc_fake_x)\n        disc_y_loss = discriminator_loss(disc_real_y, disc_fake_y)\n\n    # Calculate the gradients for generator and discriminator\n    generator_g_gradients = tape.gradient(total_gen_g_loss, \n                                        generator_g.trainable_variables)\n    generator_f_gradients = tape.gradient(total_gen_f_loss, \n                                        generator_f.trainable_variables)\n\n    discriminator_x_gradients = tape.gradient(disc_x_loss, \n                                            discriminator_x.trainable_variables)\n    discriminator_y_gradients = tape.gradient(disc_y_loss, \n                                            discriminator_y.trainable_variables)\n\n    # Apply the gradients to the optimizer\n    generator_g_optimizer.apply_gradients(zip(generator_g_gradients, \n                                            generator_g.trainable_variables))\n\n    generator_f_optimizer.apply_gradients(zip(generator_f_gradients, \n                                              generator_f.trainable_variables))\n  \n    discriminator_x_optimizer.apply_gradients(zip(discriminator_x_gradients,\n                                                  discriminator_x.trainable_variables))\n  \n    discriminator_y_optimizer.apply_gradients(zip(discriminator_y_gradients,\n                                                  discriminator_y.trainable_variables))\n  ","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.337315Z","iopub.execute_input":"2023-07-08T04:01:46.337601Z","iopub.status.idle":"2023-07-08T04:01:46.353846Z","shell.execute_reply.started":"2023-07-08T04:01:46.337578Z","shell.execute_reply":"2023-07-08T04:01:46.350224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for epoch in range(EPOCHS):\n    start = time.time()\n\n    n = 0\n    for image_x, image_y in tf.data.Dataset.zip((train_ds,\n                                                 train_monet_ds.repeat(8))).shuffle(256).batch(3).take(250):\n        '''if n == 0:\n            print(image_x)'''\n        train_step(image_x, image_y)\n        if n % 10 == 0:\n            print ('.', end='')\n        n+=1\n\n    clear_output(wait=True)\n    # 使用一致的图像，以便模型的进度清晰可见。\n    generate_images(generator_g, tf.reshape(sample_photo,[1, 256, 256, 3]))\n\n    if (epoch + 1) % 100== 0:\n        ckpt_save_path = ckpt_manager.save()\n        print ('Saving checkpoint for epoch {} at {}'.format(epoch+1,\n                                                             ckpt_save_path))\n\n    print ('Time taken for epoch {} is {} sec\\n'.format(epoch + 1,\n                                                        time.time()-start))\n    del n","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:01:46.357382Z","iopub.execute_input":"2023-07-08T04:01:46.357643Z","iopub.status.idle":"2023-07-08T04:06:43.383448Z","shell.execute_reply.started":"2023-07-08T04:01:46.357620Z","shell.execute_reply":"2023-07-08T04:06:43.381926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = train_photo_ds.map(_parse_test_function, num_parallel_calls=AUTOTUNE)\nos.makedirs(\"/kaggle/working/images\", exist_ok=True)\nidx = 0\nfor i in test_ds.batch(64).take(110):\n    p = generator_g.predict(i) * 0.5 + 0.5\n    #print(p)\n    for j in p:\n        plt.imsave('/kaggle/working/images/{}.jpg'.format(idx), j)\n        idx += 1\nzip_name = shutil.make_archive('/kaggle/working/images', 'zip', '/kaggle/working/images')","metadata":{"execution":{"iopub.status.busy":"2023-07-08T04:06:43.384960Z","iopub.status.idle":"2023-07-08T04:06:43.385793Z","shell.execute_reply.started":"2023-07-08T04:06:43.385525Z","shell.execute_reply":"2023-07-08T04:06:43.385550Z"},"trusted":true},"execution_count":null,"outputs":[]}]}